--========================================
-- CTLD Initialization & Core Settings
--========================================

local Delay_sec = 5
timer.scheduleFunction(function ()

_SETTINGS:SetPlayerMenuOff()

--local my_ctld = CTLD:New(coalition.side.BLUE,{"Helicargo","CH.47","CH%-47","FCOW","Hercules","Bronco"},"Lufttransportbrigade I")
my_ctld = CTLD:New(coalition.side.BLUE,{"Helicargo","CH.47","CH%-47","FCOW","Hercules","Bronco"},"Lufttransportbrigade I")

my_ctld.useprefix = true
my_ctld.dropcratesanywhere = true
my_ctld.forcehoverload = false -- Chinook must-have option
my_ctld.allowcratepickupagain = true
my_ctld.nobuildinloadzones = false -- Chinook must-have option
my_ctld.movecratesbeforebuild = false -- Chinook must-have option - Use Ground Crew menu to load/unload.. If False, crates inside heli will also build!!
my_ctld.movetroopstowpzone = true
my_ctld.enableChinookGCLoading = true -- Chinook must-have option
my_ctld.hoverautoloading = false -- Chinook must-have options
my_ctld.enableslingload = true -- Chinook must-have option
my_ctld.pilotmustopendoors = false
my_ctld.CrateDistance = 200 -- List and Load crates in this radius only.
my_ctld.PackDistance = 200 -- Pack crates in this radius only
my_ctld.placeCratesAhead = false -- place crates straight ahead of the helicopter, in a random way. If true, crates are more neatly sorted.
my_ctld.usesubcats = true
my_ctld.buildtime = 10
my_ctld.basetype = "uh1h_cargo"
my_ctld.enableHercules = true
my_ctld.ChinookTroopCircleRadius = 20 -- Radius for troops dropping in a nice circle. Adjust to your planned squad size for the Chinook.
my_ctld.onestepmenu = true -- When set to true, the menu will create Drop and build, Get and load, Pack and remove, Pack and load, Pack only. it will be a 1 step solution.
my_ctld:__Start(5)

-- Available Crate types

-- Ammo box (type "ammo_crate")
-- M117 bomb crate (type name "m117_cargo")
-- Dual shell fuel barrels (type name "barrels")
-- UH-1H net (type name "uh1h_cargo")

--========================================
-- CTLD Troop Cargo Definitions
--========================================

-- Troops   10 = Number of Troops 80 = Weight of each troop nil = unlimited in stock replace with stock levels as required

--- Troops ---
my_ctld:AddTroopsCargo("Anti-Tank (10)",{"Anti-Tank"},CTLD_CARGO.Enum.TROOPS,10,80,nil,"Anti-Tank")
my_ctld:AddTroopsCargo("Anti-Air (12)",{"Anti-Air"},CTLD_CARGO.Enum.TROOPS,12,80,nil,"Anti-Air")
my_ctld:AddTroopsCargo("Marines (10)",{"Marines"},CTLD_CARGO.Enum.TROOPS,10,80,nil,"Marines")
my_ctld:AddTroopsCargo("Mortar (3)",{"Mortar"},CTLD_CARGO.Enum.TROOPS,10,80,nil,"Mortar")
my_ctld:AddTroopsCargo("JTAC-Ground (10)",{"JTAC-Ground"},CTLD_CARGO.Enum.TROOPS,10,80,nil,"JTAC")
my_ctld:AddTroopsCargo("Wrenches (4)",{"Engineers"},CTLD_CARGO.Enum.ENGINEERS,4,80,nil,"Engineers")
my_ctld.EngineerSearch = 2000 -- teams will search for crates in this radius.

--========================================
-- CTLD Vehicle Cargo - MBT & IFV
--========================================

--- MBT & Infantry Fighting Vechicles ---
my_ctld:AddCratesCargo("Challenger 2 (4)",{"Challenger 2"},CTLD_CARGO.Enum.VEHICLE,4,1000,nil,"MBT/IFV")
my_ctld:AddCratesCargo("Leopard 2 (4)",{"Leopard 2"},CTLD_CARGO.Enum.VEHICLE,4,1000,nil,"MBT/IFV")
my_ctld:AddCratesCargo("M1 Abrams (4)",{"M1 Abrams"},CTLD_CARGO.Enum.VEHICLE,4,1000,nil,"MBT/IFV")
my_ctld:AddCratesCargo("Marder IFV (2)",{"Marder IFV"},CTLD_CARGO.Enum.VEHICLE,2,500,nil,"MBT/IFV")
my_ctld:AddCratesCargo("Warrior IFV (2)",{"Warrior IFV"},CTLD_CARGO.Enum.VEHICLE,2,500,nil,"MBT/IFV")
my_ctld:AddCratesCargo("HMV Gun (1)",{"HMV Gun"},CTLD_CARGO.Enum.VEHICLE,1,500,nil,"MBT/IFV")
my_ctld:AddCratesCargo("Stryker IFV (2)",{"Stryker IFV"},CTLD_CARGO.Enum.VEHICLE,2,500,nil,"MBT/IFV")
my_ctld:AddCratesCargo("Bradley IFV (2)",{"Bradley IFV"},CTLD_CARGO.Enum.VEHICLE,2,500,nil,"MBT/IFV")
-- my_ctld:AddCratesCargo("Humvee (2)",{"Humvee"},CTLD_CARGO.Enum.VEHICLE,2,1000,nil,"MBT/IFV")

--========================================
-- CTLD Vehicle Cargo - Artillery
--========================================

--- Artillery ---
my_ctld:AddCratesCargo("Paladin (4)",{"Paladin"},CTLD_CARGO.Enum.VEHICLE,4,1000,nil,"Artillery")
my_ctld:AddCratesCargo("Firtina (4)",{"Firtina"},CTLD_CARGO.Enum.VEHICLE,4,1000,nil,"Artillery")
my_ctld:AddCratesCargo("Excalibur (4)",{"Excalibur"},CTLD_CARGO.Enum.VEHICLE,4,1000,nil,"Artillery")
my_ctld:AddCratesCargo("MLRS 270 (4)",{"MLRS 270"},CTLD_CARGO.Enum.VEHICLE,4,1000,nil,"Artillery")
my_ctld:AddCratesCargo("L118 (4)",{"L118"},CTLD_CARGO.Enum.VEHICLE,4,1000,nil,"Artillery")

--========================================
-- CTLD Vehicle Cargo - Anti-Aircraft
--========================================

--- Anti Aircraft ---
my_ctld:AddCratesCargo("Roland ADS (2)",{"Roland ADS"},CTLD_CARGO.Enum.VEHICLE,2,500,nil,"Anti-Air")
my_ctld:AddCratesCargo("Gepard (2)",{"Gepard"},CTLD_CARGO.Enum.VEHICLE,2,500,nil,"Anti-Air")
my_ctld:AddCratesCargo("Vulcan (2)",{"Vulcan"},CTLD_CARGO.Enum.VEHICLE,2,500,nil,"Anti-Air")
my_ctld:AddCratesCargo("Avenger (2)",{"Avenger"},CTLD_CARGO.Enum.VEHICLE,2,500,nil,"Anti-Air")
my_ctld:AddCratesCargo("C-RAM (3)",{"C-RAM"},CTLD_CARGO.Enum.VEHICLE,3,500,nil,"Anti-Air")

--========================================
-- CTLD Vehicle & Troop Cargo - JTAC Units
--========================================

--- JTAC ---
my_ctld:AddCratesCargo("JTAC HMV Scout (1)",{"JTAC HMV Scout"},CTLD_CARGO.Enum.VEHICLE,1,500,nil,"JTAC")
my_ctld:AddCratesCargo("JTAC HMV ATGM (1)",{"JTAC HMV ATGM"},CTLD_CARGO.Enum.VEHICLE,1,500,nil,"JTAC")
my_ctld:AddCratesCargo("JTAC Stryker (2)",{"JTAC Stryker"},CTLD_CARGO.Enum.VEHICLE,2,500,nil,"JTAC")
my_ctld:AddCratesCargo("JTAC Warrior (2)",{"JTAC Warrior"},CTLD_CARGO.Enum.VEHICLE,2,500,nil,"JTAC")
my_ctld:AddCratesCargo("JTAC Trooper (1)",{"JTAC Trooper"},CTLD_CARGO.Enum.TROOPS,1,500,nil,"JTAC")
my_ctld:AddTroopsCargo("JTAC Trooper (10)",{"JTAC Trooper"},CTLD_CARGO.Enum.TROOPS,10,80,nil,"JTAC")
my_ctld:AddCratesCargo("JTAC Bradley (2)",{"JTAC Bradley"},CTLD_CARGO.Enum.VEHICLE,2,500,nil,"JTAC")

--========================================
-- CTLD SAM Site Cargo - Small Systems
--========================================

--- SAM Site Small ---
my_ctld:AddCratesCargo("NASAM C2 (1)",{"NASAM C2"},CTLD_CARGO.Enum.VEHICLE,1,2000,nil,"SAM-Small")
my_ctld:AddCratesCargo("NASAM SR (1)",{"NASAM SR"},CTLD_CARGO.Enum.VEHICLE,1,2000,nil,"SAM-Small")
my_ctld:AddCratesCargo("NASAM 120C (1)",{"NASAM 120C"},CTLD_CARGO.Enum.VEHICLE,1,2000,nil,"SAM-Small")
my_ctld:AddCratesCargo("Rapier BF TR (1)",{"Rapier BF TR"},CTLD_CARGO.Enum.VEHICLE,1,2000,nil,"SAM-Small")
my_ctld:AddCratesCargo("Rapier TR (1)",{"Rapier TR"},CTLD_CARGO.Enum.VEHICLE,1,2000,nil,"SAM-Small")
my_ctld:AddCratesCargo("Rapier LN (1)",{"Rapier LN"},CTLD_CARGO.Enum.VEHICLE,1,2000,nil,"SAM-Small")

--========================================
-- CTLD SAM Site Cargo - Large Systems
--========================================

--- SAM Site Large --
my_ctld:AddCratesCargo("Hawk PCP (1)",{"Hawk PCP"},CTLD_CARGO.Enum.VEHICLE,1,1000,nil,"SAM-Large")
my_ctld:AddCratesCargo("Hawk CWAR (1)",{"Hawk CWAR"},CTLD_CARGO.Enum.VEHICLE,1,1000,nil,"SAM-Large")
my_ctld:AddCratesCargo("Hawk TR (1)",{"Hawk TR"},CTLD_CARGO.Enum.VEHICLE,1,000,nil,"SAM-Large")
my_ctld:AddCratesCargo("Hawk SR (1)",{"Hawk SR"},CTLD_CARGO.Enum.VEHICLE,1,1000,nil,"SAM-Large")
my_ctld:AddCratesCargo("Hawk LNR (1)",{"Hawk LN"},CTLD_CARGO.Enum.VEHICLE,1,1000,nil,"SAM-Large")

--========================================
-- CTLD Vehicle Cargo - Ground Attack Missiles
--========================================

--- Air to Ground Missiles --
my_ctld:AddCratesCargo("Stryker ATGM (1)",{"Stryker ATGM"},CTLD_CARGO.Enum.VEHICLE,2,500,nil,"ATGM")
my_ctld:AddCratesCargo("HMV ATGM (2)",{"HMV ATGM"},CTLD_CARGO.Enum.VEHICLE,2,500,nil,"ATGM")

--========================================
-- CTLD FARP and Logistics Objects
--========================================

--- FARP/Log/OP ---
my_ctld:AddCratesCargo("Outpost (2)",{"Outpost"},CTLD_CARGO.Enum.FOB,2,500,nil,"FARP/MASH")
my_ctld:AddCratesCargo("Ammo Truck (2)",{"Ammo Truck"},CTLD_CARGO.Enum.VEHICLE,2,500,nil,"FARP/MASH")
my_ctld:AddCratesCargo("FARP (3)",{"FOB"},CTLD_CARGO.Enum.FOB,3,500,nil,"FARP/MASH")

-- Add MASH crates to CTLD cargo list
my_ctld:AddCratesCargo("MASH", {"MASH"}, CTLD_CARGO.Enum.FOB, 2, 500, nil, "FARP/MASH")

--========================================
-- CTLD Repair Crates - MBT / SAM / Arty
--========================================

--- Repair MBT/SAM/Arty ---
my_ctld:AddCratesRepair("Challenger 2 Repair","Challenger 2",CTLD_CARGO.Enum.REPAIR,1,500,nil,"Repair MBT/SAM/ARTY")
my_ctld:AddCratesRepair("Leopard 2 Repair","Leopard 2",CTLD_CARGO.Enum.REPAIR,1,500,nil,"Repair MBT/SAM/ARTY")
my_ctld:AddCratesRepair("M1 Abrams Repair","M1 Abrams",CTLD_CARGO.Enum.REPAIR,1,500,nil,"Repair MBT/SAM/ARTY")
my_ctld:AddCratesRepair("NASAM C2 Repair","NASAM C2",CTLD_CARGO.Enum.REPAIR,1,500,nil,"Repair MBT/SAM/ARTY")
my_ctld:AddCratesRepair("NASAM SR Repair","NASAM SR",CTLD_CARGO.Enum.REPAIR,1,500,nil,"Repair MBT/SAM/ARTY")
my_ctld:AddCratesRepair("NASAM 120C Repair","NASAM 120C",CTLD_CARGO.Enum.REPAIR,1,500,nil,"Repair MBT/SAM/ARTY")
my_ctld:AddCratesRepair("Paladin Repair","Paladin",CTLD_CARGO.Enum.REPAIR,1,500,nil,"Repair MBT/SAM/ARTY")
my_ctld:AddCratesRepair("Firtina Repair","Firtina",CTLD_CARGO.Enum.REPAIR,1,500,nil,"Repair MBT/SAM/ARTY")
my_ctld:AddCratesRepair("Excalibur Repair","Excalibur",CTLD_CARGO.Enum.REPAIR,1,500,nil,"Repair MBT/SAM/ARTY")

--========================================
-- CTLD Repair Crates - IFV / ADS
--========================================

--- Repair IFV/ADS ---
my_ctld:AddCratesRepair("Marder IFV Repair","Marder IFV",CTLD_CARGO.Enum.REPAIR,1,500,nil,"Repair IFV-ADS")
my_ctld:AddCratesRepair("Warrior IFV Repair","Warrior IFV",CTLD_CARGO.Enum.REPAIR,1,500,nil,"Repair IFV-ADS")
my_ctld:AddCratesRepair("HMV Gun Repair","HMV Gun",CTLD_CARGO.Enum.REPAIR,1,500,nil,"Repair IFV-ADS")
my_ctld:AddCratesRepair("Stryker IFV Repair","Stryker IFV",CTLD_CARGO.Enum.REPAIR,1,500,nil,"Repair IFV-ADS")
my_ctld:AddCratesRepair("Gepard Repair","Gepard",CTLD_CARGO.Enum.REPAIR,1,500,nil,"Repair IFV-ADS")
my_ctld:AddCratesRepair("Roland ADS Repair","Roland ADS",CTLD_CARGO.Enum.REPAIR,1,500,nil,"Repair IFV-ADS")
my_ctld:AddCratesRepair("C-RAM Repair","C-RAM",CTLD_CARGO.Enum.REPAIR,1,500,nil,"Repair IFV-ADS")
my_ctld:AddCratesRepair("JTAC Bradley Repair","JTAC Bradley",CTLD_CARGO.Enum.REPAIR,1,500,nil,"Repair IFV-ADS")
my_ctld:AddCratesRepair("MLRS M270 Repair","MLRS M270",CTLD_CARGO.Enum.REPAIR,1,500,nil,"Repair IFV-ADS")

my_ctld.repairtime = 30 -- takes 30 seconds to repair something


--==================================================
-- CTLD in Vehicles
--==================================================

--  Create a SET_CLIENT to capture CA vehicles steered by players
--  local truckers = SET_CLIENT:New():HandleCASlots():FilterCoalitions("blue"):FilterPrefixes("Truck"):FilterStart()
--  Allow CA transport
--          my_ctld:AllowCATransport(true,truckers)
--  Set truck capability by typename
--          my_ctld:SetUnitCapabilities("M 818", true, true, 2, 12, 9, 4500)
--  Alternatively set truck capability with a UNIT object
--          local GazTruck = UNIT:FindByName("GazTruck-1-1")
--          my_ctld:SetUnitCapabilities(GazTruck, true, true, 2, 12, 9, 4500)

local truckers = SET_CLIENT:New():HandleCASlots():FilterCoalitions("blue"):FilterPrefixes("Truck"):FilterStart()
local GazTruck = UNIT:FindByName("GazTruck-1")

my_ctld:AllowCATransport(true,truckers)
my_ctld:SetUnitCapabilities(GazTruck, true, true, 4, 12, 9, 4500) --true (Crates) true (troops) 4 (Max Crates) 12 (Max Troops) 9 (Length)  4500 (Max Weight)

--------------------------------------------------------------------

--==================================================
-- Generate Zone Types
--==================================================

my_ctld:AddCTLDZone("Loadzone",CTLD.CargoZoneType.LOAD,SMOKECOLOR.Blue,true,true) -- Note: since there are no blue flares, this will be a white flare when requested.
my_ctld:AddCTLDZone("Loadzone-1",CTLD.CargoZoneType.LOAD,SMOKECOLOR.Blue,true,true) -- Zones 1-6 are for Carrier operations
my_ctld:AddCTLDZone("Loadzone-2",CTLD.CargoZoneType.LOAD,SMOKECOLOR.Blue,true,true) -- Carrier route has zone for each leg
my_ctld:AddCTLDZone("Loadzone-3",CTLD.CargoZoneType.LOAD,SMOKECOLOR.Blue,true,true) -- this ensurse the loadzone remains avaiable
my_ctld:AddCTLDZone("Loadzone-4",CTLD.CargoZoneType.LOAD,SMOKECOLOR.Blue,true,true) -- for the movement of the carrier!!
my_ctld:AddCTLDZone("Loadzone-5",CTLD.CargoZoneType.LOAD,SMOKECOLOR.Blue,true,true)
my_ctld:AddCTLDZone("Loadzone-6",CTLD.CargoZoneType.LOAD,SMOKECOLOR.Blue,true,true)
my_ctld:AddCTLDZone("Dropzone",CTLD.CargoZoneType.DROP,SMOKECOLOR.Red,true,true)
my_ctld:AddCTLDZone("Movezone",CTLD.CargoZoneType.MOVE,SMOKECOLOR.Orange,false,false)

--- These make Cargo Load Zones available on Ships ---

my_ctld:AddCTLDZone("USS Tarawa",CTLD.CargoZoneType.SHIP,SMOKECOLOR.Blue,true,true,240,20)
my_ctld:AddCTLDZone("CVN-72",CTLD.CargoZoneType.SHIP,SMOKECOLOR.Blue,true,true,240,20)

   -- Add a zone of type SHIP to our setup. Players can load troops and crates from this ship
   -- "Tarawa" is the unitname (callsign) of the ship from the ME. Players can load, if they are inside the zone.
   -- The ship is 240 meters long and 20 meters wide.
   -- Note that you need to adjust the max hover height to deck height plus 5 meters or so for loading to work.
   -- When the ship is moving, avoid forcing hoverload.
   -- my_ctld:AddCTLDZone("Tarawa",CTLD.CargoZoneType.SHIP,SMOKECOLOR.Blue,true,true,240,20)

--==================================================
-- Creating a FOB with CTLD
--==================================================

-- Prerequisite - you need to add a FOB type cargo to your CTLD instance, for simplification we call it FOB:
-- Also, you should already have all the statics with the proper names according to your mission script, because we will be copying them,

-- How many farps do you want to load? 
-- Oldest will not be spawned if the number is exceded.

-- ========================================
-- CONFIGURATION
-- ========================================

local MAX_SAVED_FARPS = 2
local ADFStartFreq = 350
local FARPName = 1

local FARPClearnames = {
  [1] = "London", [2] = "Dallas", [3] = "Paris", [4] = "Moscow", [5] = "Berlin",
  [6] = "Rome", [7] = "Madrid", [8] = "Warsaw", [9] = "Dublin", [10] = "Perth",
}

local BuiltFARPCoordinates = {}
local SpawnedFARPsFromSave = 0

local StaticFARPs = { "FARP1", "FARP2", "FARP3" }

function BuildAFARP(Coordinate, stamp)
  local isFromSave = (stamp ~= nil)
  if isFromSave and SpawnedFARPsFromSave >= MAX_SAVED_FARPS then return end
  if isFromSave then SpawnedFARPsFromSave = SpawnedFARPsFromSave + 1 end

  local coord = Coordinate
  local FarpNameNumber = ((FARPName - 1) % 10) + 1
  local FName = FARPClearnames[FarpNameNumber]
  local adfFreq = ADFStartFreq + FARPName
  FARPName = FARPName + 1

  ZONE_RADIUS:New(FName, coord:GetVec2(), 150, false)

  UTILS.SpawnFARPAndFunctionalStatics(
    FName, coord,
    ENUMS.FARPType.FARP,
    my_ctld.coalition,
    country.id.USA,
    FarpNameNumber,
    adfFreq,
    radio.modulation.AM,
    nil, 30, nil, 6000, 6000
  )

  my_ctld:AddCTLDZone(FName, CTLD.CargoZoneType.LOAD, SMOKECOLOR.Blue, true, false)
  MESSAGE:New(string.format("FARP %s in operation on ADF %d KHz!", FName, adfFreq), 15, "CTLD"):ToBlue()
  my_ctld:RemoveStockCrates("FOB", 1)

  table.insert(BuiltFARPCoordinates, {
    name = FName,
    coord = coord,
    adf = adfFreq,
    timestamp = stamp or timer.getTime()
  })
end

function my_ctld:OnAfterCratesBuild(From, Event, To, Group, Unit, Vehicle)
  local name = Vehicle:GetName() or ""

  -- Existing: FOB crate builds into a FARP
  if string.find(name, "FOB", 1, true) then
    local Coord = Vehicle:GetCoordinate()
    Vehicle:Destroy(false)
    BuildAFARP(Coord)
    return
  end

  -- Added: MASH crate builds into your full MASH static set (at the build location)
  if string.find(name, "MASH", 1, true) then
    local Coord = Vehicle:GetCoordinate()
    Vehicle:Destroy(false)

    -- Simple unique-ish name + ADF (400–600 KHz)
    local mashName = string.format("MASH-%d", math.floor(timer.getTime()))
    local adf = math.random(400, 600)

    -- Spawns the complete MASH static package at the crate build point.
    -- (This uses your UTILS.SpawnMASHStatics from the MASH script.)
    UTILS.SpawnMASHStatics(mashName, Coord, country.id.USA, adf, "us army dark green", nil)
    return
  end
end


--==================================================
-- F10 Menu Setup and FARP Reporting (final, canonical)
--   - ONLY "Static FARP-1/2/3" from the ME
--   - PLUS dynamically built FARPs from BuildAFARP()
--   - Status: on-screen only (no SRS, no "CSAR:" prefix)
--   - Closest: on-screen (FARP), SRS voice-only says "farp"
--   - Uses ' | ' separators and shows ADF where available
--==================================================

--local farpMenu = MENU_COALITION:New(coalition.side.BLUE, "FARP")
--
---- Valid helicopter groups to anchor the report to (first alive unit is used)
--local validHelicopters = {
--  -- Helicargo
--  "Helicargo-1","Helicargo-2","Helicargo-3","Helicargo-4",
--  -- Herc
--  "Herc1",
--  -- MEDEVAC
--  "MEDEVAC  Bronco",  -- note the double space
--  -- Vision
--  "Vision-1","Vision-2","Vision-3","Vision-LC","Vision-LC-1","Vision-LH","Vision-LH-FARP",
--  "Vision-MG","Vision-MH","Vision-MinGun-H","Vision-MiniGun-C",
--  -- Eyeball
--  "Eyeball-1","Eyeball-2","Eyeball-3","Eyeball-4"
--}
--
---- Get first alive unit from those groups
--local function GetValidHelicopterUnit()
--  for _, groupName in ipairs(validHelicopters) do
--    local group = GROUP:FindByName(groupName)
--    if group and group:IsAlive() then
--      local unit = group:GetUnit(1)
--      if unit and unit:IsAlive() then return unit end
--    end
--  end
--  return nil
--end
--
---- Helpers
--local function _deg(h)
--  if not h then return 0 end
--  if h > 2*math.pi then return h end
--  return math.deg(h)
--end
--
---- EXACT list of ME statics to include
--local STATIC_FARP_NAMES = { "Static FARP-1", "Static FARP-2", "Static FARP-3" }
--
---- Fixed ADFs for those statics
--local StaticFARP_ADFs = {
--  ["Static FARP-1"] = 200,
--  ["Static FARP-2"] = 210,
--  ["Static FARP-3"] = 220,
--}
--
---- Build list of active FARPs: the exact statics above + any spawned (tracked in BuiltFARPCoordinates)
--local function GetActiveFARPs()
--  local names = {}
--
--  for _, n in ipairs(STATIC_FARP_NAMES) do table.insert(names, n) end
--
--  if BuiltFARPCoordinates then
--    for _, item in ipairs(BuiltFARPCoordinates) do
--      if item.name then table.insert(names, item.name) end
--    end
--  end
--
--  -- De-dupe while preserving order, then validate as statics
--  local seen, unique = {}, {}
--  for _, n in ipairs(names) do
--    if not seen[n] then seen[n] = true; table.insert(unique, n) end
--  end
--  local active = {}
--  for _, n in ipairs(unique) do
--    local s = STATIC:FindByName(n, false)
--    if s and s:IsAlive() then table.insert(active, n) end
--  end
--  return active
--end
--
---- ADF lookup: static FARPs first (fixed), then dynamic FARPs (from BuildAFARP)
--local function LookupADF(name)
--  if StaticFARP_ADFs[name] then return StaticFARP_ADFs[name] end
--  if BuiltFARPCoordinates then
--    for _, item in ipairs(BuiltFARPCoordinates) do
--      if item.name == name and item.adf then return item.adf end
--    end
--  end
--  return nil
--end
--
---- === FARP Status Report (ON-SCREEN ONLY)
--function ReportAllFARPStatus()
--  local player = GetValidHelicopterUnit()
--  if not player or not player:IsAlive() then return end
--
--  local myPos = player:GetCoordinate()
--  local hdg   = _deg(player:GetHeading())
--
--  local active = GetActiveFARPs()
--  if #active == 0 then
--    MESSAGE:New("FARP Status Report:\nNo active FARPs found.", 20):ToCoalition(coalition.side.BLUE)
--    return
--  end
--
--  local rows = {}
--  for _, name in ipairs(active) do
--    local s = STATIC:FindByName(name, false)
--    if s and s:IsAlive() then
--      local c     = s:GetCoordinate()
--      local d     = myPos:Get2DDistance(c)
--      local brgT  = myPos:HeadingTo(c)            -- true bearing (deg)
--      local brgR  = (brgT - hdg + 360) % 360
--      local adf   = LookupADF(name)
--
--      local line = adf
--        and string.format("%s | %.1f km | Bearing %03d° | ADF %d KHz", name, d/1000, brgR, adf)
--        or  string.format("%s | %.1f km | Bearing %03d°",              name, d/1000, brgR)
--
--      table.insert(rows, { dist = d, text = line })
--    end
--  end
--
--  table.sort(rows, function(a,b) return a.dist < b.dist end)
--
--  local out = { "FARP Status Report:" }
--  for _, r in ipairs(rows) do table.insert(out, r.text) end
--  local message = table.concat(out, "\n")
--
--  -- On-screen only (no CSAR/SRS, no "CSAR:" prefix)
--  MESSAGE:New(message, 20):ToCoalition(coalition.side.BLUE)
--end
--
---- === Closest FARP Report (screen shows "FARP"; SRS voice-only says "farp")
--function ReportClosestFARP()
--  local player = GetValidHelicopterUnit()
--  if not player or not player:IsAlive() then return end
--
--  local myPos = player:GetCoordinate()
--  local hdg   = _deg(player:GetHeading())
--
--  local active = GetActiveFARPs()
--  if #active == 0 then return end
--
--  local bestName, bestDist, bestRel = nil, math.huge, 0
--
--  for _, name in ipairs(active) do
--    local s = STATIC:FindByName(name, false)
--    if s and s:IsAlive() then
--      local c  = s:GetCoordinate()
--      local d  = myPos:Get2DDistance(c)
--      if d < bestDist then
--        bestDist = d
--        local brgT = myPos:HeadingTo(c)
--        bestRel = (brgT - hdg + 360) % 360
--        bestName = name
--      end
--    end
--  end
--
--  if not bestName then return end
--
--  -- On-screen message (keep "FARP"; no CSAR prefix)
--  local msg_screen = string.format("Closest FARP | %s | %.1f km | Bearing %03d°",
--                                   bestName, bestDist/1000, bestRel)
--  MESSAGE:New(msg_screen, 20):ToCoalition(coalition.side.BLUE)
--
--  -- SRS voice-only via CSAR (suppress CSAR overlay)
--  if mycsar and mycsar._DisplayMessageToSAR then
--    local srsName = bestName:gsub("FARP","farp"):gsub("%-"," ")
--    local msg_tts = string.format("Closest farp, %s, distance %.1f kilometers, bearing %03d degrees.",
--                                  srsName, bestDist/1000, bestRel)
--
--    -- duration=0 hides CSAR text; flags: clear=false, voice=true, screen=false
--    mycsar:_DisplayMessageToSAR(player, msg_tts, 0, false, true, false)
--  end
--end
--
---- === Add to F10 menu (coalition-wide)
--MENU_COALITION_COMMAND:New(coalition.side.BLUE, "FARP Closest", farpMenu, ReportClosestFARP)
--MENU_COALITION_COMMAND:New(coalition.side.BLUE, "FARP Status Report", farpMenu, ReportAllFARPStatus)
--
--


--==================================================
-- CTLD Event Handlers (Commented Out)
--==================================================

-- function my_ctld:OnAfterCratesPickedUp(From,Event,To,Group,Unit,Cargo)
-- MESSAGE:New("Crates picked up by "..Unit:GetPlayerName(),10,"CTLD"):ToBlue()
-- end

-- function my_ctld:OnAfterCratesDropped(From,Event,To,Group,Unit,Cargotable)
-- MESSAGE:New("Crates dropped by "..Unit:GetPlayerName(),10,"CTLD"):ToBlue()
-- end

-- function my_ctld:OnAfterCratesRepaired(From,Event,To,Group,Unit,Vehicle)
-- local groupname = Group:GetName()
-- local vehiclename = Vehicle:GetName()
-- local m = MESSAGE:New(string.format("%s has repaired %s! Good job!", groupname, vehiclename),10,"CTLD",true):ToAll()
-- end


--==================================================
-- CTLD Unit Capability Overrides
--==================================================

my_ctld:SetUnitCapabilities("CH-47Fbl1", true, true, 6, 31, 18, 10000)
my_ctld:SetUnitCapabilities("UH-1H", true, true, 6, 30, 12, 12000)
my_ctld:SetUnitCapabilities("Bronco-OV-10A", true, true, 1,4, 12, 5000)
my_ctld:SetUnitCapabilities("UH-60L", true, true, 6, 31, 18, 10000)


-- E.g. update unit capabilities for testing. Please stay realistic in your mission design.
-- Make a Gazelle into a heavy truck, this type can load both crates and troops and eight of each type, up to 4000 kgs:
-- my_ctld:SetUnitCapabilities("SA342L", true, true, 8, 8, 12, 4000)


--==================================================
-- Default Unit Type Capabilities (Reference Only)
--==================================================

--   ["SA342Mistral"] = {type="SA342Mistral", crates=false, troops=true, cratelimit = 0, trooplimit = 4, length = 12, cargoweightlimit = 400},
--   ["SA342L"] = {type="SA342L", crates=false, troops=true, cratelimit = 0, trooplimit = 2, length = 12, cargoweightlimit = 400},
--   ["SA342M"] = {type="SA342M", crates=false, troops=true, cratelimit = 0, trooplimit = 4, length = 12, cargoweightlimit = 400},
--   ["SA342Minigun"] = {type="SA342Minigun", crates=false, troops=true, cratelimit = 0, trooplimit = 2, length = 12, cargoweightlimit = 400},
--   ["UH-1H"] = {type="UH-1H", crates=true, troops=true, cratelimit = 1, trooplimit = 8, length = 15, cargoweightlimit = 700},
--   ["Mi-8MT"] = {type="Mi-8MT", crates=true, troops=true, cratelimit = 2, trooplimit = 12, length = 15, cargoweightlimit = 3000},
--   ["Mi-8MTV2"] = {type="Mi-8MTV2", crates=true, troops=true, cratelimit = 2, trooplimit = 12, length = 15, cargoweightlimit = 3000},
--   ["Ka-50"] = {type="Ka-50", crates=false, troops=false, cratelimit = 0, trooplimit = 0, length = 15, cargoweightlimit = 0},
--   ["Mi-24P"] = {type="Mi-24P", crates=true, troops=true, cratelimit = 2, trooplimit = 8, length = 18, cargoweightlimit = 700},
--   ["Mi-24V"] = {type="Mi-24V", crates=true, troops=true, cratelimit = 2, trooplimit = 8, length = 18, cargoweightlimit = 700},
--   ["Hercules"] = {type="Hercules", crates=true, troops=true, cratelimit = 7, trooplimit = 64, length = 25, cargoweightlimit = 19000},
--   ["UH-60L"] = {type="UH-60L", crates=true, troops=true, cratelimit = 2, trooplimit = 20, length = 16, cargoweightlimit = 3500},
--   ["AH-64D_BLK_II"] = {type="AH-64D_BLK_II", crates=false, troops=true, cratelimit = 0, trooplimit = 2, length = 17, cargoweightlimit = 200}, 
--   ["MH-60R"] = {type="MH-60R", crates=true, troops=true, cratelimit = 2, trooplimit = 20, length = 16, cargoweightlimit = 3500}, -- 4t cargo, 20 (unsec) seats
--   ["SH-60B"] = {type="SH-60B", crates=true, troops=true, cratelimit = 2, trooplimit = 20, length = 16, cargoweightlimit = 3500}, -- 4t cargo, 20 (unsec) seats
--   ["Bronco-OV-10A"] = {type="Bronco-OV-10A", crates= false, troops=true, cratelimit = 0, trooplimit = 5, length = 13, cargoweightlimit = 1450},
--   ["Bronco-OV-10A"] = {type="Bronco-OV-10A", crates= false, troops=true, cratelimit = 0, trooplimit = 5, length = 13, cargoweightlimit = 1450},
--   ["OH-6A"] = {type="OH-6A", crates=false, troops=true, cratelimit = 0, trooplimit = 4, length = 7, cargoweightlimit = 550},
--   ["OH58D"] = {type="OH58D", crates=false, troops=false, cratelimit = 0, trooplimit = 0, length = 14, cargoweightlimit = 400},
--   ["CH-47Fbl1"] = {type="CH-47Fbl1", crates=true, troops=true, cratelimit = 4, trooplimit = 31, length = 20, cargoweightlimit = 8000},


--==================================================
-- FARP Load/Save Logic (Persistent CTLD Positions)
--==================================================

if lfs then
local FarpFileName = "CTLD.csv"

function SaveFARPS()
  local path = my_ctld.filepath
  local filename = FarpFileName
  local data = "FARP COORDINATES\n"

  local function sortingfunction(d1,d2)
   return d1.timestamp > d2.timestamp
  end
    
  table.sort(BuiltFARPCoordinates,sortingfunction)

  local counter = 0
  
  for _,_coord in pairs(BuiltFARPCoordinates) do
    local FName = _coord.name
    local coord = _coord.coord -- Core.Point#COORDINATE
    local AFB = STATIC:FindByName(FName,false)
    if AFB and AFB:IsAlive() then
      counter = counter + 1 -- increase counter
      local vec2 = coord:GetVec2() -- { x = self.x, y = self.z }
      data = data .. string.format("%f;%f;\n",vec2.x,vec2.y)
      if counter == FARPStock then break end -- stop creating data when we reached the ceiling
    end
  end
  
  if UTILS.SaveToFile(path,filename,data) then
    BASE:I("***** FARP Positions saved successfully!")
  else
    BASE:E("***** ERROR Saving FARP Positions!")
  end
  
end
 
function LoadFARPS()
  local path = my_ctld.filepath
  local filename = FarpFileName
  local okay,data = UTILS.LoadFromFile(path,filename)
  local stamp = 0
  if okay then
    BASE:I("***** FARP Positions loaded successfully!")
    -- remove header
    table.remove(data, 1)
    for _,_entry in pairs(data) do
      local dataset = UTILS.Split(_entry,";")
      local x = tonumber(dataset[1])
      local y = tonumber(dataset[2])
      
      local coord = COORDINATE:NewFromVec2({x=x,y=y})
      stamp = stamp + 1
      BuildAFARP(coord,stamp)
    end
  else
    BASE:E("***** ERROR Loading FARP Positions!")
  end
end

local LoadFARPTimer = TIMER:New(LoadFARPS)
LoadFARPTimer:Start(5)

local SaveFARPTimer = TIMER:New(SaveFARPS)
SaveFARPTimer:Start(30,30)

my_ctld.enableLoadSave = true
my_ctld.saveinterval = 300
    my_ctld.filename = "Kiowa_Training.csv"
	my_ctld.filepath = lfs.writedir() .. "Missions\\Saves\\"
    my_ctld.eventoninject = true
    my_ctld.useprecisecoordloads = true

else
    MESSAGE:New("CTLD will not Save/load. Please, De-Sanitize DCS missionscripting.lua.\n\nfunctionality disabled.", 300):ToAll()
end

my_ctld:__Load(10)

end, nil, timer.getTime() + Delay_sec)

---------------------------------
