mission = 
{
    ["requiredModules"] = 
    {
    }, -- end of ["requiredModules"]
    ["date"] = 
    {
        ["Year"] = 2016,
        ["Day"] = 21,
        ["Month"] = 6,
    }, -- end of ["date"]
    ["result"] = 
    {
        ["offline"] = 
        {
            ["conditions"] = 
            {
            }, -- end of ["conditions"]
            ["actions"] = 
            {
            }, -- end of ["actions"]
            ["func"] = 
            {
            }, -- end of ["func"]
        }, -- end of ["offline"]
        ["total"] = 0,
        ["blue"] = 
        {
            ["conditions"] = 
            {
            }, -- end of ["conditions"]
            ["actions"] = 
            {
            }, -- end of ["actions"]
            ["func"] = 
            {
            }, -- end of ["func"]
        }, -- end of ["blue"]
        ["red"] = 
        {
            ["conditions"] = 
            {
            }, -- end of ["conditions"]
            ["actions"] = 
            {
            }, -- end of ["actions"]
            ["func"] = 
            {
            }, -- end of ["func"]
        }, -- end of ["red"]
    }, -- end of ["result"]
    ["maxDictId"] = 7,
    ["trig"] = 
    {
        ["actions"] = 
        {
            [1] = "a_do_script(\"dcsCommon = {}\\\
dcsCommon.version = \\\"2.8.7\\\"\\\
--[[-- VERSION HISTORY\\\
 2.2.6 - compassPositionOfARelativeToB\\\
       - clockPositionOfARelativeToB\\\
 2.2.7 - isTroopCarrier \\\
       - distFlat\\\
 2.2.8 - fixed event2text \\\
 2.2.9 - getUnitAGL\\\
       - getUnitAlt\\\
       - getUnitSpeed \\\
       - getUnitHeading\\\
       - getUnitHeadingDegrees\\\
       - mag\\\
       - clockPositionOfARelativeToB with own heading \\\
 2.3.0 - unitIsInfantry\\\
 2.3.1 - bool2YesNo\\\
       - bool2Text\\\
 2.3.2 - getGroupAvgSpeed\\\
       - getGroupMaxSpeed\\\
 2.3.3 - getSizeOfTable\\\
 2.3.4 - isSceneryObject\\\
         coalition2county\\\
 2.3.5 - smallRandom\\\
         pickRandom uses smallRandom\\\
         airfield handling, parking \\\
         flight waypoint handling\\\
         landing waypoint creation\\\
         take-off waypoint creation\\\
 2.3.6 - createOverheadAirdromeRoutPintData(aerodrome)\\\
 2.3.7 - coalition2county - warning when creating UN \\\
 2.3.8 - improved headingOfBInDegrees, new getClockDirection\\\
 2.3.9 - getClosingVelocity\\\
       - dot product \\\
       - magSquare\\\
       - vMag\\\
 2.4.0 - libCheck\\\
 2.4.1 - grid/square/rect formation \\\
       - arrangeGroupInNColumns formation \\\
       - 2Columns formation deep and wide formation\\\
 2.4.2 - getAirbasesInRangeOfPoint\\\
 2.4.3 - lerp \\\
 2.4.4 - getClosestAirbaseTo\\\
       - fixed bug in containsString when strings equal\\\
 2.4.5 - added cargo and mass options to createStaticObjectData\\\
 2.4.6 - fixed randompercent \\\
 2.4.7 - smokeColor2Num(smokeColor)\\\
 2.4.8 - linkStaticDataToUnit()\\\
 2.4.9 - trim functions \\\
       - createGroundUnitData uses trim function to remove leading/trailing blanks\\\
         so now we can use blanks after comma to separate types \\\
       - dcsCommon.trimArray(\\\
       - createStaticObjectData uses trim for type \\\
       - getEnemyCoalitionFor understands strings, still returns number\\\
       - coalition2county also understands 'red' and 'blue'\\\
 2.5.0 - \\\"Line\\\" formation with one unit places unit at center     \\\
 2.5.1 - vNorm(a)  \\\
 2.5.1 - added SA-18 Igla manpad to unitIsInfantry()\\\
 2.5.2 - added copyArray method\\\
       - corrected heading in createStaticObjectData\\\
 2.5.3 - corrected rotateGroupData bug for cz \\\
       - removed forced error in failed pickRandom\\\
 2.5.4 - rotateUnitData()\\\
       - randomBetween()\\\
 2.5.5 - stringStartsWithDigit()\\\
       - stringStartsWithLetter()\\\
       - stringIsPositiveNumber()\\\
 2.5.6 - corrected stringEndsWith() bug with str\\\
 2.5.7 - point2text(p) \\\
 2.5.8 - string2GroupCat()\\\
 2.5.9 - string2ObjectCat()\\\
 2.6.0 - unified uuid, removed uuIdent\\\
 2.6.1 - removed bug in rotateUnitData: cy --> cz param passing  \\\
 2.6.2 - new combineTables()\\\
 2.6.3 - new tacan2freq()\\\
 2.6.4 - new processHMS()\\\
 2.6.5 - new bearing2compass()\\\
       - new bearingdegrees2compass()\\\
       - new latLon2Text() - based on mist \\\
 2.6.6 - new nowString() \\\
       - new str2num()\\\
       - new stringRemainsStartingWith()\\\
       - new stripLF()\\\
       - new removeBlanks()\\\
 2.6.7 - new menu2text()\\\
 2.6.8 - new getMissionName()\\\
       - new flagArrayFromString()\\\
 2.6.9 - new getSceneryObjectsInZone()\\\
       - new getSceneryObjectInZoneByName()\\\
 2.7.0 - new synchGroupData()\\\
         clone, topClone and copyArray now all nil-trap \\\
 2.7.1 - new isPlayerUnit() -- moved from cfxPlayer\\\
         new getAllExistingPlayerUnitsRaw - from cfxPlayer\\\
         new typeIsInfantry()\\\
 2.7.2 - new rangeArrayFromString()\\\
         fixed leading blank bug in flagArrayFromString\\\
         new incFlag()\\\
         new decFlag()\\\
         nil trap in stringStartsWith()\\\
         new getClosestFreeSlotForCatInAirbaseTo()\\\
 2.7.3 - new string2Array()\\\
       - additional guard for isPlayerUnit\\\
 2.7.4 - new array2string()\\\
 2.7.5 - new bitAND32()\\\
       - new LSR()\\\
       - new num2bin()\\\
 2.7.6 - new getObjectsForCatAtPointWithRadius()\\\
 2.7.7 - clone() has new stripMeta option. pass true to remove all meta tables \\\
       - dumpVar2Str detects meta tables \\\
       - rotateGroupData kills unit's psi value if it existed since it messes with heading \\\
       - rotateGroupData - changes psi to -heading if it exists rather than nilling\\\
 2.7.8 - new getGeneralDirection()\\\
       - new getNauticalDirection()\\\
       - more robust guards for getUnitSpeed\\\
 2.7.9 - new bool2Num(theBool)\\\
       - new aspectByDirection()\\\
       - createGroundGroupWithUnits corrected spelling of minDist, crashed scattered formation\\\
       - randomPointInCircle fixed erroneous local for x, z \\\
       - \\\"scattered\\\" formation repaired\\\
 2.7.10- semaphore groundwork \\\
 2.8.0 - new collectMissionIDs at start-up  \\\
       - new getUnitNameByID\\\
       - new getGroupNameByID\\\
       - bool2YesNo alsco can return NIL\\\
       - new getUnitStartPosByID\\\
 2.8.1 - arrayContainsString: type checking for theArray and warning\\\
       - processStringWildcards()\\\
       - new wildArrayContainsString() \\\
       - fix for stringStartsWith oddity with aircraft types \\\
 2.8.2 - better fixes for string.find() in stringStartsWith and containsString\\\
       - dcsCommon.isTroopCarrier(theUnit, carriers) new carriers optional param\\\
       - better guards for getUnitAlt and getUnitAGL\\\
       - new newPointAtDegreesRange()\\\
       - new newPointAtAngleRange()\\\
       - new isTroopCarrierType()\\\
       - stringStartsWith now supports case insensitive match \\\
       - isTroopCarrier() supports 'any' and 'all'\\\
       - made getEnemyCoalitionFor() more resilient \\\
       - fix to smallRandom for negative numbers\\\
       - isTroopCarrierType uses wildArrayContainsString\\\
 2.8.3 - small optimizations in bearingFromAtoB()\\\
       - new whichSideOfMine()\\\
 2.8.4 - new rotatePointAroundOriginRad()\\\
       - new rotatePointAroundPointDeg()\\\
       - new rotatePointAroundPointRad()\\\
       - getClosestAirbaseTo() now supports passing list of air bases\\\
 2.8.5 - better guard in getGroupUnit()\\\
 2.8.6 - phonetic helpers \\\
         new spellString()\\\
 2.8.7 - new flareColor2Num()\\\
       - new flareColor2Text()\\\
       - new iteratePlayers()\\\
 \\\
--]]--\\\
\\\
    -- dcsCommon is a library of common lua functions \\\
    -- for easy access and simple mission programming\\\
    -- (c) 2021 - 2023 by Chritian Franz and cf/x AG\\\
\\\
    dcsCommon.verbose = false -- set to true to see debug messages. Lots of them\\\
    dcsCommon.uuidStr = \\\"uuid-\\\"\\\
    dcsCommon.simpleUUID = 76543 -- a number to start. as good as any\\\
    \\\
    -- globals\\\
    dcsCommon.cbID = 0 -- callback id for simple callback scheduling\\\
    dcsCommon.troopCarriers = {\\\"Mi-8MT\\\", \\\"UH-1H\\\", \\\"Mi-24P\\\"} -- Ka-50, Apache and Gazelle can't carry troops\\\
    dcsCommon.coalitionSides = {0, 1, 2}\\\
    \\\
    -- lookup tables\\\
    dcsCommon.groupID2Name = {}\\\
    dcsCommon.unitID2Name = {}\\\
    dcsCommon.unitID2X = {}\\\
    dcsCommon.unitID2Y = {}\\\
\\\
    -- verify that a module is loaded. obviously not required\\\
    -- for dcsCommon, but all higher-order modules\\\
    function dcsCommon.libCheck(testingFor, requiredLibs)\\\
        local canRun = true \\\
        for idx, libName in pairs(requiredLibs) do \\\
            if not _G[libName] then \\\
                trigger.action.outText(\\\"*** \\\" .. testingFor .. \\\" requires \\\" .. libName, 30)\\\
                canRun = false \\\
            end\\\
        end\\\
        return canRun\\\
    end\\\
\\\
    -- read all groups and units from miz and build a reference table\\\
    function dcsCommon.collectMissionIDs()\\\
    -- create cross reference tables to be able to get a group or\\\
    -- unit's name by ID\\\
        for coa_name_miz, coa_data in pairs(env.mission.coalition) do -- iterate all coalitions\\\
            local coa_name = coa_name_miz\\\
            if string.lower(coa_name_miz) == 'neutrals' then -- remove 's' at neutralS\\\
                coa_name = 'neutral'\\\
            end\\\
            -- directly convert coalition into number for easier access later\\\
            local coaNum = 0\\\
            if coa_name == \\\"red\\\" then coaNum = 1 end \\\
            if coa_name == \\\"blue\\\" then coaNum = 2 end \\\
            \\\
            if type(coa_data) == 'table' then -- coalition = {bullseye, nav_points, name, county}, \\\
                                              -- with county being an array \\\
                if coa_data.country then -- make sure there a country table for this coalition\\\
                    for cntry_id, cntry_data in pairs(coa_data.country) do -- iterate all countries for this \\\
                        -- per country = {id, name, vehicle, helicopter, plane, ship, static}\\\
                        local countryName = string.lower(cntry_data.name)\\\
                        local countryID = cntry_data.id \\\
                        if type(cntry_data) == 'table' then    -- filter strings .id and .name \\\
                            for obj_type_name, obj_type_data in pairs(cntry_data) do\\\
                                -- only look at helos, ships, planes and vehicles\\\
                                if obj_type_name == \\\"helicopter\\\" or \\\
                                   obj_type_name == \\\"ship\\\" or \\\
                                   obj_type_name == \\\"plane\\\" or \\\
                                   obj_type_name == \\\"vehicle\\\" or \\\
                                   obj_type_name == \\\"static\\\" -- what about \\\"cargo\\\"?\\\
                                then -- (so it's not id or name)\\\
                                    local category = obj_type_name\\\
                                    if ((type(obj_type_data) == 'table') and obj_type_data.group and (type(obj_type_data.group) == 'table') and (#obj_type_data.group > 0)) then    --there's at least one group!\\\
                                        for group_num, group_data in pairs(obj_type_data.group) do\\\
                                            \\\
                                            local aName = group_data.name \\\
                                            local aID = group_data.groupId\\\
                                            -- store this reference \\\
                                            dcsCommon.groupID2Name[aID] = aName \\\
                                            \\\
                                            -- now iterate all units in this group \\\
                                            -- for player into \\\
                                            for unit_num, unit_data in pairs(group_data.units) do\\\
                                                if unit_data.name and unit_data.unitId then \\\
                                                    -- store this reference \\\
                                                    dcsCommon.unitID2Name[unit_data.unitId] = unit_data.name\\\
                                                    dcsCommon.unitID2X[unit_data.unitId] = unit_data.x\\\
                                                    dcsCommon.unitID2Y[unit_data.unitId] = unit_data.y\\\
                                                end\\\
                                            end -- for all units\\\
                                        end -- for all groups \\\
                                    end --if has category data \\\
                                end --if plane, helo etc... category\\\
                            end --for all objects in country \\\
                        end --if has country data \\\
                    end --for all countries in coalition\\\
                end --if coalition has country table \\\
            end -- if there is coalition data  \\\
        end --for all coalitions in mission \\\
    end\\\
\\\
    function dcsCommon.getUnitNameByID(theID)\\\
        -- accessor function for later expansion\\\
        return dcsCommon.unitID2Name[theID]\\\
    end\\\
    \\\
    function dcsCommon.getGroupNameByID(theID)\\\
        -- accessor function for later expansion \\\
        return dcsCommon.groupID2Name[theID]\\\
    end\\\
\\\
    function dcsCommon.getUnitStartPosByID(theID)\\\
        local x = dcsCommon.unitID2X[theID]\\\
        local y = dcsCommon.unitID2Y[theID]\\\
        return x, y\\\
    end\\\
    \\\
    -- returns only positive values, lo must be >0 and <= hi \\\
    function dcsCommon.randomBetween(loBound, hiBound)\\\
        if not loBound then loBound = 1 end \\\
        if not hiBound then hiBound = 1 end \\\
        if loBound == hiBound then return loBound end \\\
\\\
        local delayMin = loBound\\\
        local delayMax = hiBound \\\
        local delay = delayMax \\\
    \\\
        if delayMin ~= delayMax then \\\
            -- pick random in range , say 3-7 --> 5 s!\\\
            local delayDiff = (delayMax - delayMin) + 1 -- 7-3 + 1\\\
            delay = dcsCommon.smallRandom(delayDiff) - 1 --> 0-4\\\
            delay = delay + delayMin \\\
            if delay > delayMax then delay = delayMax end \\\
            if delay < 1 then delay = 1 end \\\
        \\\
            if dcsCommon.verbose then \\\
                trigger.action.outText(\\\"+++dcsC: delay range \\\" .. delayMin .. \\\"-\\\" .. delayMax .. \\\": selected \\\" .. delay, 30)\\\
            end\\\
        end\\\
        \\\
        return delay\\\
    end\\\
    \\\
\\\
    -- taken inspiration from mist, as dcs lua has issues with\\\
    -- random numbers smaller than 50. Given a range of x numbers 1..x, it is \\\
    -- repeated a number of times until it fills an array of at least \\\
    -- 50 items (usually some more), and only then one itemis picked from \\\
    -- that array with a random number that is from a greater range (0..50+)\\\
    function dcsCommon.smallRandom(theNum) -- adapted from mist, only support ints\\\
        theNum = math.floor(theNum)\\\
        if theNum >= 50 then return math.random(theNum) end\\\
        if theNum < 1 then\\\
            trigger.action.outText(\\\"smallRandom: invoke with argument < 1 (\\\" .. theNum .. \\\"), using 1\\\", 30)\\\
            theNum = 1 \\\
        end \\\
        -- for small randoms (<50) \\\
        local lowNum, highNum\\\
        highNum = theNum\\\
        lowNum = 1\\\
        local total = 1\\\
        if math.abs(highNum - lowNum + 1) < 50 then -- if total values is less than 50\\\
            total = math.modf(50/math.abs(highNum - lowNum + 1)) -- number of times to repeat whole range to get above 50. e.g. 11 would be 5 times 1 .. 11, giving us 55 items total \\\
        end\\\
        local choices = {}\\\
        for i = 1, total do -- iterate required number of times\\\
            for x = lowNum, highNum do -- iterate between the range\\\
                choices[#choices +1] = x -- add each entry to a table\\\
            end\\\
        end\\\
        local rtnVal; -- = math.random(#choices) -- will now do a math.random of at least 50 choices\\\
        for i = 1, 15 do\\\
            rtnVal = math.random(#choices) -- iterate 15 times for randomization\\\
        end\\\
        return choices[rtnVal] -- return indexed\\\
    end\\\
    \\\
\\\
    function dcsCommon.getSizeOfTable(theTable)\\\
        local count = 0\\\
        for _ in pairs(theTable) do count = count + 1 end\\\
        return count\\\
    end\\\
\\\
    function dcsCommon.findAndRemoveFromTable(theTable, theElement) -- assumes array \\\
        if not theElement then return false end \\\
        if not theTable then return false end \\\
        for i=1, #theTable do \\\
            if theTable[i] == theElement then \\\
                -- this element found. remove from table \\\
                table.remove(theTable, i)\\\
                return true \\\
            end\\\
        end\\\
    end\\\
\\\
    function dcsCommon.pickRandom(theTable)\\\
        if not theTable then \\\
            trigger.action.outText(\\\"*** warning: nil table in pick random\\\", 30)\\\
        end\\\
        \\\
        if #theTable < 1 then \\\
            trigger.action.outText(\\\"*** warning: zero choice in pick random\\\", 30)\\\
            --local k = i.ll \\\
            return nil\\\
        end\\\
        if #theTable == 1 then return theTable[1] end\\\
        r = dcsCommon.smallRandom(#theTable) --r = math.random(#theTable)\\\
        return theTable[r]\\\
    end\\\
\\\
    -- enumerateTable - make an array out of a table for indexed access\\\
    function dcsCommon.enumerateTable(theTable)\\\
        if not theTable then theTable = {} end\\\
        local array = {}\\\
        for key, value in pairs(theTable) do \\\
            table.insert(array, value)\\\
        end\\\
        return array\\\
    end\\\
\\\
    -- combine table. creates new \\\
    function dcsCommon.combineTables(inOne, inTwo)\\\
        local outTable = {}\\\
        for idx, element in pairs(inOne) do \\\
            table.insert(outTable, element)\\\
        end\\\
        for idx, element in pairs(inTwo) do \\\
            table.insert(outTable, element)\\\
        end\\\
        return outTable\\\
    end\\\
-- \\\
-- A I R F I E L D S  A N D  F A R P S  \\\
--\\\
\\\
    -- airfield management \\\
    function dcsCommon.getAirbaseCat(aBase)\\\
        if not aBase then return nil end \\\
        \\\
        local airDesc = aBase:getDesc()\\\
        if not airDesc then return nil end \\\
        \\\
        local airCat = airDesc.category\\\
        return airCat \\\
    end\\\
\\\
    -- get free parking slot. optional parkingType can be used to \\\
    -- filter for a scpecific type, e.g. 104 = open field\\\
    function dcsCommon.getFirstFreeParkingSlot(aerodrome, parkingType) \\\
        if not aerodrome then return nil end \\\
        local freeSlots = aerodrome:getParking(true)\\\
        \\\
        for idx, theSlot in pairs(freeSlots) do \\\
            if not parkingType then \\\
                -- simply return the first we come across\\\
                return theSlot\\\
            end        \\\
            \\\
            if theSlot.Term_Type == parkingType then \\\
                return theSlot \\\
            end\\\
        end\\\
        \\\
        return nil \\\
    end\\\
\\\
    -- getAirbasesInRangeOfPoint: get airbases that are in range of point \\\
    function dcsCommon.getAirbasesInRangeOfPoint(center, range, filterCat, filterCoalition)\\\
        if not center then return {} end \\\
        if not range then range = 500 end -- 500m default \\\
        local basesInRange = {}\\\
        \\\
        local allAB = dcsCommon.getAirbasesWhoseNameContains(\\\"*\\\", filterCat, filterCoalition)\\\
        for idx, aBase in pairs(allAB) do             \\\
            local delta = dcsCommon.dist(center, aBase:getPoint())\\\
            if delta <= range then \\\
                table.insert(basesInRange, aBase)\\\
            end\\\
        end\\\
        return basesInRange\\\
    end\\\
\\\
    -- getAirbasesInRangeOfAirbase returns all airbases that \\\
    -- are in range of the given airbase \\\
    function dcsCommon.getAirbasesInRangeOfAirbase(airbase, includeCenter, range, filterCat, filterCoalition)\\\
        if not airbase then return {} end\\\
        if not range then range = 150000 end \\\
        local center = airbase:getPoint() \\\
        local centerName = airbase:getName() \\\
        \\\
        local ABinRange = {}\\\
        local allAB = dcsCommon.getAirbasesWhoseNameContains(\\\"*\\\", filterCat, filterCoalition)\\\
        \\\
        for idx, aBase in pairs(allAB) do \\\
            if aBase:getName() ~= centerName then \\\
                local delta = dcsCommon.dist(center, aBase:getPoint())\\\
                if delta <= range then \\\
                    table.insert(ABinRange, aBase)\\\
                end\\\
            end        \\\
        end\\\
        \\\
        if includeCenter then \\\
            table.insert(ABinRange, airbase)\\\
        end\\\
        \\\
        return ABinRange\\\
    end\\\
\\\
    function dcsCommon.getAirbasesInRangeOfAirbaseList(theCenterList, includeList, range, filterCat, filterCoalition)\\\
        local collectorDict = {}\\\
        for idx, aCenter in pairs(theCenterList) do \\\
            -- get all surrounding airbases. returns list of airfields \\\
            local surroundingAB = dcsCommon.getAirbasesInRangeOfAirbase(airbase, includeList, range, filterCat, filterCoalition)\\\
            \\\
            for idx2, theAirField in pairs (surroundingAB) do \\\
                collectorDict[airField] = theAirField \\\
            end\\\
        end\\\
        \\\
        -- make result an array\\\
        local theABList = dcsCommon.enumerateTable(collectorDict)\\\
        return theABList\\\
    end\\\
\\\
    -- getAirbasesWhoseNameContains - get all airbases containing \\\
    -- a name. filterCat is optional and can be aerodrome (0), farp (1), ship (2)\\\
    -- filterCoalition is optional and can be 0 (neutral), 1 (red), 2 (blue) \\\
    -- if no name given or aName = \\\"*\\\", then all bases are returned prior to filtering \\\
    function dcsCommon.getAirbasesWhoseNameContains(aName, filterCat, filterCoalition)\\\
        --trigger.action.outText(\\\"getAB(name): enter with \\\" .. aName, 30)\\\
        if not aName then aName = \\\"*\\\" end \\\
        local allYourBase = world.getAirbases() -- get em all \\\
        local areBelongToUs = {}\\\
        -- now iterate all bases\\\
        for idx, aBase in pairs(allYourBase) do\\\
            local airBaseName = aBase:getName() -- get display name\\\
            if aName == \\\"*\\\" or dcsCommon.containsString(airBaseName, aName) then \\\
                -- containsString is case insesitive unless told otherwise\\\
                --if aName ~= \\\"*\\\" then \\\
                --    trigger.action.outText(\\\"getAB(name): matched \\\" .. airBaseName, 30)\\\
                --end \\\
                local doAdd = true \\\
                if filterCat then \\\
                    -- make sure the airbase is of that category \\\
                    local airCat = dcsCommon.getAirbaseCat(aBase)\\\
                    doAdd = doAdd and airCat == filterCat \\\
                end\\\
                \\\
                if filterCoalition then \\\
                    doAdd = doAdd and filterCoalition == aBase:getCoalition()\\\
                end\\\
                \\\
                if doAdd then \\\
                    -- all good, add to table\\\
                    table.insert(areBelongToUs, aBase)\\\
                end            \\\
            end\\\
        end\\\
        return areBelongToUs\\\
    end\\\
\\\
    function dcsCommon.getFirstAirbaseWhoseNameContains(aName, filterCat, filterCoalition)\\\
        local allBases = dcsCommon.getAirbasesWhoseNameContains(aName, filterCat, filterCoalition)\\\
        for idx, aBase in pairs (allBases) do \\\
            -- simply return first \\\
            return aBase\\\
        end\\\
        return nil \\\
    end    \\\
\\\
    function dcsCommon.getClosestAirbaseTo(thePoint, filterCat, filterCoalition, allYourBase)\\\
        local delta = math.huge\\\
        if not allYourBase then \\\
            allYourBase = dcsCommon.getAirbasesWhoseNameContains(\\\"*\\\", filterCat, filterCoalition) -- get em all and filter\\\
        end \\\
        \\\
        local closestBase = nil \\\
        for idx, aBase in pairs(allYourBase) do\\\
            -- iterate them all \\\
            local abPoint = aBase:getPoint()\\\
            newDelta = dcsCommon.dist(thePoint, {x=abPoint.x, y = 0, z=abPoint.z})\\\
            if newDelta < delta then \\\
                delta = newDelta\\\
                closestBase = aBase\\\
            end\\\
        end\\\
        return closestBase, delta \\\
    end\\\
\\\
    function dcsCommon.getClosestFreeSlotForCatInAirbaseTo(cat, x, y, theAirbase, ignore)\\\
        if not theAirbase then return nil end \\\
        if not ignore then ignore = {} end \\\
        if not cat then return nil end \\\
        if (not cat == \\\"helicopter\\\") and (not cat == \\\"plane\\\") then \\\
            trigger.action.outText(\\\"+++common-getslotforcat: wrong cat <\\\" .. cat .. \\\">\\\", 30)\\\
            return nil \\\
        end\\\
        local allFree = theAirbase:getParking(true) --  only free slots\\\
        local filterFreeByType = {}\\\
        for idx, aSlot in pairs(allFree) do \\\
            local termT = aSlot.Term_Type\\\
            if termT == 104 or \\\
            (termT == 72 and cat == \\\"plane\\\") or \\\
            (termT == 68 and cat == \\\"plane\\\") or \\\
            (termT == 40 and cat == \\\"helicopter\\\") then \\\
                table.insert(filterFreeByType, aSlot)\\\
            else \\\
                -- we skip this slot, not good for type \\\
            end\\\
        end\\\
        \\\
        if #filterFreeByType == 0 then \\\
            return nil\\\
        end \\\
        \\\
        local reallyFree = {}\\\
        for idx, aSlot in pairs(filterFreeByType) do \\\
            local slotNum = aSlot.Term_Index\\\
            isTaken = false \\\
            for idy, taken in pairs(ignore) do \\\
                if taken == slotNum then isTaken = true end \\\
            end\\\
            if not isTaken then \\\
                table.insert(reallyFree, aSlot)\\\
            end\\\
        end\\\
        \\\
        if #reallyFree < 1 then \\\
            reallyFree = filterFreeByType\\\
        end\\\
        \\\
        local closestDist = math.huge \\\
        local closestSlot = nil \\\
        local p = {x = x, y = 0, z = y} -- !!\\\
        for idx, aSlot in pairs(reallyFree) do \\\
            local sp = {x = aSlot.vTerminalPos.x, y = 0, z = aSlot.vTerminalPos.z}\\\
            local currDist = dcsCommon.distFlat(p, sp)\\\
            --trigger.action.outText(\\\"slot <\\\" .. aSlot.Term_Index .. \\\"> has dist \\\" .. math.floor(currDist) .. \\\" and _0 of <\\\" .. aSlot.Term_Index_0 .. \\\">\\\", 30)\\\
            if currDist < closestDist then \\\
                closestSlot = aSlot \\\
                closestDist = currDist \\\
            end\\\
        end\\\
        --trigger.action.outText(\\\"slot <\\\" .. closestSlot.Term_Index .. \\\"> has closest dist <\\\" .. math.floor(closestDist) .. \\\">\\\", 30)\\\
        return closestSlot\\\
    end\\\
\\\
-- \\\
-- U N I T S   M A N A G E M E N T \\\
--\\\
\\\
    -- number of living units in group\\\
    function dcsCommon.livingUnitsInGroup(group)\\\
        local living = 0\\\
        local allUnits = group:getUnits()\\\
        for key, aUnit in pairs(allUnits) do \\\
            if aUnit:isExist() and aUnit:getLife() >= 1 then \\\
                living = living + 1\\\
            end\\\
        end\\\
        return living\\\
    end\\\
\\\
    -- closest living unit in group to a point\\\
    function dcsCommon.getClosestLivingUnitToPoint(group, p)\\\
        if not p then return nil end\\\
        if not group then return nil end\\\
        local closestUnit = nil\\\
        local closestDist = math.huge\\\
        local allUnits = group:getUnits()\\\
        for key, aUnit in pairs(allUnits) do \\\
            if aUnit:isExist() and aUnit:getLife() >= 1 then \\\
                local thisDist = dcsCommon.dist(p, aUnit:getPoint())\\\
                if thisDist < closestDist then \\\
                    closestDist = thisDist\\\
                    closestUnit = aUnit \\\
                end\\\
            end\\\
        end\\\
        return closestUnit, closestDist\\\
    end\\\
    \\\
    -- closest living group to a point - cat can be nil or one of Group.Category = { AIRPLANE = 0, HELICOPTER = 1, GROUND = 2, SHIP = 3, TRAIN = 4}\\\
    function dcsCommon.getClosestLivingGroupToPoint(p, coal, cat) \\\
        if not cat then cat = 2 end -- ground is default \\\
        local closestGroup = nil;\\\
        local closestGroupDist = math.huge\\\
        local allGroups =  coalition.getGroups(coal, cat) -- get all groups from this coalition, perhaps filtered by cat \\\
        for key, grp in pairs(allGroups) do\\\
            local closestUnit, dist = dcsCommon.getClosestLivingUnitToPoint(grp, p)\\\
            if closestUnit then \\\
                if dist < closestGroupDist then \\\
                    closestGroup = grp\\\
                    closestGroupDist = dist\\\
                end\\\
            end            \\\
        end\\\
        return closestGroup, closestGroupDist\\\
    end\\\
\\\
    function dcsCommon.getLivingGroupsAndDistInRangeToPoint(p, range, coal, cat) \\\
        if not cat then cat = 2 end -- ground is default \\\
        local groupsInRange = {};\\\
        local allGroups = coalition.getGroups(coal, cat) -- get all groups from this coalition, perhaps filtered by cat \\\
        for key, grp in pairs(allGroups) do\\\
            local closestUnit, dist = dcsCommon.getClosestLivingUnitToPoint(grp, p)\\\
            if closestUnit then \\\
                if dist < range then \\\
                    table.insert(groupsInRange, {group = grp, dist = dist}) -- array\\\
                end\\\
            end            \\\
        end\\\
        -- sort the groups by distance\\\
        table.sort(groupsInRange, function (left, right) return left.dist < right.dist end )\\\
        return groupsInRange\\\
    end\\\
\\\
    -- distFlat ignores y, input must be xyz points, NOT xy points  \\\
    function dcsCommon.distFlat(p1, p2) \\\
        local point1 = {x = p1.x, y = 0, z=p1.z}\\\
        local point2 = {x = p2.x, y = 0, z=p2.z}\\\
        return dcsCommon.dist(point1, point2)\\\
    end\\\
    \\\
    \\\
    -- distance between points\\\
    function dcsCommon.dist(point1, point2)     -- returns distance between two points\\\
      -- supports xyz and xy notations\\\
      if not point1 then \\\
        trigger.action.outText(\\\"+++ warning: nil point1 in common:dist\\\", 30)\\\
        point1 = {x=0, y=0, z=0}\\\
      end\\\
\\\
      if not point2 then \\\
        trigger.action.outText(\\\"+++ warning: nil point2 in common:dist\\\", 30)\\\
        point2 = {x=0, y=0, z=0}\\\
        stop.here.now = 1\\\
      end\\\
      \\\
      local p1 = {x = point1.x, y = point1.y}\\\
      if not point1.z then \\\
        p1.z = p1.y\\\
        p1.y = 0\\\
      else \\\
        p1.z = point1.z\\\
      end\\\
      \\\
      local p2 = {x = point2.x, y = point2.y}\\\
      if not point2.z then \\\
        p2.z = p2.y\\\
        p2.y = 0\\\
      else \\\
        p2.z = point2.z\\\
      end\\\
      \\\
      local x = p1.x - p2.x\\\
      local y = p1.y - p2.y \\\
      local z = p1.z - p2.z\\\
      \\\
      return (x*x + y*y + z*z)^0.5\\\
    end\\\
\\\
    function dcsCommon.delta(name1, name2) -- returns distance (in meters) of two named objects\\\
      local n1Pos = Unit.getByName(name1):getPosition().p\\\
      local n2Pos = Unit.getByName(name2):getPosition().p\\\
      return dcsCommon.dist(n1Pos, n2Pos)\\\
    end\\\
\\\
    -- lerp between a and b, x being 0..1 (percentage), clipped to [0..1]\\\
    function dcsCommon.lerp(a, b, x) \\\
        if not a then return 0 end\\\
        if not b then return 0 end\\\
        if not x then return a end\\\
        if x < 0 then x = 0 end \\\
        if x > 1 then x = 1 end \\\
        return a + (b - a ) * x\\\
    end\\\
\\\
    function dcsCommon.bearingFromAtoB(A, B) -- coords in x, z \\\
        if not A then \\\
            trigger.action.outText(\\\"WARNING: no 'A' in bearingFromAtoB\\\", 30)\\\
            return 0\\\
        end\\\
        if not B then\\\
            trigger.action.outText(\\\"WARNING: no 'A' in bearingFromAtoB\\\", 30)\\\
            return 0\\\
        end\\\
        if not A.x then \\\
            trigger.action.outText(\\\"WARNING: no 'A.x' (type A =<\\\" .. type(A) .. \\\">)in bearingFromAtoB\\\", 30)\\\
            return 0\\\
        end\\\
        if not A.y then \\\
            trigger.action.outText(\\\"WARNING: no 'A.x' (type A =<\\\" .. type(A) .. \\\">)in bearingFromAtoB\\\", 30)\\\
            return 0\\\
        end\\\
        if not B.x then \\\
            trigger.action.outText(\\\"WARNING: no 'B.x' (type B =<\\\" .. type(B) .. \\\">)in bearingFromAtoB\\\", 30)\\\
            return 0\\\
        end\\\
        if not B.y then \\\
            trigger.action.outText(\\\"WARNING: no 'B.y' (type B =<\\\" .. type(B) .. \\\">)in bearingFromAtoB\\\", 30)\\\
            return 0\\\
        end\\\
        \\\
        local dx = B.x - A.x\\\
        local dz = B.z - A.z\\\
        local bearing = math.atan2(dz, dx) -- in radiants\\\
        return bearing\\\
    end\\\
\\\
    function dcsCommon.bearingInDegreesFromAtoB(A, B)\\\
        local bearing = dcsCommon.bearingFromAtoB(A, B) -- in rads \\\
        bearing = math.floor(bearing / math.pi * 180)\\\
        if bearing < 0 then bearing = bearing + 360 end\\\
        if bearing > 360 then bearing = bearing - 360 end\\\
        return bearing\\\
    end\\\
    \\\
    function dcsCommon.compassPositionOfARelativeToB(A, B)\\\
        -- warning: is REVERSE in order for bearing, returns a string like 'Sorth', 'Southwest'\\\
        if not A then return \\\"***error:A***\\\" end\\\
        if not B then return \\\"***error:B***\\\" end\\\
        local bearing = dcsCommon.bearingInDegreesFromAtoB(B, A) -- returns 0..360\\\
        if bearing < 23 then return \\\"North\\\" end \\\
        if bearing < 68 then return \\\"NE\\\" end\\\
        if bearing < 112 then return \\\"East\\\" end \\\
        if bearing < 158 then return \\\"SE\\\" end \\\
        if bearing < 202 then return \\\"South\\\" end \\\
        if bearing < 248 then return \\\"SW\\\" end \\\
        if bearing < 292 then return \\\"West\\\" end\\\
        if bearing < 338 then return \\\"NW\\\" end \\\
        return \\\"North\\\"\\\
    end\\\
    \\\
    function dcsCommon.bearing2compass(inrad)\\\
        local bearing = math.floor(inrad / math.pi * 180)\\\
        if bearing < 0 then bearing = bearing + 360 end\\\
        if bearing > 360 then bearing = bearing - 360 end\\\
        return dcsCommon.bearingdegrees2compass(bearing)\\\
    end\\\
    \\\
    function dcsCommon.bearingdegrees2compass(bearing)\\\
        if bearing < 23 then return \\\"North\\\" end \\\
        if bearing < 68 then return \\\"NE\\\" end\\\
        if bearing < 112 then return \\\"East\\\" end \\\
        if bearing < 158 then return \\\"SE\\\" end \\\
        if bearing < 202 then return \\\"South\\\" end \\\
        if bearing < 248 then return \\\"SW\\\" end \\\
        if bearing < 292 then return \\\"West\\\" end\\\
        if bearing < 338 then return \\\"NW\\\" end \\\
        return \\\"North\\\"\\\
    end\\\
    \\\
    function dcsCommon.clockPositionOfARelativeToB(A, B, headingOfBInDegrees)\\\
        -- o'clock notation \\\
        if not A then return \\\"***error:A***\\\" end\\\
        if not B then return \\\"***error:B***\\\" end\\\
        if not headingOfBInDegrees then headingOfBInDegrees = 0 end \\\
        \\\
        local bearing = dcsCommon.bearingInDegreesFromAtoB(B, A) -- returns 0..360\\\
--        trigger.action.outText(\\\"+++comm: oclock - bearing = \\\" .. bearing .. \\\" and inHeading = \\\" .. headingOfBInDegrees, 30) \\\
        bearing = bearing - headingOfBInDegrees\\\
        return dcsCommon.getClockDirection(bearing)\\\
        \\\
    end \\\
    \\\
    -- given a heading, return clock with 0 being 12, 180 being 6 etc.\\\
    function dcsCommon.getClockDirection(direction) -- inspired by cws, improvements my own\\\
        if not direction then return 0 end\\\
        direction = math.fmod (direction, 360)\\\
        while direction < 0 do \\\
            direction = direction + 360\\\
        end\\\
        while direction >= 360 do \\\
            direction = direction - 360\\\
        end\\\
        if direction < 15 then -- special case 12 o'clock past 12 o'clock\\\
            return 12\\\
        end\\\
    \\\
        direction = direction + 15 -- add offset so we get all other times correct\\\
        return math.floor(direction/30)\\\
    \\\
    end\\\
\\\
    function dcsCommon.getGeneralDirection(direction) -- inspired by cws, improvements my own\\\
        if not direction then return \\\"unkown\\\" end\\\
        direction = math.fmod (direction, 360)\\\
        while direction < 0 do \\\
            direction = direction + 360\\\
        end\\\
        while direction >= 360 do \\\
            direction = direction - 360\\\
        end\\\
        if direction < 45 then return \\\"ahead\\\" end    \\\
        if direction < 135 then return \\\"right\\\" end\\\
        if direction < 225 then return \\\"behind\\\" end\\\
        if direction < 315 then return \\\"left\\\" end \\\
        return \\\"ahead\\\"\\\
    end\\\
    \\\
    function dcsCommon.getNauticalDirection(direction) -- inspired by cws, improvements my own\\\
        if not direction then return \\\"unkown\\\" end\\\
        direction = math.fmod (direction, 360)\\\
        while direction < 0 do \\\
            direction = direction + 360\\\
        end\\\
        while direction >= 360 do \\\
            direction = direction - 360\\\
        end\\\
        if direction < 45 then return \\\"ahead\\\" end    \\\
        if direction < 135 then return \\\"starboard\\\" end\\\
        if direction < 225 then return \\\"aft\\\" end\\\
        if direction < 315 then return \\\"port\\\" end \\\
        return \\\"ahead\\\"\\\
    end\\\
\\\
    function dcsCommon.aspectByDirection(direction) -- inspired by cws, improvements my own\\\
        if not direction then return \\\"unkown\\\" end\\\
        direction = math.fmod (direction, 360)\\\
        while direction < 0 do \\\
            direction = direction + 360\\\
        end\\\
        while direction >= 360 do \\\
            direction = direction - 360\\\
        end\\\
        \\\
        if direction < 45 then return \\\"hot\\\" end    \\\
        if direction < 135 then return \\\"beam\\\" end\\\
        if direction < 225 then return \\\"drag\\\" end\\\
        if direction < 315 then return \\\"beam\\\" end \\\
        return \\\"hot\\\"\\\
    end\\\
    \\\
    function dcsCommon.whichSideOfMine(theUnit, target) -- returs two values: -1/1 = left/right and \\\"left\\\"/\\\"right\\\" \\\
        if not theUnit then return nil end \\\
        if not target then return nil end \\\
        local uDOF = theUnit:getPosition() -- returns p, x, y, z Vec3\\\
        -- with x, y, z being the normalised vectors for right, up, forward \\\
        local heading = math.atan2(uDOF.x.z, uDOF.x.x) -- returns rads\\\
        if heading < 0 then\\\
            heading = heading + 2 * math.pi    -- put heading in range of 0 to 2*pi\\\
        end\\\
        -- heading now runs from 0 through 2Pi\\\
        local A = uDOF.p\\\
        local B = target:getPoint() \\\
         \\\
        -- now get bearing from theUnit to target  \\\
        local dx = B.x - A.x\\\
        local dz = B.z - A.z\\\
        local bearing = math.atan2(dz, dx) -- in rads\\\
        if bearing < 0 then\\\
            bearing = bearing + 2 * math.pi    -- make bearing 0 to 2*pi\\\
        end\\\
\\\
        -- we now have bearing to B, and own heading. \\\
        -- subtract own heading from bearing to see at what \\\
        -- bearing target would be if we 'turned the world' so\\\
        -- that theUnit is heading 0\\\
        local dBearing = bearing - heading\\\
        -- if result < 0 or > Pi (=180°), target is left from us\\\
        if dBearing < 0 or dBearing > math.pi then return -1, \\\"left\\\" end\\\
        return 1, \\\"right\\\"\\\
        -- note: no separate case for straight in front or behind\\\
    end\\\
    \\\
    function dcsCommon.randomDegrees()\\\
        local degrees = math.random(360) * 3.14152 / 180\\\
        return degrees\\\
    end\\\
\\\
    function dcsCommon.randomPercent()\\\
        local percent = math.random(100)/100\\\
        return percent\\\
    end\\\
\\\
    function dcsCommon.randomPointOnPerimeter(sourceRadius, x, z) \\\
        return dcsCommon.randomPointInCircle(sourceRadius, sourceRadius-1, x, z)\\\
    end\\\
\\\
    function dcsCommon.randomPointInCircle(sourceRadius, innerRadius, x, z)\\\
        if not x then x = 0 end\\\
        if not z then z = 0 end \\\
        \\\
        --local y = 0\\\
        if not innerRadius then innerRadius = 0 end        \\\
        if innerRadius < 0 then innerRadius = 0 end\\\
        \\\
        local percent = dcsCommon.randomPercent() -- 1 / math.random(100)\\\
        -- now lets get a random degree\\\
        local degrees = dcsCommon.randomDegrees() -- math.random(360) * 3.14152 / 180 -- ok, it's actually radiants. \\\
        local r = (sourceRadius-innerRadius) * percent \\\
        x = x + (innerRadius + r) * math.cos(degrees)\\\
        z = z + (innerRadius + r) * math.sin(degrees)\\\
    \\\
        local thePoint = {}\\\
        thePoint.x = x\\\
        thePoint.y = 0\\\
        thePoint.z = z \\\
        \\\
        return thePoint, degrees\\\
    end\\\
\\\
    function dcsCommon.newPointAtDegreesRange(p1, degrees, radius)\\\
        local rads = degrees * 3.14152 / 180\\\
        local p2 = dcsCommon.newPointAtAngleRange(p1, rads, radius)\\\
        return p2 \\\
    end\\\
    \\\
    function dcsCommon.newPointAtAngleRange(p1, angle, radius)\\\
        local p2 = {}\\\
        p2.x = p1.x + radius * math.cos(angle)\\\
        p2.y = p1.y \\\
        p2.z = p1.z + radius * math.sin(angle)\\\
        return p2 \\\
    end\\\
\\\
    -- get group location: get the group's location by \\\
    -- accessing the fist existing, alive member of the group that it finds\\\
    function dcsCommon.getGroupLocation(group)\\\
        -- nifty trick from mist: make this work with group and group name\\\
        if type(group) == 'string' then -- group name\\\
            group = Group.getByName(group)\\\
        end\\\
        \\\
        -- get all units\\\
        local allUnits = group:getUnits()\\\
\\\
        -- iterate through all members of group until one is alive and exists\\\
        for index, theUnit in pairs(allUnits) do \\\
            if (theUnit:isExist() and theUnit:getLife() > 0) then \\\
                return theUnit:getPosition().p \\\
            end;\\\
        end\\\
\\\
        -- if we get here, there was no live unit \\\
        --trigger.action.outText(\\\"+++cmn: A group has no live units. returning nil\\\", 10)\\\
        return nil \\\
        \\\
    end\\\
\\\
    -- get the group's first Unit that exists and is \\\
    -- alive \\\
    function dcsCommon.getGroupUnit(group)\\\
        if not group then return nil  end\\\
        \\\
        -- nifty trick from mist: make this work with group and group name\\\
        if type(group) == 'string' then -- group name\\\
            group = Group.getByName(group)\\\
        end\\\
        \\\
        if not group:isExist() then return nil end \\\
        \\\
        -- get all units\\\
        local allUnits = group:getUnits()\\\
\\\
        -- iterate through all members of group until one is alive and exists\\\
        for index, theUnit in pairs(allUnits) do \\\
            if Unit.isExist(theUnit) and theUnit:getLife() > 0 then \\\
                return theUnit\\\
            end;\\\
        end\\\
\\\
        -- if we get here, there was no live unit \\\
        --trigger.action.outText(\\\"+++cmn A group has no live units. returning nil\\\", 10)\\\
        return nil \\\
        \\\
    end\\\
\\\
    -- and here the alias\\\
    function dcsCommon.getFirstLivingUnit(group)\\\
        return dcsCommon.getGroupUnit(group)\\\
    end\\\
    \\\
    -- isGroupAlive returns true if there is at least one unit in the group that isn't dead\\\
    function dcsCommon.isGroupAlive(group)\\\
        return (dcsCommon.getGroupUnit(group) ~= nil) \\\
    end\\\
\\\
    function dcsCommon.getLiveGroupUnits(group)\\\
        -- nifty trick from mist: make this work with group and group name\\\
        if type(group) == 'string' then -- group name\\\
            group = Group.getByName(group)\\\
        end\\\
        \\\
        local liveUnits = {}\\\
        -- get all units\\\
        local allUnits = group:getUnits()\\\
\\\
        -- iterate through all members of group until one is alive and exists\\\
        for index, theUnit in pairs(allUnits) do \\\
            if (theUnit:isExist() and theUnit:getLife() > 0) then \\\
                table.insert(liveUnits, theUnit) \\\
            end;\\\
        end\\\
\\\
        -- if we get here, there was no live unit \\\
        return liveUnits\\\
    end\\\
\\\
    function dcsCommon.getGroupTypeString(group) -- convert into comma separated types \\\
        if not group then \\\
            trigger.action.outText(\\\"+++cmn getGroupTypeString: nil group\\\", 30)\\\
            return \\\"\\\" \\\
        end\\\
        if not dcsCommon.isGroupAlive(group) then \\\
            trigger.action.outText(\\\"+++cmn getGroupTypeString: dead group\\\", 30)\\\
            return \\\"\\\" \\\
        end \\\
        local theTypes = \\\"\\\"\\\
        local liveUnits = dcsCommon.getLiveGroupUnits(group)\\\
        for i=1, #liveUnits do \\\
            if i > 1 then theTypes = theTypes .. \\\",\\\" end\\\
            theTypes = theTypes .. liveUnits[i]:getTypeName()\\\
        end\\\
        return theTypes\\\
    end\\\
\\\
    function dcsCommon.getGroupTypes(group) \\\
        if not group then \\\
            trigger.action.outText(\\\"+++cmn getGroupTypes: nil group\\\", 30)\\\
            return {}\\\
        end\\\
        if not dcsCommon.isGroupAlive(group) then \\\
            trigger.action.outText(\\\"+++cmn getGroupTypes: dead group\\\", 30)\\\
            return {}\\\
        end \\\
        local liveUnits = dcsCommon.getLiveGroupUnits(group)\\\
        local unitTypes = {}\\\
        for i=1, #liveUnits do \\\
            table.insert(unitTypes, liveUnits[i]:getTypeName())\\\
        end\\\
        return unitTypes\\\
    end\\\
\\\
    function dcsCommon.getEnemyCoalitionFor(aCoalition)\\\
        if type(aCoalition) == \\\"string\\\" then \\\
            aCoalition = aCoalition:lower()\\\
            if aCoalition == \\\"red\\\" then return 2 end\\\
            if aCoalition == \\\"blue\\\" then return 1 end\\\
            return nil \\\
        end\\\
        if aCoalition == 1 then return 2 end\\\
        if aCoalition == 2 then return 1 end\\\
        return nil\\\
    end\\\
\\\
    function dcsCommon.getACountryForCoalition(aCoalition)\\\
        -- scan the table of countries and get the first country that is part of aCoalition\\\
        -- this is useful if you want to create troops for a coalition but don't know the\\\
        -- coalition's countries \\\
        -- we start with id=0 (Russia), go to id=85 (Slovenia), but skip id = 14\\\
        local i = 0\\\
        while i < 86 do \\\
            if i ~= 14 then \\\
                if (coalition.getCountryCoalition(i) == aCoalition) then return i end\\\
            end\\\
            i = i + 1\\\
        end\\\
        \\\
        return nil\\\
    end\\\
--\\\
--\\\
-- C A L L B A C K   H A N D L E R \\\
--\\\
--\\\
\\\
    -- installing callbacks\\\
    -- based on mist, with optional additional hooks for pre- and post-\\\
    -- processing of the event\\\
    -- when filtering occurs in pre, an alternative 'rejected' handler can be called \\\
    function dcsCommon.addEventHandler(f, pre, post, rejected) -- returns ID \\\
        local handler = {} -- build a wrapper and connect the onEvent\\\
        --dcsCommon.cbID = dcsCommon.cbID + 1 -- increment unique count\\\
        handler.id = dcsCommon.uuid(\\\"eventHandler\\\")\\\
        handler.f = f -- the callback itself\\\
        if (rejected) then handler.rejected = rejected end\\\
        -- now set up pre- and post-processors. defaults are set in place\\\
        -- so pre and post are optional. If pre returns false, the callback will\\\
        -- not be invoked\\\
        if (pre) then handler.pre = pre else handler.pre = dcsCommon.preCall end\\\
        if (post) then handler.post = post else handler.post = dcsCommon.postCall end\\\
        function handler:onEvent(event)\\\
            if not self.pre(event) then \\\
                if dcsCommon.verbose then\\\
--                    trigger.action.outText(\\\"event \\\" .. event.id .. \\\" discarded by pre-processor\\\", 10)\\\
                end\\\
                if (self.rejected) then self.rejected(event) end \\\
                return\\\
            end\\\
            self.f(event) -- call the handler\\\
            self.post(event) -- do post-processing\\\
        end\\\
        world.addEventHandler(handler)\\\
        return handler.id\\\
    end\\\
\\\
    function dcsCommon.preCall(e)\\\
        -- we can filter here\\\
        -- if we return false, the call is abortet\\\
        if dcsCommon.verbose then\\\
            trigger.action.outText(\\\"event \\\" .. e.id .. \\\" received: PRE-PROCESSING\\\", 10)\\\
        end\\\
        return true;\\\
    end;\\\
\\\
    function dcsCommon.postCall(e)\\\
        -- we do pos proccing here \\\
        if dcsCommon.verbose then\\\
            trigger.action.outText(\\\"event \\\" .. e.id .. \\\" received: post proc\\\", 10)\\\
        end\\\
    end\\\
    \\\
    -- highly specific eventhandler for one event only\\\
    -- based on above, with direct filtering built in; skips pre\\\
    -- but does post\\\
    function dcsCommon.addEventHandlerForEventTypes(f, evTypes, post, rejected) -- returns ID \\\
        local handler = {} -- build a wrapper and connect the onEvent\\\
        dcsCommon.cbID = dcsCommon.cbID + 1 -- increment unique count\\\
        handler.id = dcsCommon.cbID\\\
        handler.what = evTypes\\\
        if (rejected) then handler.rejected = rejected end \\\
        \\\
        handler.f = f -- set the callback itself\\\
        -- now set up post-processor. pre is hard-coded to match evType\\\
        -- post is optional. If event.id is not in evTypes, the callback will\\\
        -- not be invoked\\\
        if (post) then handler.post = post else handler.post = dcsCommon.postCall end\\\
        function handler:onEvent(event)\\\
            hasMatch = false;\\\
            for key, evType in pairs(self.what) do\\\
                if evType == event.id then\\\
                    hasMatch = true;\\\
                    break;\\\
                end;\\\
            end;\\\
            if not hasMatch then \\\
                if dcsCommon.verbose then\\\
                    trigger.action.outText(\\\"event \\\" .. e.id .. \\\" discarded - not in whitelist evTypes\\\", 10)\\\
                end\\\
                if (self.rejected) then self.rejected(event) end \\\
                return;\\\
            end;\\\
            \\\
            self.f(event) -- call the actual handler as passed to us\\\
            self.post(event) -- do post-processing \\\
        end\\\
        world.addEventHandler(handler) -- add to event handlers\\\
        return handler.id\\\
    end\\\
    \\\
    \\\
    \\\
    -- remove event handler / callback, identical to Mist \\\
    -- note we don't call world.removeEventHandler, but rather directly \\\
    -- access world.eventHandlers directly and remove kvp directly.\\\
    function dcsCommon.removeEventHandler(id)\\\
        for key, handler in pairs(world.eventHandlers) do\\\
            if handler.id and handler.id == id then\\\
                world.eventHandlers[key] = nil\\\
                return true\\\
            end\\\
        end\\\
        return false\\\
    end\\\
\\\
--\\\
--\\\
-- C L O N I N G \\\
--\\\
--\\\
    -- topClone is a shallow clone of orig, only top level is iterated,\\\
    -- all values are ref-copied\\\
    function dcsCommon.topClone(orig)\\\
        if not orig then return nil end \\\
        local orig_type = type(orig)\\\
        local copy\\\
        if orig_type == 'table' then\\\
            copy = {}\\\
            for orig_key, orig_value in pairs(orig) do\\\
                copy[orig_key] = orig_value\\\
            end\\\
        else -- number, string, boolean, etc\\\
            copy = orig\\\
        end\\\
        return copy\\\
    end\\\
\\\
    -- clone is a recursive clone which will also clone\\\
    -- deeper levels, as used in units \\\
    function dcsCommon.clone(orig, stripMeta)\\\
        if not orig then return nil end \\\
        local orig_type = type(orig)\\\
        local copy\\\
        if orig_type == 'table' then\\\
            copy = {}\\\
            for orig_key, orig_value in next, orig, nil do\\\
                copy[dcsCommon.clone(orig_key)] = dcsCommon.clone(orig_value)\\\
            end\\\
            if not stripMeta then \\\
                -- also connect meta data\\\
                setmetatable(copy, dcsCommon.clone(getmetatable(orig)))\\\
            else \\\
                -- strip all except string, and for strings use a fresh string \\\
                if type(copy) == \\\"string\\\" then \\\
                    local tmp = \\\"\\\"\\\
                    tmp = tmp .. copy -- will get rid of any foreign metas for string \\\
                    copy = tmp \\\
                end\\\
            end\\\
        else -- number, string, boolean, etc\\\
            copy = orig\\\
        end\\\
        return copy\\\
    end\\\
\\\
    function dcsCommon.copyArray(inArray)\\\
        if not inArray then return nil end \\\
        \\\
        -- warning: this is a ref copy!\\\
        local theCopy = {}\\\
        for idx, element in pairs(inArray) do \\\
            table.insert(theCopy, element)\\\
        end\\\
        return theCopy \\\
    end\\\
--\\\
-- \\\
-- S P A W N I N G \\\
-- \\\
-- \\\
\\\
    function dcsCommon.createEmptyGroundGroupData (name)\\\
        local theGroup = {} -- empty group\\\
        theGroup.visible = false\\\
        theGroup.taskSelected = true\\\
        -- theGroup.route = {}\\\
        -- theGroup.groupId = id\\\
        theGroup.tasks = {}\\\
        -- theGroup.hidden = false -- hidden on f10?\\\
\\\
        theGroup.units = { } -- insert units here! -- use addUnitToGroupData\\\
\\\
        theGroup.x = 0\\\
        theGroup.y = 0\\\
        theGroup.name = name\\\
        -- theGroup.start_time = 0\\\
        theGroup.task = \\\"Ground Nothing\\\"\\\
        \\\
        return theGroup\\\
    end;\\\
\\\
    function dcsCommon.createEmptyAircraftGroupData (name)\\\
        local theGroup = dcsCommon.createEmptyGroundGroupData(name)--{} -- empty group\\\
\\\
        theGroup.task = \\\"Nothing\\\" -- can be others, like Transport, CAS, etc\\\
        -- returns with empty route\\\
        theGroup.route = dcsCommon.createEmptyAircraftRouteData() -- we can add points here \\\
        return theGroup\\\
    end;\\\
\\\
    function dcsCommon.createAircraftRoutePointData(x, z, altitudeInFeet, knots, altType, action)\\\
        local rp = {}\\\
        rp.x = x\\\
        rp.y = z\\\
        rp.action = \\\"Turning Point\\\"\\\
        rp.type = \\\"Turning Point\\\"\\\
        if action then rp.action = action; rp.type = action end -- warning: may not be correct, need to verify later\\\
        rp.alt = altitudeInFeet * 0.3048\\\
        rp.speed = knots * 0.514444 -- we use \\\
        rp.alt_type = \\\"BARO\\\"\\\
        if (altType) then rp.alt_type = altType end \\\
        return rp\\\
    end\\\
\\\
    function dcsCommon.addRoutePointDataToRouteData(inRoute, x, z, altitudeInFeet, knots, altType, action)\\\
        local p = dcsCommon.createAircraftRoutePointData(x, z, altitudeInFeet, knots, altType, action)\\\
        local thePoints = inRoute.points \\\
        table.insert(thePoints, p)\\\
    end\\\
    \\\
    function dcsCommon.addRoutePointDataToGroupData(group, x, z, altitudeInFeet, knots, altType, action)\\\
        if not group.route then group.route = dcsCommon.createEmptyAircraftRouteData() end\\\
        local theRoute = group.route \\\
        dcsCommon.addRoutePointDataToRouteData(theRoute, x, z, altitudeInFeet, knots, altType, action)\\\
    end\\\
\\\
    function dcsCommon.addRoutePointForGroupData(theGroup, theRP)\\\
        if not theGroup then return end \\\
        if not theGroup.route then theGroup.route = dcsCommon.createEmptyAircraftRouteData() end\\\
        \\\
        local theRoute = theGroup.route \\\
        local thePoints = theRoute.points \\\
        table.insert(thePoints, theRP)\\\
    end\\\
    \\\
    function dcsCommon.createEmptyAircraftRouteData()\\\
        local route = {}\\\
        route.points = {}\\\
        return route\\\
    end\\\
\\\
    function dcsCommon.createTakeOffFromParkingRoutePointData(aerodrome)\\\
        if not aerodrome then return nil end \\\
            \\\
        local rp = {}    \\\
        local freeParkingSlot = dcsCommon.getFirstFreeParkingSlot(aerodrome, 104) -- get big slot first \\\
        if not freeParkingSlot then \\\
            freeParkingSlot = dcsCommon.getFirstFreeParkingSlot(aerodrome) -- try any size\\\
        end\\\
            \\\
        if not freeParkingSlot then \\\
            trigger.action.outText(\\\"civA: no free parking at \\\" .. aerodrome:getName(), 30)\\\
            return nil \\\
        end\\\
            \\\
        local p = freeParkingSlot.vTerminalPos\\\
            \\\
        rp.airdromeId = aerodrome:getID() \\\
        rp.x = p.x\\\
        rp.y = p.z\\\
        rp.alt = p.y \\\
        rp.action = \\\"From Parking Area\\\"\\\
        rp.type = \\\"TakeOffParking\\\"\\\
            \\\
        rp.speed = 100; -- in m/s? If so, that's 360 km/h \\\
        rp.alt_type = \\\"BARO\\\"\\\
        return rp\\\
    end\\\
\\\
    function dcsCommon.createOverheadAirdromeRoutPintData(aerodrome)\\\
        if not aerodrome then return nil end \\\
        local rp = {}            \\\
        local p = aerodrome:getPoint()\\\
        rp.x = p.x\\\
        rp.y = p.z\\\
        rp.alt = p.y + 2000 -- 6000 ft overhead\\\
        rp.action = \\\"Turning Point\\\"\\\
        rp.type = \\\"Turning Point\\\"\\\
            \\\
        rp.speed = 133; -- in m/s? If so, that's 360 km/h \\\
        rp.alt_type = \\\"BARO\\\"\\\
        return rp\\\
    end\\\
    \\\
\\\
    function dcsCommon.createLandAtAerodromeRoutePointData(aerodrome)\\\
        if not aerodrome then return nil end \\\
            \\\
        local rp = {}            \\\
        local p = aerodrome:getPoint()\\\
        rp.airdromeId = aerodrome:getID() \\\
        rp.x = p.x\\\
        rp.y = p.z\\\
        rp.alt = p.y \\\
        rp.action = \\\"Landing\\\"\\\
        rp.type = \\\"Land\\\"\\\
            \\\
        rp.speed = 100; -- in m/s? If so, that's 360 km/h \\\
        rp.alt_type = \\\"BARO\\\"\\\
        return rp\\\
    end\\\
\\\
    \\\
    function dcsCommon.createRPFormationData(findex) -- must be added as \\\"task\\\" to an RP. use 4 for Echelon right\\\
        local task = {}\\\
        task.id = \\\"ComboTask\\\"\\\
        local params = {}\\\
        task.params = params\\\
        local tasks = {}\\\
        params.tasks = tasks\\\
        local t1 = {}\\\
        tasks[1] = t1\\\
        t1.number = 1\\\
        t1.auto = false \\\
        t1.id = \\\"WrappedAction\\\"\\\
        t1.enabled = true\\\
        local t1p = {}\\\
        t1.params = t1p\\\
        local action = {}\\\
        t1p.action = action \\\
        action.id = \\\"Option\\\"\\\
        local ap = {}\\\
        action.params = ap\\\
        ap.variantIndex = 3\\\
        ap.name = 5 -- AI.Option.Air.ID 5 = Formation \\\
        ap.formationIndex = findex -- 4 is echelon_right\\\
        ap.value = 262147\\\
        \\\
        return task \\\
    end\\\
\\\
    function dcsCommon.addTaskDataToRP(theTask, theGroup, rpIndex)\\\
        local theRoute = theGroup.route\\\
        local thePoints = theRoute.points\\\
        local rp = thePoints[rpIndex]\\\
        rp.task = theTask\\\
    end\\\
    \\\
    -- create a minimal payload table that is compatible with creating \\\
    -- a unit. you may need to alter this before adding the unit to\\\
    -- the mission. all params optional \\\
    function dcsCommon.createPayload(fuel, flare, chaff, gun) \\\
        local payload = {}\\\
        payload.pylons = {}\\\
        if not fuel then fuel = 1000 end -- in kg. check against fuelMassMax in type desc\\\
        if not flare then flare = 0 end\\\
        if not chaff then chaff = 0 end\\\
        if not gun then gun = 0 end\\\
        return payload \\\
        \\\
    end\\\
\\\
    function dcsCommon.createCallsign(cs) \\\
        local callsign = {}\\\
        callsign[1] = 1\\\
        callsign[2] = 1\\\
        callsign[3] = 1\\\
        if not cs then cs = \\\"Enfield11\\\" end\\\
        callsign.name = cs\\\
        return callsign\\\
    end\\\
    \\\
\\\
    -- create the data table required to spawn a unit.\\\
    -- unit types are defined in https://github.com/mrSkortch/DCS-miscScripts/tree/master/ObjectDB\\\
    function dcsCommon.createGroundUnitData(name, unitType, transportable)\\\
        local theUnit = {}\\\
        unitType = dcsCommon.trim(unitType)\\\
        theUnit.type = unitType -- e.g. \\\"LAV-25\\\",\\\
        if not transportable then transportable = false end -- elaborate, not requried code\\\
        theUnit.transportable = {[\\\"randomTransportable\\\"] = transportable} \\\
        -- theUnit.unitId = id \\\
        theUnit.skill = \\\"Average\\\" -- always average \\\
        theUnit.x = 0 -- make it zero, zero!\\\
        theUnit.y = 0\\\
        theUnit.name = name\\\
        theUnit.playerCanDrive = false\\\
        theUnit.heading = 0\\\
        return theUnit\\\
    end \\\
\\\
    function dcsCommon.createAircraftUnitData(name, unitType, transportable, altitude, speed, heading)\\\
        local theAirUnit = dcsCommon.createGroundUnitData(name, unitType, transportable)\\\
        theAirUnit.alt = 100 -- make it 100m\\\
        if altitude then theAirUnit.alt = altitude end \\\
        theAirUnit.alt_type = \\\"RADIO\\\" -- AGL\\\
        theAirUnit.speed = 77 -- m/s --> 150 knots\\\
        if speed then theAirUnit.speed = speed end \\\
        if heading then theAirUnit.heading = heading end \\\
        theAirUnit.payload = dcsCommon.createPayload()\\\
        theAirUnit.callsign = dcsCommon.createCallsign()\\\
        return theAirUnit\\\
    end\\\
    \\\
\\\
    function dcsCommon.addUnitToGroupData(theUnit, theGroup, dx, dy, heading)\\\
        -- add a unit to a group, and place it at dx, dy of group's position,\\\
        -- taking into account unit's own current location\\\
        if not dx then dx = 0 end\\\
        if not dy then dy = 0 end\\\
        if not heading then heading = 0 end\\\
        theUnit.x = theUnit.x + dx + theGroup.x\\\
        theUnit.y = theUnit.y + dy + theGroup.y \\\
        theUnit.heading = heading\\\
        table.insert(theGroup.units, theUnit)\\\
    end;\\\
\\\
    function dcsCommon.createSingleUnitGroup(name, theUnitType, x, z, heading) \\\
        -- create the container \\\
        local theNewGroup = dcsCommon.createEmptyGroundGroupData(name)\\\
        local aUnit = {}\\\
        aUnit = dcsCommon.createGroundUnitData(name .. \\\"-1\\\", theUnitType, false)\\\
--        trigger.action.outText(\\\"dcsCommon - unit name retval \\\" .. aUnit.name, 30)\\\
        dcsCommon.addUnitToGroupData(aUnit, theNewGroup, x, z, heading)\\\
        return theNewGroup\\\
    end\\\
    \\\
\\\
    function dcsCommon.arrangeGroupDataIntoFormation(theNewGroup, radius, minDist, formation, innerRadius)\\\
        -- formations:\\\
        --    (default) \\\"line\\\" (left to right along x) -- that is Y direction\\\
        --    \\\"line_v\\\" a line top to bottom -- that is X direction\\\
        --    \\\"chevron\\\" - left to right middle too top\\\
        --    \\\"scattered\\\", \\\"random\\\" -- random, innerRadius used to clear area in center\\\
        --       \\\"circle\\\", \\\"circle_forward\\\" -- circle, forward facing\\\
        --    \\\"circle_in\\\" -- circle, inwarf facing\\\
        --    \\\"circle_out\\\" -- circle, outward facing\\\
        --    \\\"grid\\\", \\\"square\\\", \\\"rect\\\" -- optimal rectangle\\\
        --    \\\"2cols\\\", \\\"2deep\\\" -- 2 columns, n deep \\\
        --    \\\"2wide\\\" -- 2 columns wide, 2 deep \\\
\\\
        local num = #theNewGroup.units \\\
        \\\
        -- now do the formation stuff\\\
        -- make sure that they keep minimum  distance \\\
--        trigger.action.outText(\\\"dcsCommon - processing formation \\\" .. formation .. \\\" with radius = \\\" .. radius, 30)\\\
        if formation == \\\"LINE_V\\\" then \\\
            -- top to bottom in zone (heding 0). -- will run through x-coordinate \\\
            -- use entire radius top to bottom \\\
            local currX = -radius\\\
            local increment = radius * 2/(num - 1) -- MUST NOT TRY WITH 1 UNIT!\\\
            for i=1, num do\\\
            \\\
                local u = theNewGroup.units[i]\\\
--                trigger.action.outText(\\\"formation unit \\\" .. u.name .. \\\" currX = \\\" .. currX, 30)\\\
                u.x = currX\\\
                currX = currX + increment\\\
            end\\\
        \\\
        elseif formation == \\\"LINE\\\" then \\\
            -- left to right in zone. runs through Y\\\
            -- left and right are y because at heading 0, forward is x (not y as expected)\\\
            -- if only one, place in middle of circle and be done \\\
            if num == 1 then \\\
                -- nothing. just stay in the middle \\\
            else \\\
                local currY = -radius\\\
                local increment = radius * 2/(num - 1) -- MUST NOT TRY WITH 1 UNIT!\\\
                for i=1, num do\\\
                    local u = theNewGroup.units[i]\\\
--                    trigger.action.outText(\\\"formation unit \\\" .. u.name .. \\\" currX = \\\" .. currY, 30)\\\
                    u.y = currY\\\
                    currY = currY + increment\\\
                end    \\\
            end \\\
            \\\
        elseif formation == \\\"CHEVRON\\\" then \\\
            -- left to right in zone. runs through Y\\\
            -- left and right are y because at heading 0, forward is x (not y as expected)\\\
            local currY = -radius\\\
            local currX = 0\\\
            local incrementY = radius * 2/(num - 1) -- MUST NOT TRY WITH 1 UNIT!\\\
            local incrementX = radius * 2/(num - 1) -- MUST NOT TRY WITH 1 UNIT!\\\
            for i=1, num do\\\
                local u = theNewGroup.units[i]\\\
--                trigger.action.outText(\\\"formation unit \\\" .. u.name .. \\\" currX = \\\" .. currX .. \\\" currY = \\\" .. currY, 30)\\\
                u.x = currX\\\
                u.y = currY\\\
                -- calc coords for NEXT iteration\\\
                currY = currY + incrementY -- march left to right\\\
                if i < num / 2 then -- march up\\\
                    currX = currX + incrementX \\\
                elseif i == num / 2 then -- even number, keep height\\\
                    currX = currX + 0 \\\
                else \\\
                    currX = currX - incrementX -- march down \\\
                end \\\
                -- note: when unit number even, the wedge is sloped. may need an odd/even test for better looks\\\
            end    \\\
\\\
        elseif formation == \\\"SCATTERED\\\" or formation == \\\"RANDOM\\\" then \\\
            -- use randomPointInCircle and tehn iterate over all vehicles for mindelta\\\
            processedUnits = {}\\\
            for i=1, num do\\\
                local emergencyBreak = 1 -- prevent endless loop\\\
                local lowDist = 10000\\\
                local uPoint = {}\\\
                local thePoint = {}\\\
                repeat     -- get random point until mindistance to all is kept or emergencybreak\\\
                    thePoint = dcsCommon.randomPointInCircle(radius, innerRadius) -- returns x, 0, z\\\
                    -- check if too close to others\\\
                    for idx, rUnit in pairs(processedUnits) do -- get min dist to all positioned units\\\
                        --trigger.action.outText(\\\"rPnt: thePoint =  \\\" .. dcsCommon.point2text(thePoint), 30)\\\
                        uPoint.x = rUnit.x\\\
                        uPoint.y = 0\\\
                        uPoint.z = rUnit.y \\\
                        --trigger.action.outText(\\\"rPnt: uPoint =  \\\" .. dcsCommon.point2text(uPoint), 30)\\\
                        local dist = dcsCommon.dist(thePoint, uPoint) -- measure distance to unit\\\
                        if (dist < lowDist) then lowDist = dist end\\\
                    end\\\
                    emergencyBreak = emergencyBreak + 1\\\
                until (emergencyBreak > 20) or (lowDist > minDist)\\\
                -- we have random x, y \\\
                local u = theNewGroup.units[i] -- get unit to position\\\
                u.x = thePoint.x\\\
                u.y = thePoint.z -- z --> y mapping! \\\
                -- now add the unit to the 'processed' set \\\
                table.insert(processedUnits, u)\\\
            end    \\\
\\\
        elseif dcsCommon.stringStartsWith(formation, \\\"CIRCLE\\\") then\\\
            -- units are arranged on perimeter of circle defined by radius \\\
--            trigger.action.outText(\\\"formation circle detected\\\", 30)\\\
            local currAngle = 0\\\
            local angleInc = 2 * 3.14157 / num -- increase per spoke \\\
            for i=1, num do\\\
                local u = theNewGroup.units[i] -- get unit \\\
                u.x = radius * math.cos(currAngle)\\\
                u.y = radius * math.sin(currAngle)\\\
                \\\
                -- now baldower out heading \\\
                -- circle, circle_forward no modifier of heading\\\
                if dcsCommon.stringStartsWith(formation, \\\"CIRCLE_IN\\\") then \\\
                    -- make the heading inward faceing - that's angle + pi\\\
                    u.heading = u.heading + currAngle + 3.14157\\\
                elseif dcsCommon.stringStartsWith(formation, \\\"CIRCLE_OUT\\\") then \\\
                    u.heading = u.heading + currAngle + 0\\\
                end\\\
\\\
                currAngle = currAngle + angleInc\\\
            end\\\
        elseif formation == \\\"GRID\\\" or formation == \\\"SQUARE\\\" or formation == \\\"RECT\\\" then \\\
            if num < 2 then return end \\\
            -- arrange units in an w x h grid\\\
            -- e-g- 12 units = 4 x 3. \\\
            -- calculate w \\\
            local w = math.floor(num^(0.5) + 0.5)\\\
            dcsCommon.arrangeGroupInNColumns(theNewGroup, w, radius)\\\
            --[[--\\\
            local h = math.floor(num / w)\\\
            --trigger.action.outText(\\\"AdcsC: num=\\\" .. num .. \\\" w=\\\" .. w .. \\\"h=\\\" .. h .. \\\" -- num%w=\\\" .. num%w, 30)\\\
            if (num % w) > 0 then \\\
                h = h + 1\\\
            end\\\
            \\\
            --trigger.action.outText(\\\"BdcsC: num=\\\" .. num .. \\\" w=\\\" .. w .. \\\"h=\\\" .. h, 30)\\\
            \\\
            -- now w * h always >= num and num items fir in that grid\\\
            -- w is width, h is height, of course :) \\\
            -- now calculat xInc and yInc\\\
            local i = 1\\\
            local xInc = 0 \\\
            if w > 1 then xInc = 2 * radius / (w-1) end\\\
            local yInc = 0\\\
            if h > 1 then yInc = 2 * radius / (h-1) end \\\
            local currY = radius \\\
            if h < 2 then currY = 0 end -- special:_ place in Y middle if only one row)\\\
            while h > 0 do \\\
                local currX = radius \\\
                local wCnt = w \\\
                while wCnt > 0 and (i <= num) do \\\
                    local u = theNewGroup.units[i] -- get unit \\\
                    u.x = currX\\\
                    u.y = currY\\\
                    currX = currX - xInc\\\
                    wCnt = wCnt - 1\\\
                    i = i + 1\\\
                end\\\
                currY = currY - yInc \\\
                h = h - 1\\\
            end\\\
            --]]--\\\
        elseif formation == \\\"2DEEP\\\" or formation == \\\"2COLS\\\" then\\\
            if num < 2 then return end \\\
            -- arrange units in an 2 x h grid\\\
            local w = 2\\\
            dcsCommon.arrangeGroupInNColumnsDeep(theNewGroup, w, radius)\\\
\\\
        elseif formation == \\\"2WIDE\\\" then\\\
            if num < 2 then return end \\\
            -- arrange units in an 2 x h grid\\\
            local w = 2\\\
            dcsCommon.arrangeGroupInNColumns(theNewGroup, w, radius)\\\
        else \\\
            trigger.action.outText(\\\"dcsCommon - unknown formation: \\\" .. formation, 30)\\\
        end\\\
    \\\
    end\\\
    \\\
    function dcsCommon.arrangeGroupInNColumns(theNewGroup, w, radius)\\\
        local num = #theNewGroup.units\\\
        local h = math.floor(num / w)\\\
        if (num % w) > 0 then \\\
            h = h + 1\\\
        end\\\
        local i = 1\\\
        local xInc = 0 \\\
        if w > 1 then xInc = 2 * radius / (w-1) end\\\
        local yInc = 0\\\
        if h > 1 then yInc = 2 * radius / (h-1) end \\\
        local currY = radius \\\
        if h < 2 then currY = 0 end -- special:_ place in Y middle if only one row)\\\
        while h > 0 do \\\
            local currX = radius \\\
            local wCnt = w \\\
            while wCnt > 0 and (i <= num) do \\\
                local u = theNewGroup.units[i] -- get unit \\\
                u.x = currX\\\
                u.y = currY\\\
                currX = currX - xInc\\\
                wCnt = wCnt - 1\\\
                i = i + 1\\\
            end\\\
            currY = currY - yInc \\\
            h = h - 1\\\
        end\\\
    end\\\
    \\\
    function dcsCommon.arrangeGroupInNColumnsDeep(theNewGroup, w, radius)\\\
        local num = #theNewGroup.units\\\
        local h = math.floor(num / w)\\\
        if (num % w) > 0 then \\\
            h = h + 1\\\
        end\\\
        local i = 1\\\
        local yInc = 0 \\\
        if w > 1 then yInc = 2 * radius / (w-1) end\\\
        local xInc = 0\\\
        if h > 1 then xInc = 2 * radius / (h-1) end \\\
        local currX = radius \\\
        if h < 2 then currX = 0 end -- special:_ place in Y middle if only one row)\\\
        while h > 0 do \\\
            local currY = radius \\\
            local wCnt = w \\\
            while wCnt > 0 and (i <= num) do \\\
                local u = theNewGroup.units[i] -- get unit \\\
                u.x = currX\\\
                u.y = currY\\\
                currY = currY - yInc\\\
                wCnt = wCnt - 1\\\
                i = i + 1\\\
            end\\\
            currX = currX - xInc \\\
            h = h - 1\\\
        end\\\
    end\\\
    \\\
    \\\
    function dcsCommon.createGroundGroupWithUnits(name, theUnitTypes, radius, minDist, formation, innerRadius)\\\
        if not minDist then minDist = 4 end -- meters\\\
        if not formation then formation = \\\"line\\\" end \\\
        if not radius then radius = 30 end -- meters \\\
        if not innerRadius then innerRadius = 0 end\\\
        formation = formation:upper()\\\
        -- theUnitTypes can be either a single string or a table of strings\\\
        -- see here for TypeName https://github.com/mrSkortch/DCS-miscScripts/tree/master/ObjectDB\\\
        -- formation defines how the units are going to be arranged in the\\\
        -- formation specified. \\\
        -- formations:\\\
        --    (default) \\\"line\\\" (left to right along x) -- that is Y direction\\\
        --    \\\"line_V\\\" a line top to bottom -- that is X direction\\\
        --    \\\"chevron\\\" - left to right middle too top\\\
        --    \\\"scattered\\\", \\\"random\\\" -- random, innerRadius used to clear area in center\\\
        --       \\\"circle\\\", \\\"circle_forward\\\" -- circle, forward facing\\\
        --    \\\"circle_in\\\" -- circle, inwarf facing\\\
        --    \\\"circle_out\\\" -- circle, outward facing\\\
\\\
        -- first, we create a group\\\
        local theNewGroup = dcsCommon.createEmptyGroundGroupData(name)\\\
        \\\
        -- now add a single unit or multiple units\\\
        if type(theUnitTypes) ~= \\\"table\\\" then \\\
--            trigger.action.outText(\\\"dcsCommon - i am here\\\", 30)\\\
--            trigger.action.outText(\\\"dcsCommon - name \\\" .. name, 30)\\\
--            trigger.action.outText(\\\"dcsCommon - unit type \\\" .. theUnitTypes, 30)\\\
            \\\
            local aUnit = {}\\\
            aUnit = dcsCommon.createGroundUnitData(name .. \\\"-1\\\", theUnitTypes, false)\\\
--            trigger.action.outText(\\\"dcsCommon - unit name retval \\\" .. aUnit.name, 30)\\\
            dcsCommon.addUnitToGroupData(aUnit, theNewGroup, 0, 0) -- create with data at location (0,0)\\\
            return theNewGroup\\\
        end \\\
\\\
        -- if we get here, theUnitTypes is a table\\\
        -- now loop and create a unit for each table\\\
        local num = 1\\\
        for key, theType in pairs(theUnitTypes) do \\\
            -- trigger.action.outText(\\\"+++dcsC: creating unit \\\" .. name .. \\\"-\\\" .. num .. \\\": \\\" .. theType, 30)\\\
            local aUnit = dcsCommon.createGroundUnitData(name .. \\\"-\\\"..num, theType, false)\\\
            dcsCommon.addUnitToGroupData(aUnit, theNewGroup, 0, 0)\\\
            num = num + 1\\\
        end\\\
        \\\
        dcsCommon.arrangeGroupDataIntoFormation(theNewGroup, radius, minDist, formation, innerRadius)\\\
        return theNewGroup\\\
\\\
    \\\
    end\\\
\\\
-- create a new group, based on group in mission. Groups coords are 0,0 for group and all\\\
-- x,y and heading\\\
    function dcsCommon.createGroupDataFromLiveGroup(name, newName) \\\
        if not newName then newName = dcsCommon.uuid(\\\"uniqName\\\") end\\\
        -- get access to the group\\\
        local liveGroup = Group.getByName(name)\\\
        if not liveGroup then return nil end\\\
        -- get the categorty\\\
        local cat = liveGroup:getCategory()\\\
        local theNewGroup = {}\\\
        \\\
        -- create a new empty group at (0,0) \\\
        if cat == Group.Category.AIRPLANE or cat == Group.Category.HELICOPTER then \\\
            theNewGroup = dcsCommon.createEmptyAircraftGroupData(newName)\\\
        elseif cat == Group.Category.GROUND then\\\
            theNewGroup = dcsCommon.createEmptyGroudGroupData(newName)\\\
        else \\\
            trigger.action.outText(\\\"dcsCommon - unknown category: \\\" .. cat, 30)\\\
            return nil\\\
        end\\\
        \\\
\\\
        -- now get all units from live group and create data units\\\
        -- note that unit data for group has x=0, y=0\\\
        liveUnits = liveGroup:getUnits()\\\
        \\\
        for index, theUnit in pairs(liveUnits) do \\\
            -- for each unit we get the desc \\\
            local desc = theUnit:getDesc() -- of interest is only typename \\\
            local newUnit = dcsCommon.createGroundUnitData(dcsCommon.uuid(newName),\\\
                                                           desc.typeName,\\\
                                                           false)\\\
            -- we now basically have a ground unit at (0,0) \\\
            -- add mandatory fields by type\\\
            if cat == Group.Category.AIRPLANE or cat == Group.Category.HELICOPTER then \\\
                newUnit.alt = 100 -- make it 100m\\\
                newUnit.alt_type = \\\"RADIO\\\" -- AGL\\\
                newUnit.speed = 77 -- m/s --> 150 knots\\\
                newUnit.payload = dcsCommon.createPayload() -- empty payload\\\
                newUnit.callsign = dcsCommon.createCallsign() -- 'enfield11'\\\
                \\\
            elseif cat == Group.Category.GROUND then\\\
                -- we got all we need\\\
            else \\\
                -- trigger.action.outText(\\\"dcsCommon - unknown category: \\\" .. cat, 30)\\\
                -- return nil\\\
                -- we also got all we need\\\
            end            \\\
            \\\
        end\\\
    \\\
    end;\\\
    \\\
    function dcsCommon.rotatePointAroundOriginRad(inX, inY, angle) -- angle in degrees\\\
        local c = math.cos(angle)\\\
        local s = math.sin(angle)\\\
        local px\\\
        local py \\\
        px = inX * c - inY * s\\\
        py = inX * s + inY * c\\\
        return px, py        \\\
    end\\\
    \\\
    function dcsCommon.rotatePointAroundOrigin(inX, inY, angle) -- angle in degrees\\\
        local rads =  3.14152 / 180 -- convert to radiants. \\\
        angle = angle * rads -- turns into rads\\\
        local px, py = dcsCommon.rotatePointAroundOriginRad(inX, inY, angle)\\\
        return px, py        \\\
    end\\\
    \\\
    function dcsCommon.rotatePointAroundPointRad(x, y, px, py, angle)\\\
        x = x - px \\\
        y = y - py\\\
        x, y = dcsCommon.rotatePointAroundOriginRad(x, y, angle)\\\
        x = x + px \\\
        y = y + py \\\
        return x, y\\\
    end\\\
\\\
    function dcsCommon.rotatePointAroundPointDeg(x, y, px, py, degrees)\\\
        x, y = dcsCommon.rotatePointAroundPointRad(x, y, px, py, degrees * 3.14152 / 180)\\\
        return x, y\\\
    end\\\
\\\
    -- rotates a Vec3-base inPoly on XZ pane around inPoint on XZ pane\\\
     function dcsCommon.rotatePoly3AroundVec3Rad(inPoly, inPoint, rads)\\\
        local outPoly = {}\\\
        for idx, aVertex in pairs(inPoly) do \\\
            local x, z = dcsCommon.rotatePointAroundPointRad(aVertex.x, aVertex.z, inPoint.x, inPoint.z, rads)        \\\
            local v3 = {x = x, y = aVertex.y, z = z}\\\
            outPoly[idx] = v3\\\
        end \\\
        return outPoly \\\
    end\\\
\\\
    function dcsCommon.rotateUnitData(theUnit, degrees, cx, cz)\\\
        if not cx then cx = 0 end\\\
        if not cz then cz = 0 end\\\
        local cy = cz \\\
        --trigger.action.outText(\\\"+++dcsC:rotGrp cy,cy = \\\"..cx .. \\\",\\\" .. cy, 30)\\\
        \\\
        local rads = degrees *  3.14152 / 180\\\
        do\\\
            theUnit.x = theUnit.x - cx -- MOVE TO ORIGIN OF ROTATION\\\
            theUnit.y = theUnit.y - cy                 \\\
            theUnit.x, theUnit.y = dcsCommon.rotatePointAroundOrigin(theUnit.x, theUnit.y, degrees)\\\
            theUnit.x = theUnit.x + cx -- MOVE BACK \\\
            theUnit.y = theUnit.y + cy                 \\\
\\\
            -- may also want to increase heading by degrees\\\
            theUnit.heading = theUnit.heading + rads \\\
        end\\\
    end\\\
    \\\
\\\
    function dcsCommon.rotateGroupData(theGroup, degrees, cx, cz)\\\
        if not cx then cx = 0 end\\\
        if not cz then cz = 0 end\\\
        local cy = cz \\\
        --trigger.action.outText(\\\"+++dcsC:rotGrp cy,cy = \\\"..cx .. \\\",\\\" .. cy, 30)\\\
        \\\
        local rads = degrees *  3.14152 / 180\\\
        -- turns all units in group around the group's center by degrees.\\\
        -- may also need to turn individual units by same amount\\\
        for i, theUnit in pairs (theGroup.units) do\\\
            theUnit.x = theUnit.x - cx -- MOVE TO ORIGIN OF ROTATION\\\
            theUnit.y = theUnit.y - cy                 \\\
            theUnit.x, theUnit.y = dcsCommon.rotatePointAroundOrigin(theUnit.x, theUnit.y, degrees)\\\
            theUnit.x = theUnit.x + cx -- MOVE BACK \\\
            theUnit.y = theUnit.y + cy                 \\\
\\\
            -- may also want to increase heading by degrees\\\
            theUnit.heading = theUnit.heading + rads \\\
            -- now kill psi if it existed before \\\
            -- theUnit.psi = nil\\\
            -- better code: psi is always -heading. Nobody knows what psi is, though\\\
            if theUnit.psi then \\\
                theUnit.psi = -theUnit.heading \\\
            end\\\
        end\\\
    end\\\
\\\
    function dcsCommon.offsetGroupData(theGroup, dx, dy)\\\
        -- add dx and dy to group's and all unit's coords\\\
        for i, theUnit in pairs (theGroup.units) do \\\
            theUnit.x = theUnit.x + dx\\\
            theUnit.y = theUnit.y + dy\\\
        end\\\
        \\\
        theGroup.x = theGroup.x + dx\\\
        theGroup.y = theGroup.y + dy \\\
    end\\\
    \\\
    function dcsCommon.moveGroupDataTo(theGroup, xAbs, yAbs)\\\
        local dx = xAbs-theGroup.x\\\
        local dy = yAbs-theGroup.y\\\
        dcsCommon.offsetGroupData(theGroup, dx, dy)\\\
    end\\\
    \\\
    -- static objectr shapes and types are defined here\\\
    -- https://github.com/mrSkortch/DCS-miscScripts/tree/master/ObjectDB/Statics\\\
    \\\
    function dcsCommon.createStaticObjectData(name, objType, heading, dead, cargo, mass)\\\
        local staticObj = {}\\\
        if not heading then heading = 0 end \\\
        if not dead then dead = false end \\\
        if not cargo then cargo = false end \\\
        objType = dcsCommon.trim(objType) \\\
        \\\
        staticObj.heading = heading\\\
        -- staticObj.groupId = 0\\\
        -- staticObj.shape_name = shape -- e.g. H-Windsock_RW\\\
        staticObj.type = objType  -- e.g. Windsock\\\
        -- [\\\"unitId\\\"] = 3,\\\
        staticObj.rate = 1 -- score when killed\\\
        staticObj.name = name\\\
        -- staticObj.category = \\\"Fortifications\\\",\\\
        staticObj.y = 0\\\
        staticObj.x = 0\\\
        staticObj.dead = dead\\\
        staticObj.canCargo = cargo -- to cargo\\\
        if cargo then \\\
            if not mass then mass = 1234 end \\\
            staticObj.mass = mass -- to cargo\\\
        end\\\
        return staticObj\\\
    end\\\
    \\\
    function dcsCommon.createStaticObjectDataAt(loc, name, objType, heading, dead)\\\
        local theData = dcsCommon.createStaticObjectData(name, objType, heading, dead)\\\
        theData.x = loc.x\\\
        theData.y = loc.z \\\
        return theData\\\
    end\\\
    \\\
    function dcsCommon.createStaticObjectForCoalitionAtLocation(theCoalition, loc, name, objType, heading, dead) \\\
        if not heading then heading = math.random(360) * 3.1415 / 180 end\\\
        local theData = dcsCommon.createStaticObjectDataAt(loc, name, objType, heading, dead)\\\
        local theStatic = coalition.addStaticObject(theCoalition, theData)\\\
        return theStatic\\\
    end\\\
    \\\
    function dcsCommon.createStaticObjectForCoalitionInRandomRing(theCoalition, objType, x, z, innerRadius, outerRadius, heading, alive) \\\
        if not outerRadius then outerRadius = innerRadius end\\\
        if not heading then heading = math.random(360) * 3.1415 / 180 end\\\
        local dead = not alive\\\
        local p = dcsCommon.randomPointInCircle(outerRadius, innerRadius, x, z)\\\
        local theData = dcsCommon.createStaticObjectData(dcsCommon.uuid(\\\"static\\\"), objType, heading, dead)\\\
        theData.x = p.x\\\
        theData.y = p.z \\\
        \\\
        local theStatic = coalition.addStaticObject(theCoalition, theData)\\\
        return theStatic\\\
    end\\\
    \\\
    \\\
    \\\
    function dcsCommon.linkStaticDataToUnit(theStatic, theUnit, dx, dy, heading)\\\
        if not theStatic then \\\
            trigger.action.OutText(\\\"+++dcsC: NIL theStatic on linkStatic!\\\", 30)\\\
            return \\\
        end\\\
        -- NOTE: we may get current heading and subtract/add \\\
        -- to original heading \\\
        local rotX, rotY = dcsCommon.rotatePointAroundOrigin(dx, dy, -heading)\\\
        \\\
        if not theUnit then return end\\\
        if not theUnit:isExist() then return end \\\
        theStatic.linkOffset = true \\\
        theStatic.linkUnit = theUnit:getID()\\\
        local unitPos = theUnit:getPoint()\\\
        local offsets = {}\\\
        offsets.x = rotX  \\\
        offsets.y = rotY \\\
        offsets.angle = 0\\\
        theStatic.offsets = offsets\\\
    end\\\
    \\\
    function dcsCommon.offsetStaticData(theStatic, dx, dy)\\\
        theStatic.x = theStatic.x + dx\\\
        theStatic.y = theStatic.y + dy\\\
        -- now check if thre is a route (for linked objects)\\\
        if theStatic.route then \\\
            -- access points[1] x and y and copy from main\\\
            theStatic.route.points[1].x = theStatic.x\\\
            theStatic.route.points[1].y = theStatic.y\\\
        end\\\
    end\\\
    \\\
    function dcsCommon.moveStaticDataTo(theStatic, x, y)\\\
        theStatic.x = x\\\
        theStatic.y = y\\\
        -- now check if thre is a route (for linked objects)\\\
        if theStatic.route then \\\
            -- access points[1] x and y and copy from main\\\
            theStatic.route.points[1].x = theStatic.x\\\
            theStatic.route.points[1].y = theStatic.y\\\
        end\\\
\\\
    end\\\
\\\
function dcsCommon.synchGroupData(inGroupData) -- update group data block by \\\
-- comparing it to spawned group and update units by x, y, heding and isExist \\\
-- modifies inGroupData!\\\
    if not inGroupData then return end \\\
    -- groupdata from game, NOT MX DATA!\\\
    -- we synch the units and their coords \\\
    local livingUnits = {}\\\
    for idx, unitData in pairs(inGroupData.units) do \\\
        local theUnit = Unit.getByName(unitData.name)\\\
        if theUnit and theUnit:isExist() and theUnit:getLife()>1 then \\\
            -- update x and y and heading\\\
            local pos = theUnit:getPoint()\\\
            unitData.unitId = theUnit:getID()\\\
            unitData.x = pos.x \\\
            unitData.y = pos.z -- !!!!\\\
            unitData.heading = dcsCommon.getUnitHeading(gUnit)\\\
            table.insert(livingUnits, unitData)\\\
        end\\\
    end\\\
    inGroupData.units = livingUnits \\\
end\\\
\\\
--\\\
--\\\
-- M I S C   M E T H O D S \\\
--\\\
--\\\
\\\
-- as arrayContainsString, except it includes wildcard matches if EITHER \\\
-- ends on \\\"*\\\"\\\
    function dcsCommon.wildArrayContainsString(theArray, theString, caseSensitive) \\\
        if not theArray then return false end\\\
        if not theString then return false end\\\
        if not caseSensitive then caseSensitive = false end \\\
        if type(theArray) ~= \\\"table\\\" then \\\
            trigger.action.outText(\\\"***arrayContainsString: theArray is not type table but <\\\" .. type(theArray) .. \\\">\\\", 30)\\\
        end\\\
        if not caseSensitive then theString = string.upper(theString) end \\\
        \\\
        --trigger.action.outText(\\\"wildACS: theString = <\\\" .. theString .. \\\">, theArray contains <\\\" .. #theArray .. \\\"> elements\\\", 30)\\\
        local wildIn = dcsCommon.stringEndsWith(theString, \\\"*\\\")\\\
        if wildIn then dcsCommon.removeEnding(theString, \\\"*\\\") end \\\
        for idx, theElement in pairs(theArray) do -- i = 1, #theArray do \\\
            --local theElement = theArray[i]\\\
            --trigger.action.outText(\\\"test e <\\\" .. theElement .. \\\"> against s <\\\" .. theString .. \\\">\\\", 30)\\\
            if not caseSensitive then theElement = string.upper(theElement) end \\\
            local wildEle = dcsCommon.stringEndsWith(theElement, \\\"*\\\")\\\
            if wildEle then theElement = dcsCommon.removeEnding(theElement, \\\"*\\\") end \\\
            --trigger.action.outText(\\\"matching s=<\\\" .. theString .. \\\"> with e=<\\\" .. theElement .. \\\">\\\", 30)\\\
            if wildEle and wildIn then \\\
                -- both end on wildcards, partial match for both\\\
                if dcsCommon.stringStartsWith(theElement, theString) then return true end \\\
                if dcsCommon.stringStartsWith(theString, theElement) then return true end \\\
                --trigger.action.outText(\\\"match e* with s* failed.\\\", 30)\\\
            elseif wildEle then \\\
                -- Element is a wildcard, partial match \\\
                if dcsCommon.stringStartsWith(theString, theElement) then return true end\\\
                --trigger.action.outText(\\\"startswith - match e* <\\\" .. theElement .. \\\"> with s <\\\" .. theString .. \\\"> failed.\\\", 30)\\\
            elseif wildIn then\\\
                -- theString is a wildcard. partial match \\\
                if dcsCommon.stringStartsWith(theElement, theString) then return true end\\\
                --trigger.action.outText(\\\"match e with s* failed.\\\", 30)\\\
            else\\\
                -- standard: no wildcards, full match\\\
                if theElement == theString then return true end \\\
                --trigger.action.outText(\\\"match e with s (straight) failed.\\\", 30)\\\
            end\\\
            \\\
        end\\\
        return false \\\
    end\\\
\\\
\\\
    function dcsCommon.arrayContainsString(theArray, theString) \\\
        if not theArray then return false end\\\
        if not theString then return false end\\\
        if type(theArray) ~= \\\"table\\\" then \\\
            trigger.action.outText(\\\"***arrayContainsString: theArray is not type table but <\\\" .. type(theArray) .. \\\">\\\", 30)\\\
        end\\\
        for i = 1, #theArray do \\\
            if theArray[i] == theString then return true end \\\
        end\\\
        return false \\\
    end\\\
    \\\
    function dcsCommon.splitString(inputstr, sep) \\\
        if sep == nil then\\\
            sep = \\\"%s\\\"\\\
        end\\\
        if inputstr == nil then \\\
            inputstr = \\\"\\\"\\\
        end\\\
        \\\
        local t={}\\\
        for str in string.gmatch(inputstr, \\\"([^\\\"..sep..\\\"]+)\\\") do\\\
            table.insert(t, str)\\\
        end\\\
        return t\\\
    \\\
    end\\\
    \\\
    function dcsCommon.trimFront(inputstr) \\\
        if not inputstr then return nil end \\\
        local s = inputstr\\\
        while string.len(s) > 1 and string.sub(s, 1, 1) == \\\" \\\" do \\\
            local snew = string.sub(s, 2) -- all except first\\\
            s = snew\\\
        end\\\
        return s\\\
    end\\\
    \\\
    function dcsCommon.trimBack(inputstr)\\\
        if not inputstr then return nil end \\\
        local s = inputstr\\\
        while string.len(s) > 1 and string.sub(s, -1) == \\\" \\\" do \\\
            local snew = string.sub(s, 1, -2) -- all except last\\\
            s = snew\\\
        end\\\
        return s\\\
    end\\\
    \\\
    function dcsCommon.trim(inputstr) \\\
        local t1 = dcsCommon.trimFront(inputstr)\\\
        local t2 = dcsCommon.trimBack(t1)\\\
        return t2\\\
    end\\\
    \\\
    function dcsCommon.trimArray(theArray)\\\
        local trimmedArray = {}\\\
        for idx, element in pairs(theArray) do \\\
            local tel = dcsCommon.trim(element)\\\
            table.insert(trimmedArray, tel)\\\
        end\\\
        return trimmedArray\\\
    end\\\
    \\\
    function dcsCommon.string2Array(inString, deli, uCase)\\\
        if not inString then return {} end \\\
        if not deli then return {} end \\\
        if not uCase then uCase = false end\\\
        if uCase then inString = string.upper(inString) end\\\
        inString = dcsCommon.trim(inString)\\\
        if dcsCommon.containsString(inString, deli) then \\\
            local a = dcsCommon.splitString(inString, deli)\\\
            a = dcsCommon.trimArray(a)\\\
            return a \\\
        else \\\
            return {inString}\\\
        end\\\
    end\\\
    \\\
    function dcsCommon.array2string(inArray, deli)\\\
        if not deli then deli = \\\",\\\" end\\\
        if type(inArray) ~= \\\"table\\\" then return \\\"<err in array2string: not an array>\\\" end\\\
        local s = \\\"\\\"\\\
        local count = 0\\\
        for idx, ele in pairs(inArray) do\\\
            if count > 0 then s = s .. deli .. \\\" \\\" end\\\
            s = s .. ele\\\
        end\\\
        return s\\\
    end\\\
    \\\
    function dcsCommon.stripLF(theString)\\\
        return theString:gsub(\\\"[\\\\r\\\\n]\\\", \\\"\\\")\\\
    end\\\
    \\\
    function dcsCommon.removeBlanks(theString)\\\
        return theString:gsub(\\\"%s\\\", \\\"\\\")\\\
    end\\\
    \\\
    function dcsCommon.stringIsPositiveNumber(theString)\\\
        -- only full integer positive numbers supported \\\
        if not theString then return false end \\\
--        if theString == \\\"\\\" then return false end \\\
        for i = 1, #theString do \\\
            local c = theString:sub(i,i)\\\
            if c < \\\"0\\\" or c > \\\"9\\\" then return false end \\\
        end\\\
        return true \\\
    end\\\
    \\\
    function dcsCommon.stringStartsWithDigit(theString)\\\
        if #theString < 1 then return false end \\\
        local c = string.sub(theString, 1, 1) \\\
        return c >= \\\"0\\\" and c <= \\\"9\\\" \\\
    end\\\
    \\\
    function dcsCommon.stringStartsWithLetter(theString)\\\
        if #theString < 1 then return false end \\\
        local c = string.sub(theString, 1, 1)\\\
        if c >= \\\"a\\\" and c <= \\\"z\\\" then return true end  \\\
        if c >= \\\"A\\\" and c <= \\\"Z\\\" then return true end \\\
        return false \\\
    end\\\
    \\\
    function dcsCommon.stringStartsWith(theString, thePrefix, caseInsensitive)\\\
        if not theString then return false end \\\
        if not thePrefix then return false end \\\
        if not caseInsensitive then caseInsensitive = false end \\\
        \\\
        if caseInsensitive then \\\
            theString = string.upper(theString)\\\
            thePrefix = string.upper(theString)\\\
        end\\\
        -- new code because old 'string.find' had some really \\\
        -- strange results with aircraft types. Prefix \\\"A-10\\\" did not \\\
        -- match string \\\"A-10A\\\" etc. \\\
        \\\
        -- superseded: string.find (s, pattern [, init [, plain]]) solves the problem \\\
        \\\
        --[[\\\
        local pl = string.len(thePrefix)\\\
        if pl > string.len(theString) then return false end\\\
        if pl < 1 then return false end\\\
         for i=1, pl do \\\
        local left =  string.sub(theString, i, i)\\\
        local right = string.sub(thePrefix, i, i)\\\
            if left ~= right then \\\
                return false\\\
            end\\\
        end\\\
    \\\
        return true \\\
--]]--        trigger.action.outText(\\\"---- OK???\\\", 30)\\\
        -- strange stuff happening with some strings, let's investigate \\\
        \\\
        local i, j = string.find(theString, thePrefix, 1, true)\\\
        return (i == 1)\\\
--[[--\\\
        if res then\\\
            trigger.action.outText(\\\"startswith: <\\\" .. theString .. \\\"> pre <\\\" .. thePrefix .. \\\"> --> YES\\\", 30)\\\
        else \\\
            trigger.action.outText(\\\"startswith: <\\\" .. theString .. \\\"> nojoy pre <\\\" .. thePrefix .. \\\">\\\", 30)\\\
        end\\\
        return res \\\
--]]--\\\
    end\\\
    \\\
    function dcsCommon.removePrefix(theString, thePrefix)\\\
        if not dcsCommon.stringStartsWith(theString, thePrefix) then \\\
            return theString\\\
        end;\\\
        return theString:sub(1 + #thePrefix)\\\
    end\\\
    \\\
    function dcsCommon.stringEndsWith(theString, theEnding)\\\
        return theEnding == \\\"\\\" or theString:sub(-#theEnding) == theEnding\\\
    end\\\
    \\\
    function dcsCommon.removeEnding(theString, theEnding) \\\
        if not dcsCommon.stringEndsWith(theString, theEnding) then \\\
            return theString\\\
        end\\\
        return theString:sub(1, #theString - #theEnding)\\\
    end\\\
    \\\
    function dcsCommon.containsString(inString, what, caseSensitive)\\\
        if (not caseSensitive) then \\\
            inString = string.upper(inString)\\\
            what = string.upper(what)\\\
        end\\\
        if inString == what then return true end -- when entire match \\\
        return string.find(inString, what, 1, true) -- 1, true means start at 1, plaintext\\\
    end\\\
    \\\
    function dcsCommon.bool2Text(theBool) \\\
        if not theBool then theBool = false end \\\
        if theBool then return \\\"true\\\" end \\\
        return \\\"false\\\"\\\
    end\\\
    \\\
    function dcsCommon.bool2YesNo(theBool)\\\
        if not theBool then \\\
            theBool = false\\\
            return \\\"NIL\\\"\\\
        end \\\
        if theBool then return \\\"yes\\\" end \\\
        return \\\"no\\\"\\\
    end\\\
    \\\
    function dcsCommon.bool2Num(theBool)\\\
        if not theBool then theBool = false end \\\
        if theBool then return 1 end \\\
        return 0\\\
    end\\\
\\\
    function dcsCommon.point2text(p) \\\
        if not p then return \\\"<!NIL!>\\\" end \\\
        local t = \\\"[x=\\\"\\\
        if p.x then t = t .. p.x .. \\\", \\\" else t = t .. \\\"<nil>, \\\" end \\\
        if p.y then t = t .. \\\"y=\\\" .. p.y .. \\\", \\\" else t = t .. \\\"y=<nil>, \\\" end \\\
        if p.z then t = t .. \\\"z=\\\" .. p.z .. \\\"]\\\" else t = t .. \\\"z=<nil>]\\\" end \\\
        return t \\\
    end\\\
\\\
    function dcsCommon.string2GroupCat(inString)\\\
\\\
        if not inString then return 2 end -- default ground \\\
        inString = inString:lower()\\\
        inString = dcsCommon.trim(inString)\\\
\\\
        local catNum = tonumber(inString)\\\
        if catNum then \\\
            if catNum < 0 then catNum = 0 end \\\
            if catNum > 4 then catNum = 4 end \\\
            return catNum \\\
        end\\\
    \\\
        catNum = 2 -- ground default \\\
        if dcsCommon.stringStartsWith(inString, \\\"grou\\\") then catNum = 2 end \\\
        if dcsCommon.stringStartsWith(inString, \\\"air\\\") then catNum = 0 end\\\
        if dcsCommon.stringStartsWith(inString, \\\"hel\\\") then catNum = 1 end\\\
        if dcsCommon.stringStartsWith(inString, \\\"shi\\\") then catNum = 3 end\\\
        if dcsCommon.stringStartsWith(inString, \\\"trai\\\") then catNum = 4 end\\\
\\\
        return catNum\\\
    end\\\
\\\
    function dcsCommon.string2ObjectCat(inString)\\\
\\\
        if not inString then return 3 end -- default static \\\
        inString = inString:lower()\\\
        inString = dcsCommon.trim(inString)\\\
\\\
        local catNum = tonumber(inString)\\\
        if catNum then \\\
            if catNum < 0 then catNum = 0 end \\\
            if catNum > 6 then catNum = 6 end \\\
            return catNum \\\
        end\\\
    \\\
        catNum = 3 -- static default \\\
        if dcsCommon.stringStartsWith(inString, \\\"uni\\\") then catNum = 1 end \\\
        if dcsCommon.stringStartsWith(inString, \\\"wea\\\") then catNum = 2 end\\\
        if dcsCommon.stringStartsWith(inString, \\\"bas\\\") then catNum = 4 end\\\
        if dcsCommon.stringStartsWith(inString, \\\"sce\\\") then catNum = 5 end\\\
        if dcsCommon.stringStartsWith(inString, \\\"car\\\") then catNum = 6 end\\\
\\\
        return catNum\\\
    end\\\
\\\
    function dcsCommon.menu2text(inMenu)\\\
        if not inMenu then return \\\"<nil>\\\" end\\\
        local s = \\\"\\\"\\\
        for n, v in pairs(inMenu) do \\\
            if type(v) == \\\"string\\\" then \\\
                if s == \\\"\\\" then s = \\\"[\\\" .. v .. \\\"]\\\"  else \\\
                    s = s .. \\\" | [\\\" .. type(v) .. \\\"]\\\" end\\\
            else \\\
                if s == \\\"\\\" then s = \\\"[<\\\" .. type(v) .. \\\">]\\\"  else\\\
                    s = s .. \\\" | [<\\\" .. type(v) .. \\\">]\\\" end\\\
            end\\\
        end\\\
        return s\\\
    end\\\
\\\
    -- recursively show the contents of a variable\\\
    function dcsCommon.dumpVar(key, value, prefix, inrecursion)\\\
        if not inrecursion then \\\
            -- output a marker to find in the log / screen\\\
            env.info(\\\"*** dcsCommon vardump START\\\")\\\
        end\\\
        if not value then value = \\\"nil\\\" end\\\
        if not prefix then prefix = \\\"\\\" end\\\
        prefix = \\\" \\\" .. prefix\\\
        if type(value) == \\\"table\\\" then \\\
            env.info(prefix .. key .. \\\": [ \\\")\\\
            -- iterate through all kvp\\\
            for k,v in pairs (value) do\\\
                dcsCommon.dumpVar(k, v, prefix, true)\\\
            end\\\
            env.info(prefix .. \\\" ] - end \\\" .. key)\\\
            \\\
        elseif type(value) == \\\"boolean\\\" then \\\
            local b = \\\"false\\\"\\\
            if value then b = \\\"true\\\" end\\\
            env.info(prefix .. key .. \\\": \\\" .. b)\\\
            \\\
        else -- simple var, show contents, ends recursion\\\
            env.info(prefix .. key .. \\\": \\\" .. value)\\\
        end\\\
        \\\
        if not inrecursion then \\\
            -- output a marker to find in the log / screen\\\
            trigger.action.outText(\\\"=== dcsCommon vardump END\\\", 30)\\\
            env.info(\\\"=== dcsCommon vardump END\\\")\\\
        end\\\
    end\\\
    \\\
    function dcsCommon.dumpVar2Str(key, value, prefix, inrecursion)\\\
        if not inrecursion then \\\
            -- output a marker to find in the log / screen\\\
            trigger.action.outText(\\\"*** dcsCommon vardump START\\\",30)\\\
        end\\\
        if not value then value = \\\"nil\\\" end\\\
        if not prefix then prefix = \\\"\\\" end\\\
        prefix = \\\" \\\" .. prefix\\\
        if getmetatable(value) then \\\
            if type(value) == \\\"string\\\" then \\\
            else \\\
                trigger.action.outText(prefix .. key (\\\" .. type(value) .. \\\") .. \\\" HAS META\\\", 30)\\\
            end\\\
        end\\\
        if type(value) == \\\"table\\\" then \\\
            trigger.action.outText(prefix .. key .. \\\": [ \\\", 30)\\\
            -- iterate through all kvp\\\
            for k,v in pairs (value) do\\\
                dcsCommon.dumpVar2Str(k, v, prefix, true)\\\
            end\\\
            trigger.action.outText(prefix .. \\\" ] - end \\\" .. key, 30)\\\
            \\\
        elseif type(value) == \\\"boolean\\\" then \\\
            local b = \\\"false\\\"\\\
            if value then b = \\\"true\\\" end\\\
            trigger.action.outText(prefix .. key .. \\\": \\\" .. b, 30)\\\
            \\\
        else -- simple var, show contents, ends recursion\\\
            trigger.action.outText(prefix .. key .. \\\": \\\" .. value, 30)\\\
        end\\\
        \\\
        if not inrecursion then \\\
            -- output a marker to find in the log / screen\\\
            trigger.action.outText(\\\"=== dcsCommon vardump END\\\", 30)\\\
            --env.info(\\\"=== dcsCommon vardump END\\\")\\\
        end\\\
    end\\\
    \\\
\\\
    \\\
    function dcsCommon.numberUUID()\\\
        dcsCommon.simpleUUID = dcsCommon.simpleUUID + 1\\\
        return dcsCommon.simpleUUID\\\
    end\\\
\\\
    function dcsCommon.uuid(prefix)\\\
        --dcsCommon.uuIdent = dcsCommon.uuIdent + 1\\\
        if not prefix then prefix = dcsCommon.uuidStr end\\\
        return prefix .. \\\"-\\\" .. dcsCommon.numberUUID() -- dcsCommon.uuIdent\\\
    end\\\
    \\\
    function dcsCommon.event2text(id) \\\
        if not id then return \\\"error\\\" end\\\
        if id == 0 then return \\\"invalid\\\" end\\\
        -- translate the event id to text\\\
        local events = {\\\"shot\\\", \\\"hit\\\", \\\"takeoff\\\", \\\"land\\\",\\\
                        \\\"crash\\\", \\\"eject\\\", \\\"refuel\\\", \\\"dead\\\",\\\
                        \\\"pilot dead\\\", \\\"base captured\\\", \\\"mission start\\\", \\\"mission end\\\", -- 12\\\
                        \\\"took control\\\", \\\"refuel stop\\\", \\\"birth\\\", \\\"human failure\\\", \\\
                        \\\"det. failure\\\", \\\"engine start\\\", \\\"engine stop\\\", \\\"player enter unit\\\",\\\
                        \\\"player leave unit\\\", \\\"player comment\\\", \\\"start shoot\\\", \\\"end shoot\\\",\\\
                        \\\"mark add\\\", \\\"mark changed\\\", \\\"makr removed\\\", \\\"kill\\\", \\\
                        \\\"score\\\", \\\"unit lost\\\", \\\"land after eject\\\", \\\"Paratrooper land\\\", \\\
                        \\\"chair discard after eject\\\", \\\"weapon add\\\", \\\"trigger zone\\\", \\\"landing quality mark\\\",\\\
                        \\\"BDA\\\", \\\"max\\\"}\\\
        if id > #events then return \\\"Unknown (ID=\\\" .. id .. \\\")\\\" end\\\
        return events[id]\\\
    end\\\
\\\
    function dcsCommon.smokeColor2Text(smokeColor)\\\
        if (smokeColor == 0) then return \\\"Green\\\" end\\\
        if (smokeColor == 1) then return \\\"Red\\\" end\\\
        if (smokeColor == 2) then return \\\"White\\\" end\\\
        if (smokeColor == 3) then return \\\"Orange\\\" end\\\
        if (smokeColor == 4) then return \\\"Blue\\\" end\\\
        \\\
        return (\\\"unknown: \\\" .. smokeColor)\\\
    end\\\
    \\\
    function dcsCommon.flareColor2Text(flareColor)\\\
        if (flareColor == 0) then return \\\"Green\\\" end\\\
        if (flareColor == 1) then return \\\"Red\\\" end\\\
        if (flareColor == 2) then return \\\"White\\\" end\\\
        if (flareColor == 3) then return \\\"Yellow\\\" end\\\
        if (flareColor < 0) then return \\\"Random\\\" end \\\
        return (\\\"unknown: \\\" .. flareColor)\\\
    end\\\
    \\\
    function dcsCommon.smokeColor2Num(smokeColor)\\\
        if not smokeColor then smokeColor = \\\"green\\\" end \\\
        if type(smokeColor) ~= \\\"string\\\" then return 0 end \\\
        smokeColor = smokeColor:lower()\\\
        if (smokeColor == \\\"green\\\") then return 0 end \\\
        if (smokeColor == \\\"red\\\") then return 1 end \\\
        if (smokeColor == \\\"white\\\") then return 2 end \\\
        if (smokeColor == \\\"orange\\\") then return 3 end \\\
        if (smokeColor == \\\"blue\\\") then return 4 end \\\
        return 0\\\
    end\\\
\\\
    function dcsCommon.flareColor2Num(flareColor)\\\
        if not flareColor then flareColor = \\\"green\\\" end \\\
        if type(flareColor) ~= \\\"string\\\" then return 0 end \\\
        flareColor = flareColor:lower()\\\
        if (flareColor == \\\"green\\\") then return 0 end \\\
        if (flareColor == \\\"red\\\") then return 1 end \\\
        if (flareColor == \\\"white\\\") then return 2 end \\\
        if (flareColor == \\\"yellow\\\") then return 3 end \\\
        if (flareColor == \\\"random\\\") then return -1 end \\\
        if (flareColor == \\\"rnd\\\") then return -1 end \\\
        return 0\\\
    end\\\
\\\
    \\\
    function dcsCommon.markPointWithSmoke(p, smokeColor)\\\
        if not smokeColor then smokeColor = 0 end \\\
        local x = p.x \\\
        local z = p.z -- do NOT change the point directly\\\
        -- height-correct\\\
        local y = land.getHeight({x = x, y = z})\\\
        local newPoint= {x = x, y = y + 2, z = z}\\\
        trigger.action.smoke(newPoint, smokeColor)\\\
    end\\\
\\\
-- based on buzzer1977's idea, channel is number, eg in 74X, channel is 74, mode is \\\"X\\\"\\\
    function tacan2freq(channel, mode)    \\\
        if not mode then mode = \\\"X\\\" end \\\
        if not channel then channel = 1 end \\\
        if type(mode) ~= \\\"string\\\" then mode = \\\"X\\\" end \\\
        mode = mode:upper()\\\
        local offset = 1000000 * channel\\\
        if channel < 64 then \\\
            if mode == \\\"Y\\\" then\\\
                return 1087000000 + offset\\\
            end\\\
            return 961000000 + offset -- mode x\\\
        end\\\
    \\\
        if mode == \\\"Y\\\" then\\\
            return 961000000 + offset\\\
        end\\\
        return 1087000000 + offset -- mode x\\\
    end\\\
    \\\
    function dcsCommon.processHMS(msg, delta)\\\
        local rS = math.floor(delta)\\\
        local remainS = tostring(rS)\\\
        local rM = math.floor(delta/60)\\\
        local remainM = tostring(rM)\\\
        local rH = math.floor(delta/3600)\\\
        local remainH = tostring(rH)\\\
        local hmsH = remainH \\\
        if rH < 10 then hmsH = \\\"0\\\" .. hmsH end \\\
        \\\
        local hmsCount = delta - (rH * 3600) -- mins left \\\
        local mins = math.floor (hmsCount / 60)\\\
        local hmsM = tostring(mins)\\\
        if mins < 10 then hmsM = \\\"0\\\" .. hmsM end \\\
        \\\
        hmsCount = hmsCount - (mins * 60) \\\
        local secs = math.floor(hmsCount)\\\
        local hmsS = tostring(secs)\\\
        if secs < 10 then hmsS = \\\"0\\\" .. hmsS end \\\
        \\\
        msg = string.gsub(msg, \\\"<s>\\\", remainS)\\\
        msg = string.gsub(msg, \\\"<m>\\\", remainM)\\\
        msg = string.gsub(msg, \\\"<h>\\\", remainH)\\\
        \\\
        msg = string.gsub(msg, \\\"<:s>\\\", hmsS)\\\
        msg = string.gsub(msg, \\\"<:m>\\\", hmsM)\\\
        msg = string.gsub(msg, \\\"<:h>\\\", hmsH)\\\
        \\\
        return msg \\\
    end\\\
    \\\
    function dcsCommon.nowString()\\\
        local absSecs = timer.getAbsTime()-- + env.mission.start_time\\\
        while absSecs > 86400 do \\\
            absSecs = absSecs - 86400 -- subtract out all days \\\
        end\\\
        return dcsCommon.processHMS(\\\"<:h>:<:m>:<:s>\\\", absSecs)\\\
    end\\\
    \\\
    function dcsCommon.str2num(inVal, default) \\\
        if not default then default = 0 end\\\
        if not inVal then return default end\\\
        if type(inVal) == \\\"number\\\" then return inVal end                 \\\
        local num = nil\\\
        if type(inVal) == \\\"string\\\" then num = tonumber(inVal) end\\\
        if not num then return default end\\\
        return num\\\
    end\\\
    \\\
    function dcsCommon.stringRemainsStartingWith(theString, startingWith)\\\
        -- find the first position where startingWith starts \\\
        local pos = theString:find(startingWith)\\\
        if not pos then return theString end \\\
        -- now return the entire remainder of the string from pos \\\
        local nums = theString:len() - pos + 1\\\
        return theString:sub(-nums)\\\
    end\\\
\\\
--\\\
--\\\
-- V E C T O R   M A T H \\\
--\\\
--\\\
\\\
function dcsCommon.vAdd(a, b) \\\
    local r = {}\\\
    if not a then a = {x = 0, y = 0, z = 0} end\\\
    if not b then b = {x = 0, y = 0, z = 0} end\\\
    r.x = a.x + b.x \\\
    r.y = a.y + b.y \\\
    r.z = a.z + b.z \\\
    return r \\\
end\\\
\\\
function dcsCommon.vSub(a, b) \\\
    local r = {}\\\
    if not a then a = {x = 0, y = 0, z = 0} end\\\
    if not b then b = {x = 0, y = 0, z = 0} end\\\
    r.x = a.x - b.x \\\
    r.y = a.y - b.y \\\
    r.z = a.z - b.z \\\
    return r \\\
end\\\
\\\
function dcsCommon.vMultScalar(a, f) \\\
    local r = {}\\\
    if not a then a = {x = 0, y = 0, z = 0} end\\\
    if not f then f = 0 end\\\
    r.x = a.x * f \\\
    r.y = a.y * f \\\
    r.z = a.z * f \\\
    return r \\\
end\\\
\\\
function dcsCommon.vLerp (a, b, t)\\\
    if not a then a = {x = 0, y = 0, z = 0} end\\\
    if not b then b = {x = 0, y = 0, z = 0} end\\\
    \\\
    local d = dcsCommon.vSub(b, a)\\\
    local dt = dcsCommon.vMultScalar(d, t)\\\
    local r = dcsCommon.vAdd(a, dt)\\\
    return r\\\
end\\\
\\\
function dcsCommon.mag(x, y, z) \\\
    if not x then x = 0 end\\\
    if not y then y = 0 end \\\
    if not z then z = 0 end \\\
    \\\
    return (x * x + y * y + z * z)^0.5\\\
end\\\
\\\
function dcsCommon.vMag(a) \\\
    if not a then return 0 end \\\
    if not a.x then a.x = 0 end \\\
    if not a.y then a.y = 0 end \\\
    if not a.z then a.z = 0 end\\\
    return dcsCommon.mag(a.x, a.y, a.z) \\\
end\\\
\\\
function dcsCommon.magSquare(x, y, z) \\\
    if not x then x = 0 end\\\
    if not y then y = 0 end \\\
    if not z then z = 0 end \\\
    \\\
    return (x * x + y * y + z * z)\\\
end\\\
\\\
function dcsCommon.vNorm(a) \\\
    if not a then return {x = 0, y = 0, z = 0} end \\\
    m = dcsCommon.vMag(a)\\\
    if m <= 0 then return {x = 0, y = 0, z = 0} end \\\
    local r = {}\\\
    r.x = a.x / m \\\
    r.y = a.y / m \\\
    r.z = a.z / m\\\
    return r \\\
end\\\
\\\
function dcsCommon.dot (a, b) \\\
    if not a then a = {} end \\\
    if not a.x then a.x = 0 end \\\
    if not a.y then a.y = 0 end \\\
    if not a.z then a.z = 0 end\\\
    if not b then b = {} end \\\
    if not b.x then b.x = 0 end \\\
    if not b.y then b.y = 0 end \\\
    if not b.z then b.z = 0 end \\\
    \\\
    return a.x * b.x + a.y * b.y + a.z * b.z \\\
end\\\
--\\\
-- UNIT MISC\\\
-- \\\
function dcsCommon.isSceneryObject(theUnit)\\\
    if not theUnit then return false end\\\
    return theUnit.getCoalition == nil -- scenery objects do not return a coalition \\\
end\\\
\\\
function dcsCommon.isTroopCarrierType(theType, carriers)\\\
    if not theType then return false end \\\
    if not carriers then carriers = dcsCommon.troopCarriers \\\
    end \\\
    -- remember that arrayContainsString is case INsensitive by default \\\
    if dcsCommon.wildArrayContainsString(carriers, theType) then \\\
        -- may add additional tests before returning true\\\
        return true\\\
    end\\\
    \\\
    -- see if user wanted 'any' or 'all' supported\\\
    if dcsCommon.arrayContainsString(carriers, \\\"any\\\") then \\\
        return true \\\
    end \\\
    \\\
    if dcsCommon.arrayContainsString(carriers, \\\"all\\\") then \\\
        return true \\\
    end \\\
    \\\
    return false\\\
end\\\
\\\
function dcsCommon.isTroopCarrier(theUnit, carriers)\\\
    -- return true if conf can carry troups\\\
    if not theUnit then return false end \\\
    local uType = theUnit:getTypeName()\\\
    return dcsCommon.isTroopCarrierType(uType, carriers) \\\
end\\\
\\\
function dcsCommon.isPlayerUnit(theUnit)\\\
    -- new patch. simply check if getPlayerName returns something\\\
    if not theUnit then return false end \\\
    if not Unit.isExist(theUnit) then return end \\\
    if not theUnit.getPlayerName then return false end -- map/static object \\\
    local pName = theUnit:getPlayerName()\\\
    if pName then return true end \\\
    return false \\\
end\\\
\\\
function dcsCommon.getAllExistingPlayerUnitsRaw()\\\
    local apu = {}\\\
    for idx, theSide in pairs(dcsCommon.coalitionSides) do\\\
        local thePlayers = coalition.getPlayers(theSide) \\\
        for idy, theUnit in pairs (thePlayers) do \\\
            if theUnit and theUnit:isExist() then \\\
                table.insert(apu, theUnit)\\\
            end\\\
        end\\\
    end\\\
    return apu \\\
end\\\
\\\
function dcsCommon.getUnitAlt(theUnit)\\\
    if not theUnit then return 0 end\\\
    if not Unit.isExist(theUnit) then return 0 end -- safer \\\
    local p = theUnit:getPoint()\\\
    return p.y \\\
end\\\
\\\
function dcsCommon.getUnitAGL(theUnit)\\\
    if not theUnit then return 0 end\\\
    if not Unit.isExist(theUnit) then return 0 end -- safe fix\\\
    local p = theUnit:getPoint()\\\
    local alt = p.y \\\
    local loc = {x = p.x, y = p.z}\\\
    local landElev = land.getHeight(loc)\\\
    return alt - landElev\\\
end \\\
\\\
function dcsCommon.getUnitSpeed(theUnit)\\\
    if not theUnit then return 0 end\\\
    if not Unit.isExist(theUnit) then return 0 end \\\
    local v = theUnit:getVelocity()\\\
    return dcsCommon.mag(v.x, v.y, v.z)\\\
end\\\
\\\
-- closing velocity of u1 and u2, seen from u1\\\
function dcsCommon.getClosingVelocity(u1, u2)\\\
    if not u1 then return 0 end \\\
    if not u2 then return 0 end \\\
    if not u1:isExist() then return 0 end \\\
    if not u2:isExist() then return 0 end \\\
    local v1 = u1:getVelocity()\\\
    local v2 = u2:getVelocity()\\\
    local dV = dcsCommon.vSub(v1,v2)\\\
    local a = u1:getPoint()\\\
    local b = u2:getPoint() \\\
    local aMinusB = dcsCommon.vSub(a,b) -- vector from u2 to u1\\\
    local abMag = dcsCommon.vMag(aMinusB) -- distance u1 to u2 \\\
    if abMag < .0001 then return 0 end \\\
    -- project deltaV onto vector from u2 to u1 \\\
    local vClose = dcsCommon.dot(dV, aMinusB) / abMag \\\
    return vClose \\\
end\\\
\\\
function dcsCommon.getGroupAvgSpeed(theGroup)\\\
    if not theGroup then return 0 end \\\
    if not dcsCommon.isGroupAlive(theGroup) then return 0 end \\\
    local totalSpeed = 0\\\
    local cnt = 0 \\\
    local livingUnits = theGroup:getUnits()\\\
    for idx, theUnit in pairs(livingUnits) do \\\
        cnt = cnt + 1\\\
        totalSpeed = totalSpeed + dcsCommon.getUnitSpeed(theUnit)\\\
    end \\\
    if cnt == 0 then return 0 end \\\
    return totalSpeed / cnt \\\
end\\\
 \\\
function dcsCommon.getGroupMaxSpeed(theGroup)\\\
    if not theGroup then return 0 end \\\
    if not dcsCommon.isGroupAlive(theGroup) then return 0 end \\\
    local maxSpeed = 0\\\
    local livingUnits = theGroup:getUnits()\\\
    for idx, theUnit in pairs(livingUnits) do \\\
        currSpeed = dcsCommon.getUnitSpeed(theUnit)\\\
        if currSpeed > maxSpeed then maxSpeed = currSpeed end \\\
    end \\\
    return maxSpeed\\\
end \\\
\\\
function dcsCommon.getUnitHeading(theUnit)\\\
    if not theUnit then return 0 end \\\
    if not theUnit:isExist() then return 0 end \\\
    local pos = theUnit:getPosition() -- returns three vectors, p is location\\\
\\\
    local heading = math.atan2(pos.x.z, pos.x.x)\\\
    -- make sure positive only, add 360 degrees\\\
    if heading < 0 then\\\
        heading = heading + 2 * math.pi    -- put heading in range of 0 to 2*pi\\\
    end\\\
    return heading \\\
end\\\
\\\
function dcsCommon.getUnitHeadingDegrees(theUnit)\\\
    local heading = dcsCommon.getUnitHeading(theUnit)\\\
    return heading * 57.2958 -- 180 / math.pi \\\
end\\\
\\\
function dcsCommon.typeIsInfantry(theType)\\\
    local isInfantry =  \\\
                dcsCommon.containsString(theType, \\\"infantry\\\", false) or \\\
                dcsCommon.containsString(theType, \\\"paratrooper\\\", false) or\\\
                dcsCommon.containsString(theType, \\\"stinger\\\", false) or\\\
                dcsCommon.containsString(theType, \\\"manpad\\\", false) or\\\
                dcsCommon.containsString(theType, \\\"soldier\\\", false) or \\\
                dcsCommon.containsString(theType, \\\"SA-18 Igla\\\", false)\\\
    return isInfantry\\\
end\\\
\\\
function dcsCommon.unitIsInfantry(theUnit)\\\
    if not theUnit then return false end \\\
    if not theUnit:isExist() then return end\\\
    local theType = theUnit:getTypeName()\\\
--[[--\\\
    local isInfantry =  \\\
                dcsCommon.containsString(theType, \\\"infantry\\\", false) or \\\
                dcsCommon.containsString(theType, \\\"paratrooper\\\", false) or\\\
                dcsCommon.containsString(theType, \\\"stinger\\\", false) or\\\
                dcsCommon.containsString(theType, \\\"manpad\\\", false) or\\\
                dcsCommon.containsString(theType, \\\"soldier\\\", false) or \\\
                dcsCommon.containsString(theType, \\\"SA-18 Igla\\\", false)\\\
    return isInfantry\\\
--]]--\\\
    return dcsCommon.typeIsInfantry(theType)\\\
end\\\
\\\
function dcsCommon.coalition2county(inCoalition)\\\
    -- simply return UN troops for 0 neutral,\\\
    -- joint red for 1  red\\\
    -- joint blue for 2 blue \\\
    if inCoalition == 1 then return 81 end -- cjtf red\\\
    if inCoalition == 2 then return 80 end -- blue \\\
    if type(inCoalition) == \\\"string\\\" then \\\
            inCoalition = inCoalition:lower()\\\
            if inCoalition == \\\"red\\\" then return 81 end\\\
            if inCoalition == \\\"blue\\\" then return 80 end\\\
    end\\\
        \\\
    trigger.action.outText(\\\"+++dcsC: coalition2county in (\\\" .. inCoalition .. \\\") converts to UN (82)!\\\", 30)\\\
    return 82 -- UN \\\
    \\\
end\\\
\\\
function dcsCommon.latLon2Text(lat, lon)\\\
    -- inspired by mist, thanks Grimes!\\\
    -- returns two strings: lat and lon \\\
    \\\
    -- determine hemispheres by sign\\\
    local latHemi, lonHemi\\\
    if lat > 0 then latHemi = 'N' else latHemi = 'S' end\\\
    if lon > 0 then lonHemi = 'E' else lonHemi = 'W' end\\\
\\\
    -- remove sign since we have hemi\\\
    lat = math.abs(lat)\\\
    lon = math.abs(lon)\\\
\\\
    -- calc deg / mins \\\
    local latDeg = math.floor(lat)\\\
    local latMin = (lat - latDeg) * 60\\\
    local lonDeg = math.floor(lon)\\\
    local lonMin = (lon - lonDeg) * 60\\\
\\\
    -- calc seconds \\\
    local rawLatMin = latMin\\\
    latMin = math.floor(latMin)\\\
    local latSec = (rawLatMin - latMin) * 60\\\
    local rawLonMin = lonMin\\\
    lonMin = math.floor(lonMin)\\\
    local lonSec = (rawLonMin - lonMin) * 60\\\
\\\
    -- correct for rounding errors \\\
    if latSec >= 60 then\\\
        latSec = latSec - 60\\\
        latMin = latMin + 1\\\
    end\\\
    if lonSec >= 60 then\\\
        lonSec = lonSec - 60\\\
        lonMin = lonMin + 1\\\
    end\\\
\\\
    -- prepare string output \\\
    local secFrmtStr = '%06.3f'\\\
    local lat = string.format('%02d', latDeg) .. '°' .. string.format('%02d', latMin) .. \\\"'\\\" .. string.format(secFrmtStr, latSec) .. '\\\"' .. latHemi\\\
    local lon = string.format('%02d', lonDeg) .. '°' .. string.format('%02d', lonMin) .. \\\"'\\\" .. string.format(secFrmtStr, lonSec) .. '\\\"' .. lonHemi\\\
    return lat, lon  \\\
end\\\
\\\
-- get mission name. If mission file name without \\\".miz\\\"\\\
function dcsCommon.getMissionName()\\\
    local mn = net.dostring_in(\\\"gui\\\", \\\"return DCS.getMissionName()\\\")\\\
    return mn\\\
end\\\
\\\
function dcsCommon.flagArrayFromString(inString, verbose)\\\
    if not verbose then verbose = false end \\\
    \\\
    if verbose then \\\
        trigger.action.outText(\\\"+++flagArray: processing <\\\" .. inString .. \\\">\\\", 30)\\\
    end \\\
\\\
    if string.len(inString) < 1 then \\\
        trigger.action.outText(\\\"+++flagArray: empty flags\\\", 30)\\\
        return {} \\\
    end\\\
    \\\
    \\\
    local flags = {}\\\
    local rawElements = dcsCommon.splitString(inString, \\\",\\\")\\\
    -- go over all elements \\\
    for idx, anElement in pairs(rawElements) do \\\
        anElement = dcsCommon.trim(anElement)\\\
        if dcsCommon.stringStartsWithDigit(anElement) and  dcsCommon.containsString(anElement, \\\"-\\\") then \\\
            -- interpret this as a range\\\
            local theRange = dcsCommon.splitString(anElement, \\\"-\\\")\\\
            local lowerBound = theRange[1]\\\
            lowerBound = tonumber(lowerBound)\\\
            local upperBound = theRange[2]\\\
            upperBound = tonumber(upperBound)\\\
            if lowerBound and upperBound then\\\
                -- swap if wrong order\\\
                if lowerBound > upperBound then \\\
                    local temp = upperBound\\\
                    upperBound = lowerBound\\\
                    lowerBound = temp \\\
                end\\\
                -- now add add numbers to flags\\\
                for f=lowerBound, upperBound do \\\
                    table.insert(flags, f)\\\
\\\
                end\\\
            else\\\
                -- bounds illegal\\\
                trigger.action.outText(\\\"+++flagArray: ignored range <\\\" .. anElement .. \\\"> (range)\\\", 30)\\\
            end\\\
        else\\\
            -- single number\\\
            local f = dcsCommon.trim(anElement) -- DML flag upgrade: accept strings tonumber(anElement)\\\
            if f then \\\
                table.insert(flags, f)\\\
\\\
            else \\\
                trigger.action.outText(\\\"+++flagArray: ignored element <\\\" .. anElement .. \\\"> (single)\\\", 30)\\\
            end\\\
        end\\\
    end\\\
    if verbose then \\\
        trigger.action.outText(\\\"+++flagArray: <\\\" .. #flags .. \\\"> flags total\\\", 30)\\\
    end \\\
    return flags\\\
end\\\
\\\
function dcsCommon.rangeArrayFromString(inString, verbose)\\\
    if not verbose then verbose = false end \\\
    \\\
    if verbose then \\\
        trigger.action.outText(\\\"+++rangeArray: processing <\\\" .. inString .. \\\">\\\", 30)\\\
    end \\\
\\\
    if string.len(inString) < 1 then \\\
        trigger.action.outText(\\\"+++rangeArray: empty ranges\\\", 30)\\\
        return {} \\\
    end\\\
    \\\
    local ranges = {}\\\
    local rawElements = dcsCommon.splitString(inString, \\\",\\\")\\\
    -- go over all elements \\\
    for idx, anElement in pairs(rawElements) do \\\
        anElement = dcsCommon.trim(anElement)\\\
        local outRange = {}\\\
        if dcsCommon.stringStartsWithDigit(anElement) and  dcsCommon.containsString(anElement, \\\"-\\\") then \\\
            -- interpret this as a range\\\
            local theRange = dcsCommon.splitString(anElement, \\\"-\\\")\\\
            local lowerBound = theRange[1]\\\
            lowerBound = tonumber(lowerBound)\\\
            local upperBound = theRange[2]\\\
            upperBound = tonumber(upperBound)\\\
            if lowerBound and upperBound then\\\
                -- swap if wrong order\\\
                if lowerBound > upperBound then \\\
                    local temp = upperBound\\\
                    upperBound = lowerBound\\\
                    lowerBound = temp \\\
                end\\\
                -- now add to ranges\\\
                outRange[1] = lowerBound\\\
                outRange[2] = upperBound\\\
                table.insert(ranges, outRange)\\\
                if verbose then \\\
                    trigger.action.outText(\\\"+++rangeArray: new range <\\\" .. lowerBound .. \\\"> to <\\\" .. upperBound .. \\\">\\\", 30)\\\
                end\\\
            else\\\
                -- bounds illegal\\\
                trigger.action.outText(\\\"+++rangeArray: ignored range <\\\" .. anElement .. \\\"> (range)\\\", 30)\\\
            end\\\
        else\\\
            -- single number\\\
            local f = dcsCommon.trim(anElement) \\\
            f = tonumber(f)\\\
            if f then \\\
                outRange[1] = f\\\
                outRange[2] = f\\\
                table.insert(ranges, outRange)\\\
                if verbose then \\\
                    trigger.action.outText(\\\"+++rangeArray: new (single-val) range <\\\" .. f .. \\\"> to <\\\" .. f .. \\\">\\\", 30)\\\
                end\\\
            else \\\
                trigger.action.outText(\\\"+++rangeArray: ignored element <\\\" .. anElement .. \\\"> (single)\\\", 30)\\\
            end\\\
        end\\\
    end\\\
    if verbose then \\\
        trigger.action.outText(\\\"+++rangeArray: <\\\" .. #ranges .. \\\"> ranges total\\\", 30)\\\
    end \\\
    return ranges\\\
end\\\
\\\
function dcsCommon.incFlag(flagName)\\\
    local v = trigger.misc.getUserFlag(flagName)\\\
    trigger.action.setUserFlag(flagName, v + 1)\\\
end\\\
\\\
function dcsCommon.decFlag(flagName)\\\
    local v = trigger.misc.getUserFlag(flagName)\\\
    trigger.action.setUserFlag(flagName, v - 1)\\\
end\\\
\\\
function dcsCommon.objectHandler(theObject, theCollector)\\\
    table.insert(theCollector, theObject)\\\
    return true \\\
end\\\
\\\
function dcsCommon.getObjectsForCatAtPointWithRadius(aCat, thePoint, theRadius)\\\
    if not aCat then aCat = Object.Category.UNIT end \\\
    local p = {x=thePoint.x, y=thePoint.y, z=thePoint.z}\\\
    local collector = {}\\\
    \\\
    -- now build the search argument \\\
    local args = {\\\
            id = world.VolumeType.SPHERE,\\\
            params = {\\\
                point = p,\\\
                radius = theRadius\\\
            }\\\
        }\\\
    \\\
    -- now call search\\\
    world.searchObjects(aCat, args, dcsCommon.objectHandler, collector)\\\
    return collector\\\
end\\\
\\\
function dcsCommon.getSceneryObjectsInZone(theZone) -- DCS ZONE!!! \\\
    local aCat = 5 -- scenery\\\
    -- WARNING: WE ARE USING DCS ZONES, NOT CFX!!!\\\
    local p = {x=theZone.x, y=0, z=theZone.y}\\\
    local lp = {x = p.x, y = p.z}\\\
    p.y = land.getHeight(lp)\\\
    local collector = {}\\\
    \\\
    -- now build the search argument \\\
    local args = {\\\
            id = world.VolumeType.SPHERE,\\\
            params = {\\\
                point = p,\\\
                radius = theZone.radius\\\
            }\\\
        }\\\
    \\\
    -- now call search\\\
    world.searchObjects(aCat, args, dcsCommon.objectHandler, collector)\\\
    return collector\\\
end\\\
\\\
function dcsCommon.getSceneryObjectInZoneByName(theName, theZone) -- DCS ZONE!!!\\\
    local allObs = dcsCommon.getSceneryObjectsInZone(theZone)\\\
    for idx, anObject in pairs(allObs) do \\\
        if tostring(anObject:getName()) == theName then return anObject end \\\
    end\\\
    return nil \\\
end\\\
\\\
--\\\
-- bitwise operators\\\
--\\\
function dcsCommon.bitAND32(a, b)\\\
    if not a then a = 0 end \\\
    if not b then b = 0 end \\\
    local z = 0\\\
    local e = 1\\\
    for i = 0, 31 do \\\
        local a1 = a % 2 -- 0 or 1\\\
        local b1 = b % 2 -- 0 or 1\\\
        if a1 == 1 and b1 == 1 then \\\
            a = a - 1 -- remove bit \\\
            b = b - 1 \\\
            z = z + e\\\
        else\\\
            if a1 == 1 then a = a - 1 end -- remove bit \\\
            if b1 == 1 then b = b - 1 end \\\
        end\\\
        a = a / 2 -- shift right\\\
        b = b / 2        \\\
        e = e * 2 -- raise e by 1 \\\
    end\\\
    return z\\\
end\\\
\\\
function dcsCommon.num2bin(a)\\\
    if not a then a = 0 end \\\
    local z = \\\"\\\"\\\
    for i = 0, 31 do \\\
        local a1 = a % 2 -- 0 or 1\\\
        if a1 == 1 then \\\
            a = a - 1 -- remove bit \\\
            z = \\\"1\\\"..z\\\
        else\\\
            z = \\\"0\\\"..z\\\
        end\\\
        a = a / 2 -- shift right\\\
    end\\\
    return z\\\
end\\\
\\\
function dcsCommon.LSR(a, num)\\\
    if not a then a = 0 end \\\
    if not num then num = 16 end \\\
    for i = 1, num do \\\
        local a1 = a % 2 -- 0 or 1\\\
        if a1 == 1 then \\\
            a = a - 1 -- remove bit \\\
        end\\\
        a = a / 2 -- shift right\\\
    end\\\
    return a\\\
end\\\
\\\
--\\\
-- string wildcards \\\
--\\\
function dcsCommon.processStringWildcards(inMsg)\\\
    -- Replace STATIC bits of message like CR and zone name \\\
    if not inMsg then return \\\"<nil inMsg>\\\" end\\\
    local formerType = type(inMsg)\\\
    if formerType ~= \\\"string\\\" then inMsg = tostring(inMsg) end  \\\
    if not inMsg then inMsg = \\\"<inMsg is incompatible type \\\" .. formerType .. \\\">\\\" end \\\
    local outMsg = \\\"\\\"\\\
    -- replace line feeds \\\
    outMsg = inMsg:gsub(\\\"<n>\\\", \\\"\\\\n\\\")\\\
\\\
    return outMsg \\\
end\\\
\\\
--\\\
-- phonetic alphabet \\\
--\\\
dcsCommon.alphabet = {\\\
    a = \\\"alpha\\\",\\\
    b = \\\"bravo\\\",\\\
    c = \\\"charlie\\\",\\\
    d = \\\"delta\\\",\\\
    e = \\\"echo\\\",\\\
    f = \\\"foxtrot\\\",\\\
    g = \\\"golf\\\",\\\
    h = \\\"hotel\\\",\\\
    i = \\\"india\\\",\\\
    j = \\\"juliet\\\",\\\
    k = \\\"kilo\\\",\\\
    l = \\\"lima\\\",\\\
    m = \\\"mike\\\",\\\
    n = \\\"november\\\",\\\
    o = \\\"oscar\\\",\\\
    p = \\\"papa\\\",\\\
    q = \\\"quebec\\\",\\\
    r = \\\"romeo\\\",\\\
    s = \\\"sierra\\\",\\\
    t = \\\"tango\\\",\\\
    u = \\\"uniform\\\",\\\
    v = \\\"victor\\\",\\\
    w = \\\"whiskey\\\",\\\
    x = \\\"x-ray\\\",\\\
    y = \\\"yankee\\\",\\\
    z = \\\"zulu\\\",\\\
[\\\"0\\\"] = \\\"zero\\\",\\\
[\\\"1\\\"] = \\\"wun\\\",\\\
[\\\"2\\\"] = \\\"too\\\",\\\
[\\\"3\\\"] = \\\"tree\\\",\\\
[\\\"4\\\"] = \\\"fower\\\",\\\
[\\\"5\\\"] = \\\"fife\\\" ,\\\
[\\\"6\\\"] = \\\"six\\\",\\\
[\\\"7\\\"] = \\\"seven\\\",\\\
[\\\"8\\\"] = \\\"att\\\",\\\
[\\\"9\\\"] = \\\"niner\\\",\\\
[\\\" \\\"] = \\\"break\\\",\\\
}\\\
\\\
function dcsCommon.letter(inChar)\\\
    local theChar = \\\"\\\"\\\
    if type(inChar == \\\"string\\\") then \\\
        if #inChar < 1 then return \\\"#ERROR0#\\\" end\\\
        inChar = string.lower(inChar)\\\
        theChar = string.sub(inChar, 1, 1)\\\
    elseif type(inChar == \\\"number\\\") then \\\
        if inChar > 255 then return \\\"#ERROR>#\\\" end \\\
        if inChar < 0 then return \\\"#ERROR<#\\\" end \\\
        theChar = char(inChar)\\\
    else \\\
        return \\\"#ERRORT#\\\"\\\
    end\\\
--    trigger.action.outText(\\\"doing <\\\" .. theChar .. \\\">\\\", 30)\\\
    local a = dcsCommon.alphabet[theChar]\\\
    if a == nil then a = \\\"#ERROR?#\\\" end \\\
    return a \\\
end\\\
\\\
function dcsCommon.spellString(inString)\\\
    local res = \\\"\\\"\\\
    local first = true \\\
    for i = 1, #inString do\\\
        local c = inString:sub(i,i)\\\
        if first then \\\
            res = dcsCommon.letter(c)\\\
            first = false \\\
        else \\\
            res = res .. \\\" \\\" .. dcsCommon.letter(c)\\\
        end\\\
    end\\\
    return res \\\
end\\\
\\\
--\\\
-- iterators\\\
--\\\
-- iteratePlayers - call callback for all player units\\\
-- callback is of signature callback(playerUnit)\\\
--\\\
\\\
function dcsCommon.iteratePlayers(callBack)\\\
    local factions = {0, 1, 2}\\\
    for idx, theFaction in pairs(factions) do \\\
        local players = coalition.getPlayers(theFaction)\\\
        for idy, theUnit in pairs(players) do \\\
            callBack(theUnit)\\\
        end\\\
    end\\\
end\\\
\\\
--\\\
-- SEMAPHORES\\\
--\\\
dcsCommon.semaphores = {}\\\
\\\
-- replacement for trigger.misc.getUserFlag\\\
function dcsCommon.getUserFlag(flagName)\\\
    if dcsCommon.semaphores[flagName] then \\\
        return dcsCommon.semaphores[flagName]\\\
    end\\\
    \\\
    return trigger.misc.getUserFlag(flagName)\\\
end\\\
\\\
-- replacement for trigger.action.setUserFlag \\\
function dcsCommon.setUserFlag(flagName, theValue)\\\
    -- not yet connected: semaphores\\\
    \\\
    -- forget semaphore content if new value is old-school \\\
    if type(theValue) == \\\"number\\\" then \\\
        dcsCommon.semaphores[theValue] = nil --return to old-school \\\
    end\\\
    trigger.action.setUserFlag(flagName, theValue)\\\
end\\\
\\\
--\\\
--\\\
-- INIT\\\
--\\\
--\\\
    -- init any variables, tables etc that the lib requires internally\\\
    function dcsCommon.init()\\\
        cbID = 0\\\
        -- create ID tables\\\
        dcsCommon.collectMissionIDs()\\\
        \\\
        --dcsCommon.uuIdent = 0\\\
        if (dcsCommon.verbose) or true then\\\
          trigger.action.outText(\\\"dcsCommon v\\\" .. dcsCommon.version .. \\\" loaded\\\", 10)\\\
        end\\\
    end\\\
\\\
    \\\
-- do init. \\\
dcsCommon.init()\\\
\\\
\");a_do_script(\"cfxZones = {}\\\
cfxZones.version = \\\"3.0.9\\\"\\\
\\\
-- cf/x zone management module\\\
-- reads dcs zones and makes them accessible and mutable \\\
-- by scripting.\\\
--\\\
-- Copyright (c) 2021, 2022 by Christian Franz and cf/x AG\\\
--\\\
\\\
--[[-- VERSION HISTORY\\\
 - 2.2.4 - getCoalitionFromZoneProperty\\\
         - getStringFromZoneProperty\\\
 - 2.2.5 - createGroundUnitsInZoneForCoalition corrected coalition --> country \\\
 - 2.2.6 - getVectorFromZoneProperty(theZone, theProperty, defaultVal)\\\
 - 2.2.7 - allow 'yes' as 'true' for boolean attribute \\\
 - 2.2.8 - getBoolFromZoneProperty supports default \\\
         - cfxZones.hasProperty\\\
 - 2.3.0 - property names are case insensitive \\\
 - 2.3.1 - getCoalitionFromZoneProperty allows 0, 1, 2 also\\\
 - 2.4.0 - all zones look for owner attribute, and set it to 0 (neutral) if not present \\\
 - 2.4.1 - getBoolFromZoneProperty upgraded by expected bool \\\
         - markZoneWithSmoke raised by 3 meters\\\
 - 2.4.2 - getClosestZone also returns delta \\\
 - 2.4.3 - getCoalitionFromZoneProperty() accepts 'all' as neutral \\\
           createUniqueZoneName()\\\
           getStringFromZoneProperty returns default if property value = \\\"\\\"\\\
           corrected bug in addZoneToManagedZones\\\
 - 2.4.4 - getPoint(aZone) returns uip-to-date pos for linked and normal zones\\\
         - linkUnit can use \\\"useOffset\\\" property to keep relative position\\\
 - 2.4.5 - updated various methods to support getPoint when referencing \\\
           zone.point  \\\
 - 2.4.6 - corrected spelling in markZoneWithSmoke\\\
 - 2.4.7 - copy reference to dcs zone into cfx zone \\\
 - 2.4.8 - getAllZoneProperties\\\
 - 2.4.9 - createSimpleZone no longer requires location \\\
         - parse dcs adds empty .properties = {} if none tehre \\\
         - createCircleZone adds empty properties \\\
         - createPolyZone adds empty properties \\\
 - 2.4.10 - pickRandomZoneFrom now defaults to all cfxZones.zones\\\
          - getBoolFromZoneProperty also recognizes 0, 1\\\
          - removed autostart\\\
 - 2.4.11 - removed typo in get closest zone \\\
 - 2.4.12 - getStringFromZoneProperty\\\
 - 2.5.0  - harden getZoneProperty and all getPropertyXXXX\\\
 - 2.5.1  - markZoneWithSmoke supports alt attribute \\\
 - 2.5.2  - getPoint also writes through to zone itself for optimization\\\
          - new method getPositiveRangeFromZoneProperty(theZone, theProperty, default)\\\
 - 2.5.3  - new getAllGroupsInZone()\\\
 - 2.5.4  - cleaned up getZoneProperty break on no properties \\\
          - extractPropertyFromDCS trims key and property \\\
 - 2.5.5  - pollFlag() centralized for banging \\\
          - allStaticsInZone\\\
 - 2.5.6  - flag accessor setFlagValue(), getFlagValue()  \\\
          - pollFlag supports theZone as final parameter\\\
          - randomDelayFromPositiveRange\\\
          - isMEFlag\\\
 - 2.5.7  - pollFlag supports dml flags\\\
 - 2.5.8  - flagArrayFromString\\\
          - getFlagNumber invokes tonumber() before returning result \\\
 - 2.5.9  - removed pass-back flag in getPoint() \\\
 - 2.6.0  - testZoneFlag() method based flag testing\\\
 - 2.6.1  - Watchflag parsing of zone condition for number-named flags\\\
          - case insensitive\\\
          - verbose for zone-local accepted (but not acted upon)\\\
          - hasProperty now offers active information when looking for '*?' and '*!'\\\
 - 2.7.0  - doPollFlag - fully support multiple flags per bang!\\\
 - 2.7.1  - setFlagValueMult()\\\
 - 2.7.2  - '261 repair'\\\
 - 2.7.3  - testZoneFlag returns mathodResult, lastVal\\\
          - evalFlagMethodImmediate()\\\
 - 2.7.4  - doPollFlag supports immediate number setting \\\
 - 2.7.5  - more QoL checks when mixing up ? and ! for attributes\\\
 - 2.7.6  - trim for getBoolFromZoneProperty and getStringFromZoneProperty\\\
 - 2.7.7  - randomInRange()\\\
          - show number of zones \\\
 - 2.7.8  - inc method now triggers if curr value > last value \\\
          - dec method noew triggers when curr value < last value \\\
          - testFlagByMethodForZone supports lohi, hilo transitions \\\
          - doPollFlag supports 'pulse'\\\
          - pulseFlag\\\
          - unpulse \\\
- 2.7.9   - getFlagValue QoL for <none>\\\
          - setFlagValue QoL for <none>\\\
- 2.8.0      - new allGroupNamesInZone()\\\
- 2.8.1   - new zonesLinkedToUnit()  \\\
- 2.8.2   - flagArrayFromString trims elements before range check \\\
- 2.8.3   - new verifyMethod()\\\
          - changed extractPropertyFromDCS() to also match attributes with blanks like \\\"the Attr\\\" to \\\"theAttr\\\"\\\
          - new expandFlagName()\\\
- 2.8.4   - fixed bug in setFlagValue()\\\
- 2.8.5   - createGroundUnitsInZoneForCoalition() now always passes back a copy of the group data \\\
          - data also contains cty = country and cat = category for easy spawn\\\
          - getFlagValue additional zone name guards \\\
- 2.8.6   - fix in getFlagValue for missing delay \\\
- 2.8.7   - update isPointInsideZone(thePoint, theZone, radiusIncrease) - new radiusIncrease\\\
          - isPointInsideZone() returns delta as well\\\
- 2.9.0   - linked zones can useOffset and useHeading \\\
          - getPoint update \\\
          - pointInZone understands useOrig\\\
          - allStaticsInZone supports useOrig \\\
          - dPhi for zones with useHeading \\\
          - uHdg for zones with useHading, contains linked unit's original heading\\\
          - Late-linking implemented:\\\
          - linkUnit works for late-activating units \\\
          - linkUnit now also works for player / clients, dynamic (re-)linking \\\
          - linkUnit uses zone's origin for all calculations \\\
- 2.9.1   - new evalRemainder()\\\
          - pollFlag supports +/- for immediate numbers, flags, number flags in parantheses\\\
          - stronger guards in hasProperty \\\
- 2.9.2   - new createRandomPointInPolyZone()\\\
          - createRandomZoneInZone uses createRandomPointInPolyZone\\\
          - new createRandomPointInZone()\\\
          - new randomPointInZone()\\\
- 3.0.0   - support for DCS 2.8 linkUnit attribute, integration with \\\
            linedUnit and warning.\\\
          - initZoneVerbosity()\\\
- 3.0.1   - updateMovingZones() better tracks linked units by name\\\
- 3.0.2   - maxRadius for all zones, only differs from radius in polyZones \\\
          - re-factoring zone-base string processing from messenger module\\\
          - new processStringWildcards() that does almost all that messenger can \\\
- 3.0.3   - new getLinkedUnit()\\\
- 3.0.4   - new createRandomPointOnZoneBoundary()\\\
- 3.0.5   - getPositiveRangeFromZoneProperty() now also supports upper bound (optional)\\\
- 3.0.6   - new createSimplePolyZone()\\\
          - new createSimpleQuadZone()\\\
- 3.0.7   - getPoint() can also get land y when passing true as second param\\\
- 3.0.8   - new cfxZones.pointInOneOfZones(thePoint, zoneArray, useOrig) \\\
- 3.0.9   - new getFlareColorStringFromZoneProperty()\\\
\\\
--]]--\\\
cfxZones.verbose = false\\\
cfxZones.caseSensitiveProperties = false -- set to true to make property names case sensitive \\\
cfxZones.ups = 1 -- updates per second. updates moving zones\\\
\\\
cfxZones.zones = {} -- these are the zone as retrieved from the mission.\\\
                    -- ALWAYS USE THESE, NEVER DCS's ZONES!!!!\\\
\\\
-- a zone has the following attributes\\\
-- x, z -- coordinate of center. note they have correct x, 0, z coordinates so no y-->z mapping\\\
-- radius (zero if quad zone)\\\
-- isCircle (true if quad zone)\\\
-- poly the quad coords are in the poly attribute and are a \\\
-- 1..n, wound counter-clockwise as (currently) in DCS:\\\
-- lower left, lower right upper left, upper right, all coords are x, 0, z \\\
-- bounds - contain the AABB coords for the zone: ul (upper left), ur, ll (lower left), lr \\\
--          for both circle and poly, all (x, 0, z)\\\
\\\
-- zones can carry information in their names that can get processed into attributes\\\
-- use \\\
-- zones can also carry information in their 'properties' tag that ME allows to \\\
-- edit. cfxZones provides an easy method to access these properties \\\
--  - getZoneProperty (returns as string)\\\
--  - getMinMaxFromZoneProperty\\\
--  - getBoolFromZoneProperty\\\
--  - getNumberFromZoneProperty\\\
\\\
\\\
-- SUPPORTED PROPERTIES\\\
-- - \\\"linkedUnit\\\" - zone moves with unit of that name. must be exact match\\\
--   can be combined with other attributes that extend (e.g. scar manager and\\\
--   limited pilots/airframes \\\
--\\\
\\\
--\\\
-- readZonesFromDCS is executed exactly once at the beginning\\\
-- from then on, use only the cfxZones.zones table \\\
-- WARNING: cfxZones is NOT case-sensitive. All zone names are \\\
-- indexed by upper case. If you have two zones with same name but \\\
-- different case, one will be replaced\\\
--\\\
\\\
function cfxZones.readFromDCS(clearfirst)\\\
    if (clearfirst) then\\\
        cfxZones.zones = {}\\\
    end\\\
    -- not all missions have triggers or zones\\\
    if not env.mission.triggers then \\\
        if cfxZones.verbose then \\\
            trigger.action.outText(\\\"cf/x zones: no env.triggers defined\\\", 10)\\\
        end\\\
        return\\\
    end\\\
    \\\
    if not env.mission.triggers.zones then \\\
        if cfxZones.verbose then \\\
            trigger.action.outText(\\\"cf/x zones: no zones defined\\\", 10)\\\
        end\\\
        return;\\\
    end\\\
\\\
    -- we only retrieve the data we need. At this point it is name, location and radius\\\
    -- and put this in our own little  structure. we also convert to all upper case name for index\\\
    -- and assume that the name may also carry meaning, e.g. 'LZ:' defines a landing zone\\\
    -- so we can quickly create other sets from this\\\
    -- zone object. DCS 2.7 introduced quads, so this is supported as well\\\
    --   name - name in upper case\\\
    --   isCircle - true if circular zone \\\
    --   isPoly - true if zone is defined by convex polygon, e.g. quad \\\
    --   point - vec3 (x 0 z) - zone's in-world center, used to place the coordinate\\\
    --   radius - number, zero when quad\\\
    --   bounds - aabb with attributes ul, ur, ll, lr (upper left .. lower right) as (x, 0, z)\\\
    --   poly - array 1..n of poly points, wound counter-clockwise \\\
    \\\
    for i, dcsZone in pairs(env.mission.triggers.zones) do\\\
        if type(dcsZone) == 'table' then -- hint taken from MIST: verify type when reading from dcs\\\
                                         -- dcs data is like a box of chocolates...\\\
            local newZone = {}\\\
            -- name, converted to upper is used only for indexing\\\
            -- the original name remains untouched\\\
            newZone.dcsZone = dcsZone\\\
            newZone.name = dcsZone.name\\\
            newZone.isCircle = false\\\
            newZone.isPoly = false\\\
            newZone.radius = 0\\\
            newZone.poly = {}\\\
            newZone.bounds = {}\\\
            newZone.properties = {} -- dcs has this too, copy if present\\\
            if dcsZone.properties then \\\
                newZone.properties = dcsZone.properties \\\
            else\\\
                newZone.properties = {}\\\
            end -- WARNING: REF COPY. May need to clone \\\
            \\\
            local upperName = newZone.name:upper()\\\
            \\\
            -- location as 'point'\\\
            -- WARNING: zones locs are 2D (x,y) pairs, while y in DCS is altitude.\\\
            --          so we need to change (x,y) into (x, 0, z). Since Zones have no\\\
            --          altitude (they are an infinite cylinder) this works. Remember to \\\
            --          drop y from zone calculations to see if inside. \\\
            -- WARNING: ME linked zones have a relative x any y \\\
            --          to the linked unit \\\
            if dcsZone.linkUnit then \\\
                -- calculate the zone's real position by accessing the unit's MX data \\\
                -- as precached by dcsCommon\\\
                local ux, uy = dcsCommon.getUnitStartPosByID(dcsZone.linkUnit)\\\
                newZone.point = cfxZones.createPoint(ux + dcsZone.x, 0, uy + dcsZone.y)\\\
                newZone.dcsOrigin = cfxZones.createPoint(ux + dcsZone.x, 0, uy + dcsZone.y)\\\
            else \\\
                newZone.point = cfxZones.createPoint(dcsZone.x, 0, dcsZone.y)\\\
                newZone.dcsOrigin = cfxZones.createPoint(dcsZone.x, 0, dcsZone.y)\\\
            end\\\
\\\
            -- start type processing. if zone.type exists, we have a mission \\\
            -- created with 2.7 or above, else earlier \\\
            local zoneType = 0\\\
            if (dcsZone.type) then \\\
                zoneType = dcsZone.type \\\
            end\\\
            \\\
            if zoneType == 0 then \\\
                -- circular zone \\\
                newZone.isCircle = true \\\
                newZone.radius = dcsZone.radius\\\
                newZone.maxRadius = newZone.radius -- same for circular\\\
    \\\
            elseif zoneType == 2 then\\\
                -- polyZone\\\
                newZone.isPoly = true \\\
                newZone.radius = dcsZone.radius -- radius is still written in DCS, may change later. The radius has no meaning and is the last radius written before zone changed to poly.\\\
                -- note that newZone.point is only inside the tone for \\\
                -- convex polys, and DML only correctly works with convex polys\\\
                -- now transfer all point in the poly\\\
                -- note: DCS in 2.7 misspells vertices as 'verticies'\\\
                -- correct for this \\\
                newZone.maxRadius = 0\\\
                local verts = {}\\\
                if dcsZone.verticies then verts = dcsZone.verticies \\\
                else \\\
                    -- in later versions, this was corrected\\\
                    verts = dcsZone.vertices -- see if this is ever called\\\
                end\\\
                \\\
                for v=1, #verts do\\\
                    local dcsPoint = verts[v]\\\
                    local polyPoint = cfxZones.createPointFromDCSPoint(dcsPoint) -- (x, y) --> (x, 0, y-->z)\\\
                    newZone.poly[v] = polyPoint\\\
                    -- measure distance from zone's point, and store maxRadius \\\
                    -- dcs always saves a point with the poly zone \\\
                    local dist = dcsCommon.dist(newZone.point, polyPoint)\\\
                    if dist > newZone.maxRadius then newZone.maxRadius = dist end \\\
                end\\\
            else \\\
                \\\
                trigger.action.outText(\\\"cf/x zones: malformed zone #\\\" .. i .. \\\" unknown type \\\" .. zoneType, 10)\\\
            end\\\
            \\\
\\\
            -- calculate bounds\\\
            cfxZones.calculateZoneBounds(newZone) \\\
\\\
            -- add to my table\\\
            cfxZones.zones[upperName] = newZone -- WARNING: UPPER ZONE!!!\\\
            --trigger.action.outText(\\\"znd: procced \\\" .. newZone.name .. \\\" with radius \\\" .. newZone.radius, 30)\\\
        else\\\
            if cfxZones.verbose then \\\
                trigger.action.outText(\\\"cf/x zones: malformed zone #\\\" .. i .. \\\" dropped\\\", 10)\\\
            end\\\
        end -- else var not a table\\\
        \\\
    end -- for all zones kvp\\\
end -- readFromDCS\\\
\\\
function cfxZones.calculateZoneBounds(theZone)\\\
    if not (theZone) then return \\\
    end\\\
    \\\
    local bounds = theZone.bounds -- copy ref!\\\
    \\\
    if theZone.isCircle then \\\
        -- aabb are easy: center +/- radius \\\
        local center = theZone.point\\\
        local radius = theZone.radius \\\
        -- dcs uses z+ is down on map\\\
        -- upper left is center - radius \\\
        bounds.ul = cfxZones.createPoint(center.x - radius, 0, center.z - radius)\\\
        bounds.ur = cfxZones.createPoint(center.x + radius, 0, center.z - radius)\\\
        bounds.ll = cfxZones.createPoint(center.x - radius, 0, center.z + radius)\\\
        bounds.lr = cfxZones.createPoint(center.x + radius, 0, center.z + radius)\\\
        \\\
    elseif theZone.isPoly then\\\
        local poly = theZone.poly -- ref copy!\\\
        -- create the four points\\\
        local ll = cfxZones.createPointFromPoint(poly[1])\\\
        local lr = cfxZones.createPointFromPoint(poly[1])\\\
        local ul = cfxZones.createPointFromPoint(poly[1])\\\
        local ur = cfxZones.createPointFromPoint(poly[1])\\\
        \\\
        local pRad = dcsCommon.dist(theZone.point, poly[1]) -- rRad is radius for polygon from theZone.point \\\
        \\\
        -- now iterate through all points and adjust bounds accordingly \\\
        for v=2, #poly do \\\
            local vertex = poly[v]\\\
            if (vertex.x < ll.x) then ll.x = vertex.x; ul.x = vertex.x end \\\
            if (vertex.x > lr.x) then lr.x = vertex.x; ur.x = vertex.x end \\\
            if (vertex.z < ul.z) then ul.z = vertex.z; ur.z = vertex.z end\\\
            if (vertex.z > ll.z) then ll.z = vertex.z; lr.z = vertex.z end \\\
            local dp = dcsCommon.dist(theZone.point, vertex)\\\
            if dp > pRad then pRad = dp end -- find largst distance to vertex\\\
        end\\\
        \\\
        -- now keep the new point references\\\
        -- and store them in the zone's bounds\\\
        bounds.ll = ll\\\
        bounds.lr = lr\\\
        bounds.ul = ul\\\
        bounds.ur = ur \\\
        -- store pRad \\\
        theZone.pRad = pRad -- not sure we'll ever need that, but at least we have it\\\
--        trigger.action.outText(\\\"+++Zones: poly zone <\\\" .. theZone.name .. \\\"> has pRad = \\\" .. pRad, 30) -- remember to remove me \\\
    else \\\
        -- huston, we have a problem\\\
        if cfxZones.verbose then \\\
            trigger.action.outText(\\\"cf/x zones: calc bounds: zone \\\" .. theZone.name .. \\\" has unknown type\\\", 30)\\\
        end\\\
    end\\\
    \\\
end\\\
\\\
function cfxZones.createPoint(x, y, z)\\\
    local newPoint = {}\\\
    newPoint.x = x\\\
    newPoint.y = y\\\
    newPoint.z = z \\\
    return newPoint\\\
end\\\
\\\
function cfxZones.copyPoint(inPoint) \\\
    local newPoint = {}\\\
    newPoint.x = inPoint.x\\\
    newPoint.y = inPoint.y\\\
    -- handle xz only \\\
    if inPoint.z then \\\
        newPoint.z = inPoint.z \\\
    else \\\
        newPoint.z = inPoint.y \\\
    end\\\
    return newPoint    \\\
end\\\
\\\
function cfxZones.createHeightCorrectedPoint(inPoint) -- this should be in dcsCommon\\\
    local cP = cfxZones.createPoint(inPoint.x, land.getHeight({x=inPoint.x, y=inPoint.z}),inPoint.z)\\\
    return cP\\\
end\\\
\\\
function cfxZones.getHeightCorrectedZonePoint(theZone)\\\
    return cfxZones.createHeightCorrectedPoint(theZone.point)\\\
end\\\
\\\
function cfxZones.createPointFromPoint(inPoint)\\\
    return cfxZones.copyPoint(inPoint)\\\
end\\\
\\\
function cfxZones.createPointFromDCSPoint(inPoint) \\\
    return cfxZones.createPoint(inPoint.x, 0, inPoint.y)\\\
end\\\
\\\
\\\
function cfxZones.createRandomPointInsideBounds(bounds)\\\
    -- warning: bounds do not move woth zone! may have to be updated\\\
    local x = math.random(bounds.ll.x, ur.x)\\\
    local z = math.random(bounds.ll.z, ur.z)\\\
    return cfxZones.createPoint(x, 0, z)\\\
end\\\
\\\
function cfxZones.createRandomPointOnZoneBoundary(theZone)\\\
    if not theZone then return nil end \\\
    if theZone.isPoly then \\\
        local loc, dx, dy = cfxZones.createRandomPointInPolyZone(theZone, true)\\\
        return loc, dx, dy \\\
    else \\\
        local loc, dx, dy = cfxZones.createRandomPointInCircleZone(theZone, true)\\\
        return loc, dx, dy \\\
    end\\\
end\\\
\\\
function cfxZones.createRandomPointInZone(theZone)\\\
    if not theZone then return nil end \\\
    if theZone.isPoly then \\\
        local loc, dx, dy = cfxZones.createRandomPointInPolyZone(theZone)\\\
        return loc, dx, dy \\\
    else \\\
        local loc, dx, dy = cfxZones.createRandomPointInCircleZone(theZone)\\\
        return loc, dx, dy \\\
    end\\\
end\\\
\\\
function cfxZones.randomPointInZone(theZone)\\\
    local loc, dx, dy =  cfxZones.createRandomPointInZone(theZone)\\\
    return loc, dx, dy \\\
end\\\
\\\
function cfxZones.createRandomPointInCircleZone(theZone, onEdge)\\\
    if not theZone.isCircle then \\\
        trigger.action.outText(\\\"+++Zones: warning - createRandomPointInCircleZone called for non-circle zone <\\\" .. theZone.name .. \\\">\\\", 30)\\\
        return {x=theZone.point.x, y=0, z=theZone.point.z}\\\
    end\\\
    \\\
    -- ok, let's first create a random percentage value for the new radius\\\
    -- now lets get a random degree\\\
    local degrees = math.random() * 2 * 3.14152 -- radiants. \\\
    local r = theZone.radius \\\
    if not onEdge then \\\
        r = r * math.random()\\\
    end \\\
    local p = cfxZones.getPoint(theZone) -- force update of zone if linked\\\
    local dx = r * math.cos(degrees)\\\
    local dz = r * math.sin(degrees)\\\
    local px = p.x + dx -- r * math.cos(degrees)\\\
    local pz = p.z + dz -- r * math.sin(degrees)\\\
    return {x=px, y=0, z = pz}, dx, dz -- returns loc and offsets to theZone.point\\\
end\\\
\\\
function cfxZones.createRandomPointInPolyZone(theZone, onEdge)\\\
    if not theZone.isPoly then \\\
        trigger.action.outText(\\\"+++Zones: warning - createRandomPointInPolyZone called for non-poly zone <\\\" .. theZone.name .. \\\">\\\", 30)\\\
        return cfxZones.createPoint(theZone.point.x, 0, theZone.point.z)\\\
    end\\\
    -- force update of all points \\\
    local p = cfxZones.getPoint(theZone)\\\
    \\\
    -- point in convex poly: choose two different lines from that polygon \\\
    local lineIdxA = dcsCommon.smallRandom(#theZone.poly)\\\
    repeat lineIdxB = dcsCommon.smallRandom(#theZone.poly) until (lineIdxA ~= lineIdxB)\\\
    \\\
    -- we now have two different lines. pick a random point on each. \\\
    -- we use lerp to pick any point between a and b \\\
    local a = theZone.poly[lineIdxA]\\\
    lineIdxA = lineIdxA + 1 -- get next point in poly and wrap around\\\
    if lineIdxA > #theZone.poly then lineIdxA = 1 end \\\
    local b = theZone.poly[lineIdxA] \\\
    local randompercent = math.random()\\\
    local sourceA = dcsCommon.vLerp (a, b, randompercent)\\\
    -- if all we want is a point on an edge, we are done \\\
    if onEdge then \\\
        local polyPoint = sourceA\\\
        return polyPoint, polyPoint.x - p.x, polyPoint.z - p.z -- return loc, dx, dz \\\
    end \\\
    \\\
    -- now get point on second line \\\
    a = theZone.poly[lineIdxB]\\\
    lineIdxB = lineIdxB + 1 -- get next point in poly and wrap around\\\
    if lineIdxB > #theZone.poly then lineIdxB = 1 end \\\
    b = theZone.poly[lineIdxB] \\\
    randompercent = math.random()\\\
    local sourceB = dcsCommon.vLerp (a, b, randompercent)\\\
    \\\
    -- now take a random point on that line that entirely \\\
    -- runs through the poly \\\
    randompercent = math.random()\\\
    local polyPoint = dcsCommon.vLerp (sourceA, sourceB, randompercent)\\\
    return polyPoint, polyPoint.x - p.x, polyPoint.z - p.z -- return loc, dx, dz \\\
end\\\
\\\
function cfxZones.addZoneToManagedZones(theZone)\\\
    local upperName = string.upper(theZone.name) -- newZone.name:upper()\\\
    cfxZones.zones[upperName] = theZone\\\
end\\\
\\\
function cfxZones.createUniqueZoneName(inName, searchSet)\\\
    if not inName then return nil end \\\
    if not searchSet then searchSet = cfxZones.zones end \\\
    inName = inName:upper()\\\
    while searchSet[inName] ~= nil do \\\
        inName = inName .. \\\"X\\\"\\\
    end\\\
    return inName\\\
end\\\
\\\
function cfxZones.createSimpleZone(name, location, radius, addToManaged)\\\
    if not radius then radius = 10 end\\\
    if not addToManaged then addToManaged = false end \\\
    if not location then \\\
        location = {}\\\
    end\\\
    if not location.x then location.x = 0 end \\\
    if not location.z then location.z = 0 end \\\
    \\\
    local newZone = cfxZones.createCircleZone(name, location.x, location.z, radius)\\\
    \\\
    if addToManaged then \\\
        cfxZones.addZoneToManagedZones(newZone)\\\
    end\\\
    return newZone\\\
end\\\
\\\
function cfxZones.createCircleZone(name, x, z, radius) \\\
    local newZone = {}\\\
    newZone.isCircle = true\\\
    newZone.isPoly = false\\\
    newZone.poly = {}\\\
    newZone.bounds = {}\\\
            \\\
    newZone.name = name\\\
    newZone.radius = radius\\\
    newZone.point = cfxZones.createPoint(x, 0, z)\\\
 \\\
    -- props \\\
    newZone.properties = {}\\\
    \\\
    -- calculate my bounds\\\
    cfxZones.calculateZoneBounds(newZone)\\\
    \\\
    return newZone\\\
end\\\
\\\
function cfxZones.createSimplePolyZone(name, location, points, addToManaged)\\\
    if not addToManaged then addToManaged = false end \\\
    if not location then \\\
        location = {}\\\
    end\\\
    if not location.x then location.x = 0 end \\\
    if not location.z then location.z = 0 end \\\
\\\
    local newZone = cfxZones.createPolyZone(name, points)\\\
    \\\
    if addToManaged then \\\
        cfxZones.addZoneToManagedZones(newZone)\\\
    end\\\
    return newZone\\\
end\\\
\\\
function cfxZones.createSimpleQuadZone(name, location, points, addToManaged)\\\
    if not location then \\\
        location = {}\\\
    end\\\
    if not location.x then location.x = 0 end \\\
    if not location.z then location.z = 0 end \\\
        \\\
    -- synthesize 4 points if they don't exist\\\
    -- remember: in DCS positive x is up, positive z is right \\\
    if not points then \\\
        points = {} \\\
    end\\\
    if not points[1] then \\\
        -- upper left \\\
        points[1] = {x = location.x-1, y = 0, z = location.z-1}\\\
    end\\\
    if not points[2] then \\\
        -- upper right \\\
        points[2] = {x = location.x-1, y = 0, z = location.z+1}\\\
    end\\\
    if not points[3] then \\\
        -- lower right \\\
        points[3] = {x = location.x+1, y = 0, z = location.z+1}\\\
    end\\\
    if not points[4] then \\\
        -- lower left \\\
        points[4] = {x = location.x+1, y = 0, z = location.z-1}\\\
    end\\\
    \\\
    return cfxZones.createSimplePolyZone(name, location, points, addToManaged)\\\
end\\\
\\\
function cfxZones.createPolyZone(name, poly) -- poly must be array of point type\\\
local newZone = {}\\\
    newZone.isCircle = false\\\
    newZone.isPoly = true\\\
    newZone.poly = {}\\\
    newZone.bounds = {}\\\
            \\\
    newZone.name = name\\\
    newZone.radius = 0\\\
    -- copy poly\\\
    for v=1, #poly do \\\
        local theVertex = poly[v] \\\
        newZone.poly[v] = cfxZones.createPointFromPoint(theVertex) \\\
    end\\\
    \\\
    -- properties \\\
    newZone.properties = {}\\\
    \\\
    cfxZones.calculateZoneBounds(newZone)\\\
end\\\
\\\
\\\
\\\
function cfxZones.createRandomZoneInZone(name, inZone, targetRadius, entirelyInside)\\\
    -- create a new circular zone with center placed inside inZone\\\
    -- if entirelyInside is false, only the zone's center is guaranteed to be inside\\\
    -- inZone.\\\
    -- entirelyInside is not guaranteed for polyzones\\\
    \\\
--    trigger.action.outText(\\\"Zones: creating rZiZ with tr = \\\" .. targetRadius .. \\\" for \\\" .. inZone.name .. \\\" that as r = \\\" .. inZone.radius, 10)\\\
    \\\
    if inZone.isCircle then \\\
        local sourceRadius = inZone.radius\\\
        if entirelyInside and targetRadius > sourceRadius then targetRadius = sourceRadius end\\\
        if entirelyInside then sourceRadius = sourceRadius - targetRadius end\\\
    \\\
        -- ok, let's first create a random percentage value for the new radius\\\
        local percent = 1 / math.random(100)\\\
        -- now lets get a random degree\\\
        local degrees = math.random(360) * 3.14152 / 180 -- ok, it's actually radiants. \\\
        local r = sourceRadius * percent \\\
        local x = inZone.point.x + r * math.cos(degrees)\\\
        local z = inZone.point.z + r * math.sin(degrees)\\\
        -- construct new zone\\\
        local newZone = cfxZones.createCircleZone(name, x, z, targetRadius)\\\
        return newZone\\\
    \\\
    elseif inZone.isPoly then \\\
        -- we have a poly zone. the way we do this is simple:\\\
        -- generate random x, z with ranges of the bounding box \\\
        -- until the point falls within the polygon.\\\
        --[[ replaced by new code \\\
        \\\
        local newPoint = {}\\\
        local emergencyBrake = 0\\\
        repeat\\\
            newPoint = cfxZones.createRandomPointInsideBounds(inZone.bounds)\\\
            emergencyBrake = emergencyBrake + 1\\\
            if (emergencyBrake > 100) then \\\
                newPoint = cfxZones.copyPoint(inZone.Point)\\\
                trigger.action.outText(\\\"CreateZoneInZone: emergency brake for inZone\\\" .. inZone.name,  10)\\\
                break\\\
            end\\\
        until cfxZones.isPointInsidePoly(newPoint, inZone.poly)\\\
        --]]--\\\
        local newPoint = cfxZones.createRandomPointInPolyZone(inZone)\\\
        -- construct new zone\\\
        local newZone = cfxZones.createCircleZone(name, newPoint.x, newPoint.z, targetRadius)\\\
        return newZone\\\
        \\\
    else \\\
        -- zone type unknown\\\
        trigger.action.outText(\\\"CreateZoneInZone: unknown zone type for inZone =\\\" .. inZone.name ,  10)\\\
        return nil \\\
    end\\\
end\\\
\\\
-- polygon inside zone calculations\\\
\\\
\\\
-- isleft returns true if point P is to the left of line AB \\\
-- by determining the sign (up or down) of the normal vector of \\\
-- the two vectors PA and PB in the y coordinate. We arbitrarily define\\\
-- left as being > 0, so right is <= 0. As long as we always use the \\\
-- same comparison, it does not matter what up or down mean.\\\
-- this is important because we don't know if dcs always winds quads\\\
-- the same way, we must simply assume that they are wound as a polygon \\\
function cfxZones.isLeftXZ(A, B, P)\\\
    return ((B.x - A.x)*(P.z - A.z) - (B.z - A.z)*(P.x - A.x)) > 0\\\
end\\\
\\\
-- returns true/false for inside\\\
function cfxZones.isPointInsideQuad(thePoint, A, B, C, D) \\\
    -- Inside test (only convex polygons): \\\
    -- point lies on the same side of each quad's vertex AB, BC, CD, DA\\\
    -- how do we find out which side a point lies on? via the cross product\\\
    -- see isLeft below\\\
    \\\
    -- so all we need to do is make sure all results of isLeft for all\\\
    -- four sides are the same\\\
    mustMatch = isLeftXZ(A, B, thePoint) -- all test results must be the same and we are ok\\\
                                       -- they just must be the same side.\\\
    if (cfxZones.isLeftXZ(B, C, thePoint ~= mustMatch)) then return false end -- on other side than all before\\\
    if (cfxZones.isLeftXZ(C, D, thePoint ~= mustMatch)) then return false end \\\
    if (cfxZones.isLeftXZ(D, A, thePoint ~= mustMatch)) then return false end\\\
    return true\\\
end\\\
\\\
-- generalized version of insideQuad, assumes winding of poly, poly convex, poly closed\\\
function cfxZones.isPointInsidePoly(thePoint, poly)\\\
    local mustMatch = cfxZones.isLeftXZ(poly[1], poly[2], thePoint)\\\
    for v=2, #poly-1 do \\\
        if cfxZones.isLeftXZ(poly[v], poly[v+1], thePoint) ~= mustMatch then return false end\\\
    end\\\
    -- final test\\\
    if cfxZones.isLeftXZ(poly[#poly], poly[1], thePoint) ~= mustMatch then return false end\\\
    \\\
    return true\\\
end;\\\
\\\
function cfxZones.isPointInsideZone(thePoint, theZone, radiusIncrease)\\\
    -- radiusIncrease only works for circle zones \\\
    if not radiusIncrease then radiusIncrease = 0 end \\\
    local p = {x=thePoint.x, y = 0, z = thePoint.z} -- zones have no altitude\\\
    if (theZone.isCircle) then \\\
        local zp = cfxZones.getPoint(theZone)\\\
        local d = dcsCommon.dist(p, theZone.point)\\\
        return d < theZone.radius + radiusIncrease, d \\\
    end \\\
    \\\
    if (theZone.isPoly) then \\\
        --trigger.action.outText(\\\"zne: isPointInside: \\\" .. theZone.name .. \\\" is Polyzone!\\\", 30)\\\
        return (cfxZones.isPointInsidePoly(p, theZone.poly)), 0 -- always returns delta 0\\\
    end\\\
\\\
    trigger.action.outText(\\\"isPointInsideZone: Unknown zone type for \\\" .. outerZone.name, 10)\\\
end\\\
\\\
-- isZoneInZone returns true if center of innerZone is inside  outerZone\\\
function cfxZones.isZoneInsideZone(innerZone, outerZone) \\\
    return cfxZones.isPointInsideZone(innerZone.point, outerZone)\\\
\\\
    \\\
end\\\
\\\
function cfxZones.getZonesContainingPoint(thePoint, testZones) -- return array \\\
    if not testZones then \\\
        testZones = cfxZones.zones \\\
    end \\\
    \\\
    local containerZones = {}\\\
    for tName, tData in pairs(testZones) do \\\
        if cfxZones.isPointInsideZone(thePoint, tData) then \\\
            table.insert(containerZones, tData)\\\
        end\\\
    end\\\
\\\
    return containerZones\\\
end\\\
\\\
function cfxZones.getFirstZoneContainingPoint(thePoint, testZones)\\\
    if not testZones then \\\
        testZones = cfxZones.zones \\\
    end \\\
    \\\
    for tName, tData in pairs(testZones) do \\\
        if cfxZones.isPointInsideZone(thePoint, tData) then \\\
            return tData\\\
        end\\\
    end\\\
\\\
    return nil\\\
end\\\
\\\
function cfxZones.getAllZonesInsideZone(superZone, testZones) -- returnes array!\\\
    if not testZones then \\\
        testZones = cfxZones.zones \\\
    end \\\
    \\\
    local containedZones = {}\\\
    for zName, zData in pairs(testZones) do\\\
        if cfxZones.isZoneInsideZone(zData, superZone) then \\\
            if zData ~= superZone then \\\
                -- we filter superzone because superzone usually resides \\\
                -- inside itself \\\
                table.insert(containedZones, zData)\\\
            end\\\
        end\\\
    end\\\
    return containedZones \\\
end\\\
\\\
function cfxZones.getZonesWithAttributeNamed(attributeName, testZones)\\\
    if not testZones then testZones = cfxZones.zones end \\\
\\\
    local attributZones = {}\\\
    for aName,aZone in pairs(testZones) do\\\
        local attr = cfxZones.getZoneProperty(aZone, attributeName)\\\
        if attr then \\\
            -- this zone has the requested attribute\\\
            table.insert(attributZones, aZone)\\\
        end\\\
    end\\\
    return attributZones\\\
end\\\
\\\
--\\\
-- units / groups in zone\\\
--\\\
function cfxZones.allGroupsInZone(theZone, categ) -- categ is optional, must be code \\\
    -- warning: does not check for exiting!\\\
    --trigger.action.outText(\\\"Zone \\\" .. theZone.name .. \\\" radius \\\" .. theZone.radius, 30)\\\
    local inZones = {}\\\
    local coals = {0, 1, 2} -- all coalitions\\\
    for idx, coa in pairs(coals) do \\\
        local allGroups = coalition.getGroups(coa, categ)\\\
        for key, group in pairs(allGroups) do -- iterate all groups\\\
            if cfxZones.isGroupPartiallyInZone(group, theZone) then\\\
                table.insert(inZones, group)\\\
            end\\\
        end\\\
    end\\\
    return inZones\\\
end\\\
\\\
function cfxZones.allGroupNamesInZone(theZone, categ) -- categ is optional, must be code \\\
    -- warning: does not check for exiting!\\\
    --trigger.action.outText(\\\"Zone \\\" .. theZone.name .. \\\" radius \\\" .. theZone.radius, 30)\\\
    local inZones = {}\\\
    local coals = {0, 1, 2} -- all coalitions\\\
    for idx, coa in pairs(coals) do \\\
        local allGroups = coalition.getGroups(coa, categ)\\\
        for key, group in pairs(allGroups) do -- iterate all groups\\\
            if cfxZones.isGroupPartiallyInZone(group, theZone) then\\\
                table.insert(inZones, group:getName())\\\
            end\\\
        end\\\
    end\\\
    return inZones\\\
end\\\
\\\
function cfxZones.allStaticsInZone(theZone, useOrigin) -- categ is optional, must be code \\\
    -- warning: does not check for exiting!\\\
    local inZones = {}\\\
    local coals = {0, 1, 2} -- all coalitions\\\
    for idx, coa in pairs(coals) do \\\
        local allStats = coalition.getStaticObjects(coa)\\\
        for key, statO in pairs(allStats) do -- iterate all groups\\\
            local oP = statO:getPoint()\\\
            if useOrigin then \\\
                if cfxZones.pointInZone(oP, theZone, true) then \\\
                    -- use DCS original coords\\\
                    table.insert(inZones, statO)\\\
                end\\\
            elseif cfxZones.pointInZone(oP, theZone) then\\\
                table.insert(inZones, statO)\\\
            end\\\
        end\\\
    end\\\
    return inZones\\\
end\\\
\\\
function cfxZones.groupsOfCoalitionPartiallyInZone(coal, theZone, categ) -- categ is optional\\\
    local groupsInZone = {}\\\
    local allGroups = coalition.getGroups(coal, categ)\\\
    for key, group in pairs(allGroups) do -- iterate all groups\\\
        if group:isExist() then\\\
            if cfxZones.isGroupPartiallyInZone(group, theZone) then\\\
                table.insert(groupsInZone, group)            \\\
            end\\\
        end\\\
    end\\\
    return groupsInZone\\\
end\\\
\\\
function cfxZones.isGroupPartiallyInZone(aGroup, aZone)\\\
    if not aGroup then return false end \\\
    if not aZone then return false end \\\
        \\\
    if not aGroup:isExist() then return false end \\\
    local allUnits = aGroup:getUnits()\\\
    for uk, aUnit in pairs (allUnits) do \\\
        if aUnit:isExist() and aUnit:getLife() > 1 then         \\\
            local p = aUnit:getPoint()\\\
            local inzone, percent, dist = cfxZones.pointInZone(p, aZone)\\\
            if inzone then -- cfxZones.isPointInsideZone(p, aZone) then             \\\
                --trigger.action.outText(\\\"zne: YAY <\\\" .. aUnit:getName() .. \\\"> IS IN \\\" .. aZone.name, 30) \\\
                return true\\\
            end \\\
            --trigger.action.outText(\\\"zne: <\\\" .. aUnit:getName() .. \\\"> not in \\\" .. aZone.name .. \\\", dist = \\\" .. dist .. \\\", rad = \\\", aZone.radius, 30) \\\
        end\\\
    end\\\
    return false\\\
end\\\
\\\
function cfxZones.isEntireGroupInZone(aGroup, aZone)\\\
    if not aGroup then return false end \\\
    if not aZone then return false end \\\
    if not aGroup:isExist() then return false end \\\
    local allUnits = aGroup:getUnits()\\\
    for uk, aUnit in pairs (allUnits) do \\\
        if aUnit:isExist() and aUnit:getLife() > 1 then \\\
            local p = aUnit:getPoint()\\\
            if not cfxZones.isPointInsideZone(p, aZone) then \\\
                return false\\\
            end\\\
        end\\\
    end\\\
    return true\\\
end\\\
\\\
\\\
--\\\
-- Zone Manipulation\\\
--\\\
\\\
function cfxZones.offsetZone(theZone, dx, dz)\\\
    -- first, update center \\\
    theZone.point.x = theZone.point.x + dx\\\
    theZone.point.z = theZone.point.z + dz \\\
    \\\
    -- now process all polygon points - it's empty for circular, so don't worry\\\
    for v=1, #theZone.poly do \\\
        theZone.poly[v].x = theZone.poly[v].x + dx\\\
        theZone.poly[v].z = theZone.poly[v].z + dz \\\
    end\\\
end\\\
\\\
function cfxZones.moveZoneTo(theZone, x, z)\\\
    local dx = x - theZone.point.x\\\
    local dz = z - theZone.point.z \\\
    cfxZones.offsetZone(theZone, dx, dz)\\\
end;\\\
\\\
function cfxZones.centerZoneOnUnit(theZone, theUnit) \\\
    local thePoint = theUnit:getPoint()\\\
    cfxZones.moveZoneTo(theZone, thePoint.x, thePoint.z)\\\
end\\\
\\\
\\\
--[[\\\
-- no longer makes sense with poly zones\\\
function cfxZones.isZoneEntirelyInsideZone(innerZone, outerZone)\\\
    if (innerZone.radius > outerZone.radius) then return false end -- cant fit inside\\\
    local d = dcsCommon.dist(innerZone.point, outerZone.point)\\\
    local reducedR = outerZone.radius - innerZone.radius\\\
    return d < reducedR\\\
end;\\\
--]]\\\
\\\
function cfxZones.dumpZones(zoneTable)\\\
    if not zoneTable then zoneTable = cfxZones.zones end \\\
    \\\
    trigger.action.outText(\\\"Zones START\\\", 10)\\\
    for i, zone in pairs(zoneTable) do \\\
        local myType = \\\"unknown\\\"\\\
        if zone.isCircle then myType = \\\"Circle\\\" end\\\
        if zone.isPoly then myType = \\\"Poly\\\" end \\\
        \\\
        trigger.action.outText(\\\"#\\\".. i .. \\\": \\\" .. zone.name .. \\\" of type \\\" .. myType, 10)\\\
    end\\\
    trigger.action.outText(\\\"Zones END\\\", 10)\\\
end\\\
\\\
function cfxZones.stringStartsWith(theString, thePrefix)\\\
    return theString:find(thePrefix) == 1\\\
end\\\
\\\
function cfxZones.keysForTable(theTable)\\\
    local keyset={}\\\
    local n=0\\\
\\\
    for k,v in pairs(tab) do\\\
        n=n+1\\\
        keyset[n]=k\\\
    end\\\
    return keyset\\\
end\\\
\\\
\\\
--\\\
-- return all zones that have a specific named property\\\
--\\\
function cfxZones.zonesWithProperty(propertyName, searchSet)\\\
    if not searchSet then searchSet = cfxZones.zones end \\\
    local theZones = {}\\\
    for k, aZone in pairs(searchSet) do \\\
        if not aZone then \\\
            trigger.action.outText(\\\"+++zone: nil aZone for \\\" .. k, 30)\\\
        else \\\
            local lU = cfxZones.getZoneProperty(aZone, propertyName)\\\
            if lU then \\\
                table.insert(theZones, aZone)\\\
            end\\\
        end\\\
    end    \\\
    return theZones\\\
end\\\
\\\
--\\\
-- return all zones from the zone table that begin with string prefix\\\
--\\\
function cfxZones.zonesStartingWithName(prefix, searchSet)\\\
    \\\
    if not searchSet then searchSet = cfxZones.zones end \\\
    \\\
--    trigger.action.outText(\\\"Enter: zonesStartingWithName for \\\" .. prefix , 30)\\\
    local prefixZones = {}\\\
    prefix = prefix:upper() -- all zones have UPPERCASE NAMES! THEY SCREAM AT YOU\\\
    for name, zone in pairs(searchSet) do\\\
--        trigger.action.outText(\\\"testing \\\" .. name:upper() .. \\\" starts with \\\" .. prefix , 30)\\\
        if cfxZones.stringStartsWith(name:upper(), prefix) then\\\
            prefixZones[name] = zone -- note: ref copy!\\\
            --trigger.action.outText(\\\"zone with prefix <\\\" .. prefix .. \\\"> found: \\\" .. name, 10)\\\
        end\\\
    end\\\
    \\\
    return prefixZones\\\
end\\\
\\\
--\\\
-- return all zones from the zone table that begin with the string or set of strings passed in prefix \\\
-- if you pass 'true' as second (optional) parameter, it will first look for all zones that begin\\\
-- with '+' and return only those. Use during debugging to force finding a specific zone\\\
--\\\
function cfxZones.zonesStartingWith(prefix, searchSet, debugging)\\\
    -- you can force zones by having their name start with \\\"+\\\"\\\
    -- which will force them to return immediately if debugging is true for this call\\\
\\\
    if (debugging) then \\\
        local debugZones = cfxZones.zonesStartingWithName(\\\"+\\\", searchSet)\\\
        if not (next(debugZones) == nil) then -- # operator only works on array elements \\\
            --trigger.action.outText(\\\"returning zones with prefix <\\\" .. prefix .. \\\">\\\", 10)\\\
            return debugZones \\\
        end \\\
    end\\\
    \\\
    --trigger.action.outText(\\\"#debugZones is  <\\\" .. #debugZones .. \\\">\\\", 10)\\\
\\\
    if (type(prefix) == \\\"string\\\") then \\\
        return cfxZones.zonesStartingWithName(prefix, searchSet)\\\
    end\\\
    \\\
    local allZones = {}\\\
    for i=1, #prefix do \\\
        -- iterate through all names in prefix set\\\
        local theName = prefix[i]\\\
        local newZones = cfxZones.zonesStartingWithName(theName, searchSet)\\\
        -- add them all to current table\\\
        for zName, zInfo in pairs(newZones) do \\\
            allZones[zName] = zInfo -- will also replace doublets\\\
        end\\\
    end\\\
    \\\
    return allZones\\\
end\\\
\\\
function cfxZones.getZoneByName(aName, searchSet) \\\
    if not searchSet then searchSet = cfxZones.zones end \\\
    aName = aName:upper()\\\
    return searchSet[aName] -- the joys of key value pairs\\\
end\\\
\\\
function cfxZones.getZonesContainingString(aString, searchSet) \\\
    if not searchSet then searchSet = cfxZones.zones end\\\
    aString = string.upper(aString)\\\
    resultSet = {}\\\
    for zName, zData in pairs(searchSet) do \\\
        if aString == string.upper(zData.name) then \\\
            resultSet[zName] = zData\\\
        end\\\
    end\\\
    \\\
end;\\\
\\\
-- filter zones by range to a point. returns indexed set\\\
function cfxZones.getZonesInRange(point, range, theZones)\\\
    if not theZones then theZones = cfxZones.zones end\\\
    \\\
    local inRangeSet = {}\\\
    for zName, zData in pairs (theZones) do \\\
        if dcsCommon.dist(point, zData.point) < range then \\\
            table.insert(inRangeSet, zData)\\\
        end\\\
    end\\\
    return inRangeSet \\\
end\\\
\\\
-- get closest zone returns the zone that is closest to point \\\
function cfxZones.getClosestZone(point, theZones)\\\
    if not theZones then theZones = cfxZones.zones end\\\
    local lPoint = {x=point.x, y=0, z=point.z}\\\
    local currDelta = math.huge \\\
    local closestZone = nil\\\
    for zName, zData in pairs(theZones) do \\\
        local zPoint = cfxZones.getPoint(zData)\\\
        local delta = dcsCommon.dist(lPoint, zPoint) -- emulate flag compare \\\
        if (delta < currDelta) then \\\
            currDelta = delta\\\
            closestZone = zData\\\
        end\\\
    end\\\
    return closestZone, currDelta \\\
end\\\
\\\
-- return a random zone from the table passed in zones\\\
function cfxZones.pickRandomZoneFrom(zones)\\\
    if not zones then zones = cfxZones.zones end\\\
    local indexedZones = dcsCommon.enumerateTable(zones)\\\
    local r = math.random(#indexedZones)\\\
    return indexedZones[r]\\\
end\\\
\\\
-- return an zone element by index \\\
function cfxZones.getZoneByIndex(theZones, theIndex) \\\
    local enumeratedZones = dcsCommon.enumerateTable(theZones)\\\
    if (theIndex > #enumeratedZones) then\\\
        trigger.action.outText(\\\"WARNING: zone index \\\" .. theIndex .. \\\" out of bounds - max = \\\" .. #enumeratedZones, 30)\\\
        return nil end\\\
    if (theIndex < 1) then return nil end\\\
    \\\
    return enumeratedZones[theIndex]\\\
end\\\
\\\
-- place a smoke marker in center of zone, offset by dx, dy \\\
function cfxZones.markZoneWithSmoke(theZone, dx, dz, smokeColor, alt)\\\
    if not alt then alt = 5 end \\\
    local point = cfxZones.getPoint(theZone) --{} -- theZone.point\\\
    point.x = point.x + dx -- getpoint updates and returns copy \\\
    point.z = point.z + dz \\\
    -- get height at point \\\
    point.y = land.getHeight({x = point.x, y = point.z}) + alt\\\
    -- height-correct\\\
    --local newPoint= {x = point.x, y = land.getHeight({x = point.x, y = point.z}) + 3, z= point.z}\\\
    trigger.action.smoke(point, smokeColor)\\\
end\\\
\\\
-- place a smoke marker in center of zone, offset by radius and degrees \\\
function cfxZones.markZoneWithSmokePolar(theZone, radius, degrees, smokeColor, alt)\\\
    local rads = degrees * math.pi / 180\\\
    local dx = radius * math.sin(rads)\\\
    local dz = radius * math.cos(rads)\\\
    cfxZones.markZoneWithSmoke(theZone, dx, dz, smokeColor, alt)\\\
end\\\
\\\
-- place a smoke marker in center of zone, offset by radius and randomized degrees \\\
function cfxZones.markZoneWithSmokePolarRandom(theZone, radius, smokeColor)\\\
    local degrees = math.random(360)\\\
    cfxZones.markZoneWithSmokePolar(theZone, radius, degrees, smokeColor)\\\
end\\\
\\\
function cfxZones.pointInOneOfZones(thePoint, zoneArray, useOrig) \\\
    if not zoneArray then zoneArray = cfxZones.zones end \\\
    for idx, theZone in pairs(zoneArray) do \\\
        local isIn, percent, dist = cfxZones.pointInZone(thePoint, theZone, useOrig)\\\
        if isIn then return isIn, percent, dist, theZone end \\\
    end\\\
    return false, 0, 0, nil \\\
end\\\
\\\
\\\
-- unitInZone returns true if theUnit is inside the zone \\\
-- the second value returned is the percentage of distance\\\
-- from center to rim, with 100% being entirely in center, 0 = outside\\\
-- the third value returned is the distance to center\\\
function cfxZones.pointInZone(thePoint, theZone, useOrig)\\\
\\\
    if not (theZone) then return false, 0, 0 end\\\
        \\\
    local pflat = {x = thePoint.x, y = 0, z = thePoint.z}\\\
    \\\
    local zpoint \\\
    if useOrig then\\\
        zpoint = cfxZones.getDCSOrigin(theZone)\\\
    else \\\
        zpoint = cfxZones.getPoint(theZone) -- updates zone if linked \\\
    end\\\
    local ppoint = thePoint -- xyz\\\
    local pflat = {x = ppoint.x, y = 0, z = ppoint.z}\\\
    local dist = dcsCommon.dist(zpoint, pflat)\\\
    \\\
    if theZone.isCircle then \\\
        if theZone.radius <= 0 then \\\
            return false, 0, 0\\\
        end\\\
\\\
        local success = dist < theZone.radius\\\
        local percentage = 0\\\
        if (success) then \\\
            percentage = 1 - dist / theZone.radius \\\
        end\\\
        return success, percentage, dist \\\
    \\\
    elseif theZone.isPoly then\\\
        local success = cfxZones.isPointInsidePoly(pflat, theZone.poly)\\\
        return success, 0, dist\\\
    else \\\
        trigger.action.outText(\\\"pointInZone: Unknown zone type for \\\" .. theZone.name, 10)\\\
    end\\\
\\\
    return false\\\
end\\\
\\\
function cfxZones.unitInZone(theUnit, theZone)\\\
    if not (theUnit) then return false, 0, 0 end\\\
    if not (theUnit:isExist()) then return false, 0, 0 end\\\
    -- force zone update if it is linked to another zone \\\
    -- pointInZone does update\\\
    local thePoint = theUnit:getPoint()\\\
    return cfxZones.pointInZone(thePoint, theZone)\\\
    \\\
end\\\
\\\
-- returns all units of the input set that are inside the zone \\\
function cfxZones.unitsInZone(theUnits, theZone)\\\
    if not theUnits then return {} end\\\
    if not theZone then return {} end\\\
    \\\
    local zoneUnits = {}\\\
    for index, aUnit in pairs(theUnits) do \\\
        if cfxZones.unitInZone(aUnit, theZone) then \\\
            table.insert( zoneUnits, aUnit)\\\
        end\\\
    end\\\
    return zoneUnits\\\
end\\\
\\\
function cfxZones.closestUnitToZoneCenter(theUnits, theZone)\\\
    -- does not care if they really are in zone. call unitsInZone first\\\
    -- if you need to have them filtered\\\
    -- theUnits MUST BE ARRAY\\\
    if not theUnits then return nil end\\\
    if #theUnits == 0 then return nil end\\\
    local closestUnit = theUnits[1]\\\
    for i=2, #theUnits do\\\
        local aUnit = theUnits[i]\\\
        if dcsCommon.dist(theZone.point, closestUnit:getPoint()) > dcsCommon.dist(theZone.point, aUnit:getPoint()) then \\\
            closestUnit = aUnit\\\
        end\\\
    end\\\
    return closestUnit\\\
end\\\
\\\
function cfxZones.anyPlayerInZone(theZone) -- returns first player it finds\\\
    for pname, pinfo in pairs(cfxPlayer.playerDB) do\\\
        local playerUnit = pinfo.unit\\\
        if (cfxZones.unitInZone(playerUnit, theZone)) then \\\
            return true, playerUnit\\\
        end\\\
    end -- for all players \\\
    return false, nil\\\
end\\\
\\\
\\\
-- grow zone\\\
function cfxZones.growZone()\\\
    -- circular zones simply increase radius\\\
    -- poly zones: not defined \\\
    \\\
end\\\
\\\
\\\
-- creating units in a zone\\\
function cfxZones.createGroundUnitsInZoneForCoalition (theCoalition, groupName, theZone, theUnits, formation, heading) \\\
    -- theUnits can be string or table of string \\\
    if not groupName then groupName = \\\"G_\\\"..theZone.name end \\\
    -- group name will be taken from zone name and prependend with \\\"G_\\\"\\\
    local theGroup = dcsCommon.createGroundGroupWithUnits(groupName, theUnits, theZone.radius, nil, formation)\\\
    \\\
    -- turn the entire formation to heading\\\
    if (not heading) then heading = 0 end\\\
    dcsCommon.rotateGroupData(theGroup, heading) -- currently, group is still at origin, no cx, cy\\\
    \\\
    \\\
    -- now move the group to center of theZone\\\
    dcsCommon.moveGroupDataTo(theGroup, \\\
                          theZone.point.x, \\\
                          theZone.point.z) -- watchit: Z!!!\\\
\\\
\\\
    -- create the group in the world and return it\\\
    -- first we need to translate the coalition to a legal \\\
    -- country. we use UN for neutral, cjtf for red and blue \\\
    local theSideCJTF = dcsCommon.coalition2county(theCoalition)\\\
    -- store cty and cat for later access. DCS doesn't need it, but we may \\\
    \\\
    theGroup.cty = theSideCJTF\\\
    theGroup.cat = Group.Category.GROUND\\\
    \\\
    -- create a copy of the group data for \\\
    -- later reference \\\
    local groupDataCopy = dcsCommon.clone(theGroup)\\\
\\\
    local newGroup = coalition.addGroup(theSideCJTF, Group.Category.GROUND, theGroup)\\\
    return newGroup, groupDataCopy\\\
end\\\
\\\
--\\\
-- ===============\\\
-- FLAG PROCESSING \\\
-- ===============\\\
--\\\
\\\
--\\\
-- Flag Pulling \\\
--\\\
function cfxZones.pulseFlag(theFlag, method, theZone)\\\
    local args = {}\\\
    args.theFlag = theFlag\\\
    args.method = method\\\
    args.theZone = theZone \\\
    local delay = 3\\\
    if dcsCommon.containsString(method, \\\",\\\") then \\\
        local parts = dcsCommon.splitString(method, \\\",\\\")\\\
        delay = parts[2]\\\
        if delay then delay = tonumber(delay) end  \\\
    end\\\
    if not delay then delay = 3 end \\\
    if theZone.verbose then \\\
        trigger.action.outText(\\\"+++zne: RAISING pulse t=\\\"..delay..\\\" for flag <\\\" .. theFlag .. \\\"> in zone <\\\" .. theZone.name ..\\\">\\\", 30)\\\
    end \\\
    local newVal = 1\\\
    cfxZones.setFlagValue(theFlag, newVal, theZone)\\\
    \\\
    -- schedule second half of pulse \\\
    timer.scheduleFunction(cfxZones.unPulseFlag, args, timer.getTime() + delay)\\\
end\\\
\\\
function cfxZones.unPulseFlag(args)\\\
    local theZone = args.theZone\\\
    local method = args.method \\\
    local theFlag = args.theFlag \\\
    local newVal = 0\\\
    -- we may later use method to determine pulse direction / newVal\\\
    -- for now, we always go low \\\
    if theZone.verbose then \\\
        trigger.action.outText(\\\"+++zne: DOWNPULSE pulse for flag <\\\" .. theFlag .. \\\"> in zone <\\\" .. theZone.name ..\\\">\\\", 30)\\\
    end\\\
    cfxZones.setFlagValue(theFlag, newVal, theZone)\\\
end\\\
\\\
function cfxZones.evalRemainder(remainder)\\\
    local rNum = tonumber(remainder)\\\
    if not rNum then \\\
        -- we use remainder as name for flag \\\
        -- PROCESS ESCAPE SEQUENCES\\\
        local esc = string.sub(remainder, 1, 1)\\\
        local last = string.sub(remainder, -1)\\\
        if esc == \\\"@\\\" then \\\
            remainder = string.sub(remainder, 2)\\\
            remainder = dcsCommon.trim(remainder)\\\
        end\\\
        \\\
        if esc == \\\"(\\\" and last == \\\")\\\" and string.len(remainder) > 2 then \\\
            -- note: iisues with startswith(\\\"(\\\") ???\\\
            remainder = string.sub(remainder, 2, -2)\\\
            remainder = dcsCommon.trim(remainder)        \\\
        end\\\
        if esc == \\\"\\\\\\\"\\\" and last == \\\"\\\\\\\"\\\" and string.len(remainder) > 2 then \\\
            remainder = string.sub(remainder, 2, -2)\\\
            remainder = dcsCommon.trim(remainder)        \\\
        end\\\
        if cfxZones.verbose then \\\
            trigger.action.outText(\\\"+++zne: accessing flag <\\\" .. remainder .. \\\">\\\", 30)\\\
        end \\\
        rNum = cfxZones.getFlagValue(remainder, theZone)\\\
    end \\\
    return rNum\\\
end\\\
\\\
function cfxZones.doPollFlag(theFlag, method, theZone)\\\
    if cfxZones.verbose then \\\
        trigger.action.outText(\\\"+++zones: polling flag \\\" .. theFlag .. \\\" with \\\" .. method, 30)\\\
    end \\\
    \\\
    if not theZone then \\\
        trigger.action.outText(\\\"+++zones: nil theZone on pollFlag\\\", 30)\\\
    end\\\
    \\\
    method = method:lower()\\\
    method = dcsCommon.trim(method)\\\
    val = tonumber(method)\\\
    if dcsCommon.stringStartsWith(method, \\\"+\\\") or dcsCommon.stringStartsWith(method, \\\"-\\\")\\\
    then \\\
        -- skip this processing, a legal Lua val can start with \\\"+\\\" or \\\"-\\\"\\\
        -- but we interpret it as a method\\\
    else\\\
        if val then \\\
            cfxZones.setFlagValue(theFlag, val, theZone)\\\
            if cfxZones.verbose or theZone.verbose then\\\
                trigger.action.outText(\\\"+++zones: flag <\\\" .. theFlag .. \\\"> changed to #\\\" .. val, 30)\\\
            end \\\
            return\\\
        end \\\
    end\\\
    --trigger.action.outText(\\\"+++zones: polling \\\" .. theZone.name .. \\\" method \\\" .. method .. \\\" flag \\\" .. theFlag, 30)\\\
    local currVal = cfxZones.getFlagValue(theFlag, theZone)\\\
    if method == \\\"inc\\\" or method == \\\"f+1\\\" then \\\
        --trigger.action.setUserFlag(theFlag, currVal + 1)\\\
        cfxZones.setFlagValue(theFlag, currVal+1, theZone)\\\
        \\\
    elseif method == \\\"dec\\\" or method == \\\"f-1\\\" then \\\
        -- trigger.action.setUserFlag(theFlag, currVal - 1)\\\
        cfxZones.setFlagValue(theFlag, currVal-1, theZone)\\\
\\\
    elseif method == \\\"off\\\" or method == \\\"f=0\\\" then \\\
        -- trigger.action.setUserFlag(theFlag, 0)\\\
        cfxZones.setFlagValue(theFlag, 0, theZone)\\\
\\\
    elseif method == \\\"flip\\\" or method == \\\"xor\\\" then \\\
        if currVal ~= 0 then \\\
--            trigger.action.setUserFlag(theFlag, 0)\\\
            cfxZones.setFlagValue(theFlag, 0, theZone)\\\
\\\
        else \\\
            --trigger.action.setUserFlag(theFlag, 1)\\\
            cfxZones.setFlagValue(theFlag, 1, theZone)\\\
        end\\\
        \\\
    elseif dcsCommon.stringStartsWith(method, \\\"pulse\\\") then \\\
        cfxZones.pulseFlag(theFlag, method, theZone)\\\
        \\\
    elseif dcsCommon.stringStartsWith(method, \\\"+\\\") then \\\
        -- we add whatever is to the right \\\
        local remainder = dcsCommon.removePrefix(method, \\\"+\\\")\\\
        local adder = cfxZones.evalRemainder(remainder)\\\
        cfxZones.setFlagValue(theFlag, currVal+adder, theZone)\\\
        if theZone.verbose then \\\
            trigger.action.outText(\\\"+++zones: (poll) updating with '+' flag <\\\" .. theFlag .. \\\"> in <\\\" .. theZone.name .. \\\"> by <\\\" .. adder .. \\\"> to <\\\" .. adder + currVal .. \\\">\\\", 30)\\\
        end\\\
        \\\
    elseif dcsCommon.stringStartsWith(method, \\\"-\\\") then \\\
        -- we subtract whatever is to the right \\\
        local remainder = dcsCommon.removePrefix(method, \\\"-\\\")\\\
        local adder = cfxZones.evalRemainder(remainder)\\\
        cfxZones.setFlagValue(theFlag, currVal-adder, theZone)\\\
\\\
    else \\\
        if method ~= \\\"on\\\" and method ~= \\\"f=1\\\" then \\\
            trigger.action.outText(\\\"+++zones: unknown method <\\\" .. method .. \\\"> - using 'on'\\\", 30)\\\
        end\\\
        -- default: on.\\\
--        trigger.action.setUserFlag(theFlag, 1)\\\
        cfxZones.setFlagValue(theFlag, 1, theZone)\\\
    end\\\
    \\\
    if cfxZones.verbose then\\\
        local newVal = cfxZones.getFlagValue(theFlag, theZone)\\\
        trigger.action.outText(\\\"+++zones: flag <\\\" .. theFlag .. \\\"> changed from \\\" .. currVal .. \\\" to \\\" .. newVal, 30)\\\
    end \\\
end\\\
\\\
function cfxZones.pollFlag(theFlag, method, theZone) \\\
    local allFlags = {}\\\
    if dcsCommon.containsString(theFlag, \\\",\\\") then \\\
        if cfxZones.verbose then \\\
            trigger.action.outText(\\\"+++zones: will poll flag set <\\\" .. theFlag .. \\\"> with \\\" .. method, 30)\\\
        end\\\
        allFlags = dcsCommon.splitString(theFlag, \\\",\\\")\\\
    else \\\
        table.insert(allFlags, theFlag)\\\
    end\\\
    \\\
    for idx, aFlag in pairs(allFlags) do \\\
        aFlag = dcsCommon.trim(aFlag)\\\
        -- note: mey require range preprocessing, but that's not\\\
        -- a priority \\\
        cfxZones.doPollFlag(aFlag, method, theZone)\\\
    end \\\
    \\\
end\\\
\\\
function cfxZones.expandFlagName(theFlag, theZone) \\\
    if not theFlag then return \\\"!NIL\\\" end \\\
    local zoneName = \\\"<dummy>\\\"\\\
    if theZone then \\\
        zoneName = theZone.name -- for flag wildcards\\\
    end\\\
    \\\
    if type(theFlag) == \\\"number\\\" then \\\
        -- straight number, return \\\
        return theFlag\\\
    end\\\
    \\\
    -- we assume it's a string now\\\
    theFlag = dcsCommon.trim(theFlag) -- clear leading/trailing spaces\\\
    local nFlag = tonumber(theFlag) \\\
    if nFlag then -- a number, legal\\\
        return theFlag\\\
    end\\\
        \\\
    -- now do wildcard processing. we have alphanumeric\\\
    if dcsCommon.stringStartsWith(theFlag, \\\"*\\\") then  \\\
        theFlag = zoneName .. theFlag\\\
    end\\\
    return theFlag\\\
end\\\
\\\
function cfxZones.setFlagValueMult(theFlag, theValue, theZone)\\\
    local allFlags = {}\\\
    if dcsCommon.containsString(theFlag, \\\",\\\") then \\\
        if cfxZones.verbose then \\\
            trigger.action.outText(\\\"+++zones: will multi-set flags <\\\" .. theFlag .. \\\"> to \\\" .. theValue, 30)\\\
        end\\\
        allFlags = dcsCommon.splitString(theFlag, \\\",\\\")\\\
    else \\\
        table.insert(allFlags, theFlag)\\\
    end\\\
    \\\
    for idx, aFlag in pairs(allFlags) do \\\
        aFlag = dcsCommon.trim(aFlag)\\\
        -- note: mey require range preprocessing, but that's not\\\
        -- a priority \\\
        cfxZones.setFlagValue(aFlag, theValue, theZone)\\\
    end \\\
end\\\
\\\
function cfxZones.setFlagValue(theFlag, theValue, theZone)\\\
    local zoneName = \\\"<dummy>\\\"\\\
    if not theZone then \\\
        trigger.action.outText(\\\"+++Zne: no zone on setFlagValue\\\", 30) -- mod me for detector\\\
    else \\\
        zoneName = theZone.name -- for flag wildcards\\\
    end\\\
    \\\
    if type(theFlag) == \\\"number\\\" then \\\
        -- straight set, ME flag \\\
        trigger.action.setUserFlag(theFlag, theValue)\\\
        return \\\
    end\\\
    \\\
    -- we assume it's a string now\\\
    theFlag = dcsCommon.trim(theFlag) -- clear leading/trailing spaces\\\
    local nFlag = tonumber(theFlag) \\\
    if nFlag then \\\
        trigger.action.setUserFlag(theFlag, theValue)\\\
        return \\\
    end\\\
    \\\
    -- some QoL: detect \\\"<none>\\\"\\\
    if dcsCommon.containsString(theFlag, \\\"<none>\\\") then \\\
        trigger.action.outText(\\\"+++Zone: warning - setFlag has '<none>' flag name in zone <\\\" .. zoneName .. \\\">\\\", 30) -- if error, intended break\\\
    end\\\
    \\\
    -- now do wildcard processing. we have alphanumeric\\\
    if dcsCommon.stringStartsWith(theFlag, \\\"*\\\") then  \\\
        theFlag = zoneName .. theFlag\\\
    end\\\
    trigger.action.setUserFlag(theFlag, theValue)\\\
end \\\
\\\
function cfxZones.getFlagValue(theFlag, theZone)\\\
    local zoneName = \\\"<dummy>\\\"\\\
    if not theZone or not theZone.name then \\\
        trigger.action.outText(\\\"+++Zne: no zone or zone name on getFlagValue\\\", 30)\\\
    else \\\
        zoneName = theZone.name -- for flag wildcards\\\
    end\\\
    \\\
    if type(theFlag) == \\\"number\\\" then \\\
        -- straight get, ME flag \\\
        return tonumber(trigger.misc.getUserFlag(theFlag))\\\
    end\\\
    \\\
    -- we assume it's a string now\\\
    theFlag = dcsCommon.trim(theFlag) -- clear leading/trailing spaces\\\
    local nFlag = tonumber(theFlag) \\\
    if nFlag then \\\
        return tonumber(trigger.misc.getUserFlag(theFlag))\\\
    end\\\
    \\\
    -- some QoL: detect \\\"<none>\\\"\\\
    if dcsCommon.containsString(theFlag, \\\"<none>\\\") then \\\
        trigger.action.outText(\\\"+++Zone: warning - getFlag has '<none>' flag name in zone <\\\" .. zoneName .. \\\">\\\", 30) -- break here\\\
    end\\\
    \\\
    -- now do wildcard processing. we have alphanumeric\\\
    if dcsCommon.stringStartsWith(theFlag, \\\"*\\\") then  \\\
            theFlag = zoneName .. theFlag\\\
    end\\\
    return tonumber(trigger.misc.getUserFlag(theFlag))\\\
end\\\
\\\
function cfxZones.isMEFlag(inFlag)\\\
    -- do NOT use me\\\
    trigger.action.outText(\\\"+++zne: warning: deprecated isMEFlag\\\", 30)\\\
    return true \\\
    -- returns true if inFlag is a pure positive number\\\
end\\\
\\\
function cfxZones.verifyMethod(theMethod, theZone)\\\
    local lMethod = string.lower(theMethod)\\\
    if lMethod == \\\"#\\\" or lMethod == \\\"change\\\" then \\\
        return true\\\
    end\\\
\\\
    if lMethod == \\\"0\\\" or lMethod == \\\"no\\\" or lMethod == \\\"false\\\" \\\
       or lMethod == \\\"off\\\" then \\\
        return true  \\\
    end\\\
    \\\
    if lMethod == \\\"1\\\" or lMethod == \\\"yes\\\" or lMethod == \\\"true\\\" \\\
       or lMethod == \\\"on\\\" then \\\
        return true  \\\
    end\\\
    \\\
    if lMethod == \\\"inc\\\" or lMethod == \\\"+1\\\" then \\\
        return true\\\
    end\\\
    \\\
    if lMethod == \\\"dec\\\" or lMethod == \\\"-1\\\" then \\\
        return true \\\
    end \\\
    \\\
    if lMethod == \\\"lohi\\\" or lMethod == \\\"pulse\\\" then \\\
        return true\\\
    end\\\
    \\\
    if lMethod == \\\"hilo\\\" then \\\
        return true\\\
    end\\\
    \\\
    -- number constraints\\\
    -- or flag constraints     -- ONLY RETURN TRUE IF CHANGE AND CONSTRAINT MET \\\
    local op = string.sub(theMethod, 1, 1) \\\
    local remainder = string.sub(theMethod, 2)\\\
    remainder = dcsCommon.trim(remainder) -- remove all leading and trailing spaces\\\
\\\
    if true then \\\
        -- we have a comparison = \\\">\\\", \\\"=\\\", \\\"<\\\" followed by a number \\\
        -- THEY TRIGGER EACH TIME lastVal <> currVal AND condition IS MET  \\\
        if op == \\\"=\\\" then \\\
            return true\\\
        end\\\
        \\\
        if op == \\\"#\\\" or op == \\\"~\\\" then \\\
            return true\\\
        end \\\
        \\\
        if op == \\\"<\\\" then \\\
            return true\\\
        end\\\
        \\\
        if op == \\\">\\\" then \\\
            return true\\\
        end\\\
    end\\\
    \\\
    return false \\\
end\\\
\\\
-- method-based flag testing \\\
function cfxZones.evalFlagMethodImmediate(currVal, theMethod, theZone)\\\
    -- immediate eval - does not look at last val. \\\
    -- return true/false/value based on theMethod's contraints \\\
    -- simple constraints\\\
    local lMethod = string.lower(theMethod)\\\
    if lMethod == \\\"#\\\" or lMethod == \\\"change\\\" then \\\
        -- ALWAYS RETURNS TRUE for currval <> 0, flase if currval = 0\\\
        return currVal ~= 0  \\\
    end\\\
    \\\
    if lMethod == \\\"0\\\" or lMethod == \\\"no\\\" or lMethod == \\\"false\\\" \\\
       or lMethod == \\\"off\\\" then \\\
        -- WARNING: ALWAYS RETURNS FALSE\\\
        return false  \\\
    end\\\
    \\\
    if lMethod == \\\"1\\\" or lMethod == \\\"yes\\\" or lMethod == \\\"true\\\" \\\
       or lMethod == \\\"on\\\" then \\\
        -- WARNING: ALWAYS RETURNS TRUE\\\
        return true  \\\
    end\\\
    \\\
    if lMethod == \\\"inc\\\" or lMethod == \\\"+1\\\" then \\\
        return currVal+1 -- this may be unexpected\\\
    end\\\
    \\\
    if lMethod == \\\"dec\\\" or lMethod == \\\"-1\\\" then \\\
        return currVal-1 -- this may be unexpectd\\\
    end \\\
    \\\
    -- number constraints\\\
    -- or flag constraints \\\
    -- ONLY RETURN TRUE IF CHANGE AND CONSTRAINT MET \\\
    local op = string.sub(theMethod, 1, 1) \\\
    local remainder = string.sub(theMethod, 2)\\\
    remainder = dcsCommon.trim(remainder) -- remove all leading and trailing spaces\\\
    local rNum = tonumber(remainder)\\\
    if not rNum then \\\
        -- we use remainder as name for flag \\\
        -- PROCESS ESCAPE SEQUENCES\\\
        local esc = string.sub(remainder, 1, 1)\\\
        local last = string.sub(remainder, -1)\\\
        if esc == \\\"@\\\" then \\\
            remainder = string.sub(remainder, 2)\\\
            remainder = dcsCommon.trim(remainder)\\\
        end\\\
        \\\
        if esc == \\\"(\\\" and last == \\\")\\\" and string.len(remainder) > 2 then \\\
            -- note: iisues with startswith(\\\"(\\\") ???\\\
            remainder = string.sub(remainder, 2, -2)\\\
            remainder = dcsCommon.trim(remainder)        \\\
        end\\\
        if esc == \\\"\\\\\\\"\\\" and last == \\\"\\\\\\\"\\\" and string.len(remainder) > 2 then \\\
            remainder = string.sub(remainder, 2, -2)\\\
            remainder = dcsCommon.trim(remainder)        \\\
        end\\\
        if cfxZones.verbose then \\\
            trigger.action.outText(\\\"+++zne: accessing flag <\\\" .. remainder .. \\\">\\\", 30)\\\
        end \\\
        rNum = cfxZones.getFlagValue(remainder, theZone)\\\
    end \\\
    if rNum then \\\
        -- we have a comparison = \\\">\\\", \\\"=\\\", \\\"<\\\" followed by a number  \\\
        if op == \\\"=\\\" then \\\
            return currVal == rNum\\\
        end\\\
        \\\
        if op == \\\"#\\\" or op == \\\"~\\\" then \\\
            return currVal ~= rNum \\\
        end \\\
        \\\
        if op == \\\"<\\\" then \\\
            return currVal < rNum\\\
        end\\\
        \\\
        if op == \\\">\\\" then \\\
            return currVal > rNum\\\
        end\\\
    end\\\
    \\\
    -- if we get here, we have an error \\\
    local zoneName = \\\"<NIL>\\\"\\\
    if theZone then zoneName = theZone.name end \\\
    trigger.action.outText(\\\"+++Zne: illegal |\\\" .. theMethod .. \\\"| in eval for zone \\\" .. zoneName, 30 )\\\
    return false     \\\
end\\\
\\\
function cfxZones.testFlagByMethodForZone(currVal, lastVal, theMethod, theZone)\\\
    -- return true/false based on theMethod's contraints \\\
    -- simple constraints\\\
    -- ONLY RETURN TRUE IF CHANGE AND CONSTRAINT MET \\\
    local lMethod = string.lower(theMethod)\\\
    if lMethod == \\\"#\\\" or lMethod == \\\"change\\\" then \\\
        -- check if currVal different from lastVal\\\
        return currVal ~= lastVal  \\\
    end\\\
    \\\
    if lMethod == \\\"0\\\" or lMethod == \\\"no\\\" or lMethod == \\\"false\\\" \\\
       or lMethod == \\\"off\\\" then \\\
        -- WARNING: ONLY RETURNS TRUE IF FALSE AND lastval not zero!\\\
        return currVal == 0 and currVal ~= lastVal  \\\
    end\\\
    \\\
    if lMethod == \\\"1\\\" or lMethod == \\\"yes\\\" or lMethod == \\\"true\\\" \\\
       or lMethod == \\\"on\\\" then \\\
        -- WARNING: only returns true if lastval was false!!!!\\\
        return (currVal ~= 0 and lastVal == 0)  \\\
    end\\\
    \\\
    if lMethod == \\\"inc\\\" or lMethod == \\\"+1\\\" then \\\
--        return currVal == lastVal+1 -- better: test for greater than \\\
        return currVal > lastVal\\\
    end\\\
    \\\
    if lMethod == \\\"dec\\\" or lMethod == \\\"-1\\\" then \\\
        --return currVal == lastVal-1\\\
        return currVal < lastVal \\\
    end \\\
    \\\
    if lMethod == \\\"lohi\\\" or lMethod == \\\"pulse\\\" then \\\
        return (lastVal <= 0 and currVal > 0)\\\
    end\\\
    \\\
    if lMethod == \\\"hilo\\\" then \\\
        return (lastVal > 0 and currVal <= 0)\\\
    end\\\
    \\\
    -- number constraints\\\
    -- or flag constraints \\\
    -- ONLY RETURN TRUE IF CHANGE AND CONSTRAINT MET \\\
    local op = string.sub(theMethod, 1, 1) \\\
    local remainder = string.sub(theMethod, 2)\\\
    remainder = dcsCommon.trim(remainder) -- remove all leading and trailing spaces\\\
    local rNum = tonumber(remainder)\\\
    if not rNum then \\\
        -- we use remainder as name for flag \\\
        -- PROCESS ESCAPE SEQUENCES\\\
        local esc = string.sub(remainder, 1, 1)\\\
        local last = string.sub(remainder, -1)\\\
        if esc == \\\"@\\\" then \\\
            remainder = string.sub(remainder, 2)\\\
            remainder = dcsCommon.trim(remainder)\\\
        end\\\
        \\\
        if esc == \\\"(\\\" and last == \\\")\\\" and string.len(remainder) > 2 then \\\
            -- note: iisues with startswith(\\\"(\\\") ???\\\
            remainder = string.sub(remainder, 2, -2)\\\
            remainder = dcsCommon.trim(remainder)        \\\
        end\\\
        if esc == \\\"\\\\\\\"\\\" and last == \\\"\\\\\\\"\\\" and string.len(remainder) > 2 then \\\
            remainder = string.sub(remainder, 2, -2)\\\
            remainder = dcsCommon.trim(remainder)        \\\
        end\\\
        if cfxZones.verbose then \\\
            trigger.action.outText(\\\"+++zne: accessing flag <\\\" .. remainder .. \\\">\\\", 30)\\\
        end \\\
        rNum = cfxZones.getFlagValue(remainder, theZone)\\\
    end \\\
    if rNum then \\\
        -- we have a comparison = \\\">\\\", \\\"=\\\", \\\"<\\\" followed by a number \\\
        -- THEY TRIGGER EACH TIME lastVal <> currVal AND condition IS MET  \\\
        if op == \\\"=\\\" then \\\
            return currVal == rNum and lastVal ~= currVal\\\
        end\\\
        \\\
        if op == \\\"#\\\" or op == \\\"~\\\" then \\\
            return currVal ~= rNum and lastVal ~= currVal \\\
        end \\\
        \\\
        if op == \\\"<\\\" then \\\
            return currVal < rNum and lastVal ~= currVal\\\
        end\\\
        \\\
        if op == \\\">\\\" then \\\
            return currVal > rNum and lastVal ~= currVal\\\
        end\\\
    end\\\
    \\\
    -- if we get here, we have an error \\\
    local zoneName = \\\"<NIL>\\\"\\\
    if theZone then zoneName = theZone.name end \\\
    trigger.action.outText(\\\"+++Zne: illegal method constraints |\\\" .. theMethod .. \\\"| for zone \\\" .. zoneName, 30 )\\\
    return false \\\
end\\\
\\\
\\\
function cfxZones.testZoneFlag(theZone, theFlagName, theMethod, latchName)\\\
    -- returns two values: true/false method result, and curr value\\\
    -- returns true if method constraints are met for flag theFlagName\\\
    -- as defined by theMethod \\\
    if not theMethod then \\\
        theMethod = \\\"change\\\"\\\
    end \\\
    \\\
    -- will read and update theZone[latchName] as appropriate \\\
    if not theZone then \\\
        trigger.action.outText(\\\"+++Zne: no zone for testZoneFlag\\\", 30)\\\
        return nil, nil \\\
    end \\\
    if not theFlagName then \\\
        -- this is common, no error, only on verbose \\\
        if cfxZones.verbose then \\\
            trigger.action.outText(\\\"+++Zne: no flagName for zone \\\" .. theZone.name .. \\\" for testZoneFlag\\\", 30)\\\
        end \\\
        return nil, nil\\\
    end\\\
    if not latchName then \\\
        trigger.action.outText(\\\"+++Zne: no latchName for zone \\\" .. theZone.name .. \\\" for testZoneFlag\\\", 30)\\\
        return nil, nil \\\
    end\\\
    -- get current value \\\
    local currVal = cfxZones.getFlagValue(theFlagName, theZone)\\\
    \\\
    -- get last value from latch\\\
    local lastVal = theZone[latchName]\\\
    if not lastVal then \\\
        trigger.action.outText(\\\"+++Zne: latch <\\\" .. latchName .. \\\"> not valid for zone \\\" .. theZone.name, 30) -- intentional break here \\\
        return nil, nil\\\
    end\\\
    \\\
    -- now, test by method \\\
    -- we should only test if currVal <> lastVal \\\
    if currVal == lastVal then\\\
        return false, currVal\\\
    end \\\
    \\\
    --trigger.action.outText(\\\"+++Zne: about to test: c = \\\" .. currVal .. \\\", l = \\\" .. lastVal, 30)\\\
    local testResult = cfxZones.testFlagByMethodForZone(currVal, lastVal, theMethod, theZone)\\\
\\\
    -- update latch by method\\\
    theZone[latchName] = currVal \\\
\\\
    -- return result\\\
    return testResult, currVal\\\
end\\\
\\\
\\\
\\\
function cfxZones.flagArrayFromString(inString)\\\
-- original code from RND flag\\\
    if string.len(inString) < 1 then \\\
        trigger.action.outText(\\\"+++zne: empty flags\\\", 30)\\\
        return {} \\\
    end\\\
    if cfxZones.verbose then \\\
        trigger.action.outText(\\\"+++zne: processing <\\\" .. inString .. \\\">\\\", 30)\\\
    end \\\
    \\\
    local flags = {}\\\
    local rawElements = dcsCommon.splitString(inString, \\\",\\\")\\\
    -- go over all elements \\\
    for idx, anElement in pairs(rawElements) do \\\
        anElement = dcsCommon.trim(anElement)\\\
        if dcsCommon.stringStartsWithDigit(anElement) and dcsCommon.containsString(anElement, \\\"-\\\") then \\\
            -- interpret this as a range\\\
            local theRange = dcsCommon.splitString(anElement, \\\"-\\\")\\\
            local lowerBound = theRange[1]\\\
            lowerBound = tonumber(lowerBound)\\\
            local upperBound = theRange[2]\\\
            upperBound = tonumber(upperBound)\\\
            if lowerBound and upperBound then\\\
                -- swap if wrong order\\\
                if lowerBound > upperBound then \\\
                    local temp = upperBound\\\
                    upperBound = lowerBound\\\
                    lowerBound = temp \\\
                end\\\
                -- now add add numbers to flags\\\
                for f=lowerBound, upperBound do \\\
                    table.insert(flags, tostring(f))\\\
                end\\\
            else\\\
                -- bounds illegal\\\
                trigger.action.outText(\\\"+++zne: ignored range <\\\" .. anElement .. \\\"> (range)\\\", 30)\\\
            end\\\
        else\\\
            -- single number\\\
            f = dcsCommon.trim(anElement) -- DML flag upgrade: accept strings tonumber(anElement)\\\
            if f then \\\
                table.insert(flags, f)\\\
\\\
            else \\\
                trigger.action.outText(\\\"+++zne: ignored element <\\\" .. anElement .. \\\"> (single)\\\", 30)\\\
            end\\\
        end\\\
    end\\\
    if cfxZones.verbose then \\\
        trigger.action.outText(\\\"+++zne: <\\\" .. #flags .. \\\"> flags total\\\", 30)\\\
    end \\\
    return flags\\\
end\\\
\\\
--\\\
-- ===================\\\
-- PROPERTY PROCESSING\\\
-- =================== \\\
--\\\
\\\
function cfxZones.getAllZoneProperties(theZone, caseInsensitive) -- return as dict \\\
    if not caseInsensitive then caseInsensitive = false end \\\
    if not theZone then return {} end \\\
    \\\
    local dcsProps = theZone.properties -- zone properties in dcs format \\\
    local props = {}\\\
    -- dcs has all properties as array with values .key and .value \\\
    -- so convert them into a dictionary \\\
    for i=1, #dcsProps do \\\
        local theProp = dcsProps[i]\\\
        local theKey = \\\"dummy\\\"\\\
        if string.len(theProp.key) > 0 then theKey = theProp.key end \\\
        if caseInsensitive then theKey = theKey:upper() end \\\
        props[theKey] = theProp.value\\\
    end\\\
    return props \\\
end\\\
\\\
function cfxZones.extractPropertyFromDCS(theKey, theProperties)\\\
-- trim\\\
    theKey = dcsCommon.trim(theKey) \\\
--    make lower case conversion if not case sensitive\\\
    if not cfxZones.caseSensitiveProperties then \\\
        theKey = string.lower(theKey)\\\
    end\\\
\\\
-- iterate all keys and compare to what we are looking for     \\\
    for i=1, #theProperties do\\\
        local theP = theProperties[i]\\\
         \\\
        local existingKey = dcsCommon.trim(theP.key)  \\\
        if not cfxZones.caseSensitiveProperties then \\\
            existingKey = string.lower(existingKey)\\\
        end\\\
        if existingKey == theKey then \\\
            return theP.value\\\
        end\\\
        \\\
        -- now check after removing all blanks \\\
        existingKey = dcsCommon.removeBlanks(existingKey)\\\
        if existingKey == theKey then \\\
            return theP.value\\\
        end\\\
    end\\\
    return nil \\\
end\\\
\\\
function cfxZones.getZoneProperty(cZone, theKey)\\\
    if not cZone then \\\
        trigger.action.outText(\\\"+++zone: no zone in getZoneProperty\\\", 30)\\\
--        breek.here.noew = 1\\\
        return nil\\\
    end \\\
    if not theKey then \\\
        trigger.action.outText(\\\"+++zone: no property key in getZoneProperty for zone \\\" .. cZone.name, 30)\\\
--        breakme.here = 1\\\
        return \\\
    end    \\\
\\\
    local props = cZone.properties\\\
    local theVal = cfxZones.extractPropertyFromDCS(theKey, props)\\\
    return theVal\\\
end\\\
\\\
function cfxZones.getStringFromZoneProperty(theZone, theProperty, default)\\\
    \\\
    if not default then default = \\\"\\\" end\\\
    local p = cfxZones.getZoneProperty(theZone, theProperty)\\\
    if not p then return default end\\\
    if type(p) == \\\"string\\\" then \\\
        p = dcsCommon.trim(p)\\\
        if p == \\\"\\\" then p = default end \\\
        return p\\\
    end\\\
    return default -- warning. what if it was a number first?\\\
end\\\
\\\
function cfxZones.getMinMaxFromZoneProperty(theZone, theProperty)\\\
    local p = cfxZones.getZoneProperty(theZone, theProperty)\\\
    local theNumbers = dcsCommon.splitString(p, \\\" \\\")\\\
\\\
    return tonumber(theNumbers[1]), tonumber(theNumbers[2])\\\
    \\\
end\\\
\\\
function cfxZones.randomInRange(minVal, maxVal)\\\
    if maxVal < minVal then \\\
        local t = minVal\\\
        minVal = maxVal \\\
        maxVal = t\\\
    end\\\
    return cfxZones.randomDelayFromPositiveRange(minVal, maxVal)\\\
end\\\
\\\
function cfxZones.randomDelayFromPositiveRange(minVal, maxVal) \\\
    if not maxVal then return minVal end \\\
    if not minVal then return maxVal end \\\
    local delay = maxVal\\\
    if minVal > 0 and minVal < delay then \\\
        -- we want a randomized from time from minTime .. delay\\\
        local varPart = delay - minVal + 1\\\
        varPart = dcsCommon.smallRandom(varPart) - 1\\\
        delay = minVal + varPart\\\
    end\\\
    return delay \\\
end\\\
\\\
function cfxZones.getPositiveRangeFromZoneProperty(theZone, theProperty, default, defaultmax)\\\
    -- reads property as string, and interprets as range 'a-b'. \\\
    -- if not a range but single number, returns both for upper and lower \\\
    --trigger.action.outText(\\\"***Zne: enter with <\\\" .. theZone.name .. \\\">: range for property <\\\" .. theProperty .. \\\">!\\\", 30)\\\
    if not default then default = 0 end \\\
    if not defaultmax then defaultmax = default end \\\
    \\\
    local lowerBound = default\\\
    local upperBound = defaultmax \\\
    \\\
    local rangeString = cfxZones.getStringFromZoneProperty(theZone, theProperty, \\\"\\\")\\\
    if dcsCommon.containsString(rangeString, \\\"-\\\") then \\\
        local theRange = dcsCommon.splitString(rangeString, \\\"-\\\")\\\
        lowerBound = theRange[1]\\\
        lowerBound = tonumber(lowerBound)\\\
        upperBound = theRange[2]\\\
        upperBound = tonumber(upperBound)\\\
        if lowerBound and upperBound then\\\
            -- swap if wrong order\\\
            if lowerBound > upperBound then \\\
                local temp = upperBound\\\
                upperBound = lowerBound\\\
                lowerBound = temp \\\
            end\\\
\\\
        else\\\
            -- bounds illegal\\\
            trigger.action.outText(\\\"+++Zne: illegal range  <\\\" .. rangeString .. \\\">, using \\\" .. default .. \\\"-\\\" .. defaultmax, 30)\\\
            lowerBound = default\\\
            upperBound = defaultmax \\\
        end\\\
    else \\\
        upperBound = cfxZones.getNumberFromZoneProperty(theZone, theProperty, defaultmax) -- between pulses \\\
        lowerBound = upperBound\\\
    end\\\
\\\
    return lowerBound, upperBound\\\
end\\\
\\\
function cfxZones.hasProperty(theZone, theProperty) \\\
    if not theProperty then \\\
        trigger.action.outText(\\\"+++zne: WARNING - hasProperty called with nil theProperty for zone <\\\" .. theZone.name .. \\\">\\\", 30)\\\
        return false \\\
    end \\\
    local foundIt = cfxZones.getZoneProperty(theZone, theProperty)\\\
    if not foundIt then \\\
        -- check for possible forgotten or exchanged IO flags \\\
        if string.sub(theProperty, -1) == \\\"?\\\" then\\\
            local lessOp = theProperty:sub(1,-2)\\\
            if cfxZones.getZoneProperty(theZone, lessOp) ~= nil then \\\
                trigger.action.outText(\\\"*** NOTE: \\\" .. theZone.name .. \\\"'s property <\\\" .. lessOp .. \\\"> may be missing a Query ('?') symbol\\\", 30)\\\
            end\\\
            local lessPlus = lessOp .. \\\"!\\\"\\\
            if cfxZones.getZoneProperty(theZone, lessPlus) ~= nil then \\\
                trigger.action.outText(\\\"*** NOTE: \\\" .. theZone.name .. \\\"'s property <\\\" .. lessOp .. \\\"> may be using '!' instead of '?' for input\\\", 30)\\\
            end\\\
            return false \\\
        end\\\
        \\\
        if string.sub(theProperty, -1) == \\\"!\\\" then \\\
            local lessOp = theProperty:sub(1,-2)\\\
            if cfxZones.getZoneProperty(theZone, lessOp) ~= nil then \\\
                trigger.action.outText(\\\"*** NOTE: \\\" .. theZone.name .. \\\"'s property <\\\" .. lessOp .. \\\"> may be missing a Bang! ('!') symbol\\\", 30)\\\
            end\\\
            local lessPlus = lessOp .. \\\"?\\\"\\\
            if cfxZones.getZoneProperty(theZone, lessPlus) ~= nil then \\\
                trigger.action.outText(\\\"*** NOTE: \\\" .. theZone.name .. \\\"'s property <\\\" .. lessOp .. \\\"> may be using '!' instead of '?' for input\\\", 30)\\\
            end\\\
            return false \\\
        end\\\
        \\\
        if string.sub(theProperty, -1) == \\\":\\\" then \\\
            local lessOp = theProperty:sub(1,-2)\\\
            if cfxZones.getZoneProperty(theZone, lessOp) ~= nil then \\\
                trigger.action.outText(\\\"*** NOTE: \\\" .. theZone.name .. \\\"'s property <\\\" .. lessOp .. \\\"> may be missing a colon (':') at end\\\", 30)\\\
            end\\\
            return false \\\
        end\\\
        \\\
        return false \\\
    end\\\
    return true \\\
--    return foundIt ~= nil \\\
end\\\
\\\
function cfxZones.getBoolFromZoneProperty(theZone, theProperty, defaultVal)\\\
    if not defaultVal then defaultVal = false end \\\
    if type(defaultVal) ~= \\\"boolean\\\" then \\\
        defaultVal = false \\\
    end\\\
\\\
    if not theZone then \\\
        trigger.action.outText(\\\"WARNING: NIL Zone in getBoolFromZoneProperty\\\", 30)\\\
        return defaultVal\\\
    end\\\
\\\
\\\
    local p = cfxZones.getZoneProperty(theZone, theProperty)\\\
    if not p then return defaultVal end\\\
\\\
    -- make sure we compare so default always works when \\\
    -- answer isn't exactly the opposite\\\
    p = p:lower() \\\
    p = dcsCommon.trim(p) \\\
    if defaultVal == false then \\\
        -- only go true if exact match to yes or true \\\
        theBool = false \\\
        theBool = (p == 'true') or (p == 'yes') or p == \\\"1\\\"\\\
        return theBool\\\
    end\\\
    \\\
    local theBool = true \\\
    -- only go false if exactly no or false or \\\"0\\\"\\\
    theBool = (p ~= 'false') and (p ~= 'no') and (p ~= \\\"0\\\") \\\
    return theBool\\\
end\\\
\\\
function cfxZones.getCoalitionFromZoneProperty(theZone, theProperty, default)\\\
    if not default then default = 0 end\\\
    local p = cfxZones.getZoneProperty(theZone, theProperty)\\\
    if not p then return default end  \\\
    if type(p) == \\\"number\\\" then -- can't currently really happen\\\
        if p == 1 then return 1 end \\\
        if p == 2 then return 2 end \\\
        return 0\\\
    end\\\
    \\\
    if type(p) == \\\"string\\\" then \\\
        if p == \\\"1\\\" then return 1 end \\\
        if p == \\\"2\\\" then return 2 end \\\
        if p == \\\"0\\\" then return 0 end \\\
        \\\
        p = p:lower()\\\
        \\\
        if p == \\\"red\\\" then return 1 end \\\
        if p == \\\"blue\\\" then return 2 end \\\
        if p == \\\"neutral\\\" then return 0 end\\\
        if p == \\\"all\\\" then return 0 end \\\
        return default \\\
    end\\\
    \\\
    return default \\\
end\\\
\\\
function cfxZones.getNumberFromZoneProperty(theZone, theProperty, default)\\\
--TODO: trim string \\\
    if not default then default = 0 end\\\
    local p = cfxZones.getZoneProperty(theZone, theProperty)\\\
    p = tonumber(p)\\\
    if not p then return default else return p end\\\
end\\\
\\\
function cfxZones.getVectorFromZoneProperty(theZone, theProperty, minDims, defaultVal)\\\
    if not minDims then minDims = 0 end \\\
    if not defaultVal then defaultVal = 0 end \\\
    local s = cfxZones.getStringFromZoneProperty(theZone, theProperty, \\\"\\\")\\\
    local sVec = dcsCommon.splitString(s, \\\",\\\")\\\
    local nVec = {}\\\
    for idx, numString in pairs (sVec) do \\\
        local n = tonumber(numString)\\\
        if not n then n = defaultVal end\\\
        table.insert(nVec, n)\\\
    end\\\
    -- make sure vector contains at least minDims values \\\
    while #nVec < minDims do \\\
        table.insert(nVec, defaultVal)\\\
    end\\\
    \\\
    return nVec \\\
end\\\
\\\
function cfxZones.getSmokeColorStringFromZoneProperty(theZone, theProperty, default) -- smoke as 'red', 'green', or 1..5\\\
    if not default then default = \\\"red\\\" end \\\
    local s = cfxZones.getStringFromZoneProperty(theZone, theProperty, default)\\\
    s = s:lower()\\\
    s = dcsCommon.trim(s)\\\
    -- check numbers \\\
    if (s == \\\"0\\\") then return \\\"green\\\" end\\\
    if (s == \\\"1\\\") then return \\\"red\\\" end\\\
    if (s == \\\"2\\\") then return \\\"white\\\" end\\\
    if (s == \\\"3\\\") then return \\\"orange\\\" end\\\
    if (s == \\\"4\\\") then return \\\"blue\\\" end\\\
    \\\
    if s == \\\"green\\\" or\\\
       s == \\\"red\\\" or\\\
       s == \\\"white\\\" or\\\
       s == \\\"orange\\\" or\\\
       s == \\\"blue\\\" then return s end\\\
\\\
    return default \\\
end\\\
\\\
function cfxZones.getFlareColorStringFromZoneProperty(theZone, theProperty, default) -- smoke as 'red', 'green', or 1..5\\\
    if not default then default = \\\"red\\\" end \\\
    local s = cfxZones.getStringFromZoneProperty(theZone, theProperty, default)\\\
    s = s:lower()\\\
    s = dcsCommon.trim(s)\\\
    -- check numbers \\\
    if (s == \\\"rnd\\\") then return \\\"random\\\" end \\\
    if (s == \\\"0\\\") then return \\\"green\\\" end\\\
    if (s == \\\"1\\\") then return \\\"red\\\" end\\\
    if (s == \\\"2\\\") then return \\\"white\\\" end\\\
    if (s == \\\"3\\\") then return \\\"yellow\\\" end\\\
    if (s == \\\"-1\\\") then return \\\"random\\\" end  \\\
    \\\
    if s == \\\"green\\\" or\\\
       s == \\\"red\\\" or\\\
       s == \\\"white\\\" or\\\
       s == \\\"yellow\\\" or \\\
       s == \\\"random\\\" then\\\
    return s end\\\
\\\
    return default \\\
end\\\
\\\
\\\
--\\\
-- Zone-based wildcard processing\\\
-- \\\
\\\
-- process <z>\\\
function cfxZones.processZoneStatics(inMsg, theZone)\\\
    if theZone then \\\
        inMsg = inMsg:gsub(\\\"<z>\\\", theZone.name)\\\
    end\\\
    return inMsg \\\
end\\\
\\\
-- process <t>, <lat>, <lon>, <ele>, <mgrs> \\\
function cfxZones.processSimpleZoneDynamics(inMsg, theZone, timeFormat, imperialUnits)\\\
    if not inMsg then return \\\"<nil inMsg>\\\" end\\\
    -- replace <t> with current mission time HMS\\\
    local absSecs = timer.getAbsTime()-- + env.mission.start_time\\\
    while absSecs > 86400 do \\\
        absSecs = absSecs - 86400 -- subtract out all days \\\
    end\\\
    if not timeFormat then timeFormat = \\\"<:h>:<:m>:<:s>\\\" end \\\
    local timeString  = dcsCommon.processHMS(timeFormat, absSecs)\\\
    local outMsg = inMsg:gsub(\\\"<t>\\\", timeString)\\\
    \\\
    -- replace <lat> with lat of zone point and <lon> with lon of zone point \\\
    -- and <mgrs> with mgrs coords of zone point \\\
    local currPoint = cfxZones.getPoint(theZone)\\\
    local lat, lon = coord.LOtoLL(currPoint)\\\
    lat, lon = dcsCommon.latLon2Text(lat, lon)\\\
    local alt = land.getHeight({x = currPoint.x, y = currPoint.z})\\\
    if imperialUnits then \\\
        alt = math.floor(alt * 3.28084) -- feet \\\
    else \\\
        alt = math.floor(alt) -- meters \\\
    end \\\
    outMsg = outMsg:gsub(\\\"<lat>\\\", lat)\\\
    outMsg = outMsg:gsub(\\\"<lon>\\\", lon)\\\
    outMsg = outMsg:gsub(\\\"<ele>\\\", alt)\\\
    local grid = coord.LLtoMGRS(coord.LOtoLL(currPoint))\\\
    local mgrs = grid.UTMZone .. ' ' .. grid.MGRSDigraph .. ' ' .. grid.Easting .. ' ' .. grid.Northing\\\
    outMsg = outMsg:gsub(\\\"<mgrs>\\\", mgrs)\\\
    return outMsg\\\
end \\\
\\\
-- process <v: flag>, <rsp: flag> <rrnd>\\\
function cfxZones.processDynamicValues(inMsg, theZone, msgResponses)\\\
    -- replace all occurences of <v: flagName> with their values \\\
    local pattern = \\\"<v:%s*[%s%w%*%d%.%-_]+>\\\" -- no list allowed but blanks and * and . and - and _ --> we fail on the other specials to keep this simple \\\
    local outMsg = inMsg\\\
    repeat -- iterate all patterns one by one \\\
        local startLoc, endLoc = string.find(outMsg, pattern)\\\
        if startLoc then \\\
            local theValParam = string.sub(outMsg, startLoc, endLoc)\\\
            -- strip lead and trailer \\\
            local param = string.gsub(theValParam, \\\"<v:%s*\\\", \\\"\\\")\\\
            param = string.gsub(param, \\\">\\\",\\\"\\\")\\\
            -- param = dcsCommon.trim(param) -- trim is called anyway\\\
            -- access flag\\\
            local val = cfxZones.getFlagValue(param, theZone)\\\
            val = tostring(val)\\\
            if not val then val = \\\"NULL\\\" end \\\
            -- replace pattern in original with new val \\\
            outMsg = string.gsub(outMsg, pattern, val, 1) -- only one sub!\\\
        end\\\
    until not startLoc\\\
    \\\
    -- now process rsp \\\
    pattern = \\\"<rsp:%s*[%s%w%*%d%.%-_]+>\\\" -- no list allowed but blanks and * and . and - and _ --> we fail on the other specials to keep this simple \\\
\\\
    if msgResponses and (#msgResponses > 0) then -- only if this zone has an array\\\
        --trigger.action.outText(\\\"enter response proccing\\\", 30)\\\
        repeat -- iterate all patterns one by one \\\
            local startLoc, endLoc = string.find(outMsg, pattern)\\\
            if startLoc then \\\
                --trigger.action.outText(\\\"response: found an occurence\\\", 30)\\\
                local theValParam = string.sub(outMsg, startLoc, endLoc)\\\
                -- strip lead and trailer \\\
                local param = string.gsub(theValParam, \\\"<rsp:%s*\\\", \\\"\\\")\\\
                param = string.gsub(param, \\\">\\\",\\\"\\\")\\\
                \\\
                -- access flag\\\
                local val = cfxZones.getFlagValue(param, theZone)\\\
                if not val or (val < 1) then val = 1 end \\\
                if val > msgResponses then val = msgResponses end \\\
                \\\
                val = msgResponses[val]\\\
                val = dcsCommon.trim(val)\\\
                -- replace pattern in original with new val \\\
                outMsg = string.gsub(outMsg, pattern, val, 1) -- only one sub!\\\
            end\\\
        until not startLoc\\\
        \\\
        -- rnd response \\\
        local rndRsp = dcsCommon.pickRandom(msgResponses)\\\
        outMsg = outMsg:gsub (\\\"<rrnd>\\\", rndRsp)\\\
    end\\\
    \\\
    return outMsg\\\
end\\\
\\\
-- process <t: flag>\\\
function cfxZones.processDynamicTime(inMsg, theZone, timeFormat)\\\
    if not timeFormat then timeFormat = \\\"<:h>:<:m>:<:s>\\\" end\\\
    -- replace all occurences of <t: flagName> with their values \\\
    local pattern = \\\"<t:%s*[%s%w%*%d%.%-_]+>\\\" -- no list allowed but blanks and * and . and - and _ --> we fail on the other specials to keep this simple \\\
    local outMsg = inMsg\\\
    repeat -- iterate all patterns one by one \\\
        local startLoc, endLoc = string.find(outMsg, pattern)\\\
        if startLoc then \\\
            local theValParam = string.sub(outMsg, startLoc, endLoc)\\\
            -- strip lead and trailer \\\
            local param = string.gsub(theValParam, \\\"<t:%s*\\\", \\\"\\\")\\\
            param = string.gsub(param, \\\">\\\",\\\"\\\")\\\
            -- access flag\\\
            local val = cfxZones.getFlagValue(param, theZone)\\\
            -- use this to process as time value \\\
            --trigger.action.outText(\\\"time: accessing <\\\" .. param .. \\\"> and received <\\\" .. val .. \\\">\\\", 30)\\\
            local timeString  = dcsCommon.processHMS(timeFormat, val)\\\
            \\\
            if not timeString then timeString = \\\"NULL\\\" end \\\
            -- replace pattern in original with new val \\\
            outMsg = string.gsub(outMsg, pattern, timeString, 1) -- only one sub!\\\
        end\\\
    until not startLoc\\\
    return outMsg\\\
end\\\
\\\
-- process <lat/lon/ele/mgrs/lle/latlon/alt/vel/hdg/rhdg/type/player: zone/unit>\\\
function cfxZones.processDynamicLoc(inMsg, imperialUnits, responses)\\\
    local locales = {\\\"lat\\\", \\\"lon\\\", \\\"ele\\\", \\\"mgrs\\\", \\\"lle\\\", \\\"latlon\\\", \\\"alt\\\", \\\"vel\\\", \\\"hdg\\\", \\\"rhdg\\\", \\\"type\\\", \\\"player\\\"}\\\
    local outMsg = inMsg\\\
    local uHead = 0\\\
    for idx, aLocale in pairs(locales) do \\\
        local pattern = \\\"<\\\" .. aLocale .. \\\":%s*[%s%w%*%d%.%-_]+>\\\"\\\
        repeat -- iterate all patterns one by one \\\
            local startLoc, endLoc = string.find(outMsg, pattern)\\\
            if startLoc then\\\
                local theValParam = string.sub(outMsg, startLoc, endLoc)\\\
                -- strip lead and trailer \\\
                local param = string.gsub(theValParam, \\\"<\\\" .. aLocale .. \\\":%s*\\\", \\\"\\\")\\\
                param = string.gsub(param, \\\">\\\",\\\"\\\")\\\
                -- find zone or unit\\\
                param = dcsCommon.trim(param)\\\
                local thePoint = nil \\\
                local tZone = cfxZones.getZoneByName(param)\\\
                local tUnit = Unit.getByName(param)\\\
                local spd = 0\\\
                local angels = 0 \\\
                local theType = \\\"<errType>\\\"\\\
                local playerName = \\\"Unknown\\\"\\\
                if tZone then\\\
                    theType = \\\"Zone\\\"\\\
                    playerName = \\\"?zone?\\\"\\\
                    thePoint = cfxZones.getPoint(tZone)\\\
                    if tZone.linkedUnit and Unit.isExist(tZone.linkedUnit) then \\\
                        local lU = tZone.linkedUnit\\\
                        local masterPoint = lU:getPoint()\\\
                        thePoint.y = masterPoint.y \\\
                        spd = dcsCommon.getUnitSpeed(lU)\\\
                        spd = math.floor(spd * 3.6)\\\
                        uHead = math.floor(dcsCommon.getUnitHeading(tUnit) * 57.2958) -- to degrees.\\\
                    else \\\
                        -- since zones always have elevation of 0, \\\
                        -- now get the elevation from the map \\\
                        thePoint.y = land.getHeight({x = thePoint.x, y = thePoint.z})\\\
                    end\\\
                elseif tUnit then \\\
                    if Unit.isExist(tUnit) then\\\
                        theType = tUnit:getTypeName()\\\
                        if tUnit.getPlayerName and tUnit:getPlayerName() then\\\
                            playerName = tUnit:getPlayerName()\\\
                        end\\\
                        thePoint = tUnit:getPoint()\\\
                        spd = dcsCommon.getUnitSpeed(tUnit)\\\
                        -- convert m/s to km/h \\\
                        spd = math.floor(spd * 3.6)\\\
                        uHead = math.floor(dcsCommon.getUnitHeading(tUnit) * 57.2958) -- to degrees. \\\
                    end\\\
                else \\\
                    -- nothing to do, remove me.\\\
                end\\\
\\\
                local locString = \\\"err\\\"\\\
                if thePoint then \\\
                    -- now that we have a point, we can do locale-specific\\\
                    -- processing. return result in locString\\\
                    local lat, lon, alt = coord.LOtoLL(thePoint)\\\
                    lat, lon = dcsCommon.latLon2Text(lat, lon)\\\
                    angels = math.floor(thePoint.y) \\\
                    if imperialUnits then \\\
                        alt = math.floor(alt * 3.28084) -- feet\\\
                        spd = math.floor(spd * 0.539957) -- km/h to knots    \\\
                        angels = math.floor(angels * 3.28084)\\\
                    else \\\
                        alt = math.floor(alt) -- meters \\\
                    end \\\
                    \\\
                    if angels > 1000 then \\\
                        angels = math.floor(angels / 100) * 100 \\\
                    end\\\
                    \\\
                    if aLocale == \\\"lat\\\" then locString = lat \\\
                    elseif aLocale == \\\"lon\\\" then locString = lon \\\
                    elseif aLocale == \\\"ele\\\" then locString = tostring(alt)\\\
                    elseif aLocale == \\\"lle\\\" then locString = lat .. \\\" \\\" .. lon .. \\\" ele \\\" .. tostring(alt) \\\
                    elseif aLocale == \\\"latlon\\\" then locString = lat .. \\\" \\\" .. lon \\\
                    elseif aLocale == \\\"alt\\\" then locString = tostring(angels) -- don't confuse alt and angels, bad var naming here\\\
                    elseif aLocale == \\\"vel\\\" then locString = tostring(spd)\\\
                    elseif aLocale == \\\"hdg\\\" then locString = tostring(uHead)\\\
                    elseif aLocale == \\\"type\\\" then locString = theType \\\
                    elseif aLocale == \\\"player\\\" then locString = playerName \\\
                    elseif aLocale == \\\"rhdg\\\" and (responses) then \\\
                        local offset = cfxZones.rspMapper360(uHead, #responses)\\\
                        locString = dcsCommon.trim(responses[offset])\\\
                    else \\\
                        -- we have mgrs\\\
                        local grid = coord.LLtoMGRS(coord.LOtoLL(thePoint))\\\
                        locString = grid.UTMZone .. ' ' .. grid.MGRSDigraph .. ' ' .. grid.Easting .. ' ' .. grid.Northing\\\
                    end\\\
                end\\\
                -- replace pattern in original with new val \\\
                outMsg = string.gsub(outMsg, pattern, locString, 1) -- only one sub!\\\
            end -- if startloc\\\
        until not startLoc\\\
    end -- for all locales \\\
    return outMsg\\\
end\\\
\\\
function cfxZones.rspMapper360(directionInDegrees, numResponses)\\\
    -- maps responses around a clock. Clock has 12 'responses' (12, 1, .., 11), \\\
    -- with the first (12) also mapping to the last half arc \\\
    -- this method dynamically 'winds' the responses around \\\
    -- a clock and returns the index of the message to display \\\
    if numResponses < 1 then numResponses = 1 end \\\
    directionInDegrees = math.floor(directionInDegrees) \\\
    while directionInDegrees < 0 do directionInDegrees = directionInDegrees + 360 end \\\
    while directionInDegrees >= 360 do directionInDegrees = directionInDegrees - 360 end \\\
    -- now we have 0..360 \\\
    -- calculate arc per item \\\
    local arcPerItem = 360 / numResponses\\\
    local halfArc = arcPerItem / 2\\\
\\\
    -- we now map 0..360 to (0-halfArc..360-halfArc) by shifting \\\
    -- direction by half-arc and clipping back 0..360\\\
    -- and now we can directly derive the index of the response \\\
    directionInDegrees = directionInDegrees + halfArc\\\
    if directionInDegrees >= 360 then directionInDegrees = directionInDegrees - 360 end \\\
    \\\
    local index = math.floor(directionInDegrees / arcPerItem) + 1 -- 1 .. numResponses \\\
    \\\
    return index \\\
end\\\
\\\
-- replaces dcsCommon with same name \\\
-- timeFormat is optional, default is \\\"<:h>:<:m>:<:s>\\\"\\\
-- imperialUnits is optional, defaults to meters \\\
-- responses is an array of string, defaults to {}\\\
function cfxZones.processStringWildcards(inMsg, theZone, timeFormat, imperialUnits, responses)\\\
    if not inMsg then return \\\"<nil inMsg>\\\" end\\\
    local formerType = type(inMsg)\\\
    if formerType ~= \\\"string\\\" then inMsg = tostring(inMsg) end\\\
    if not inMsg then inMsg = \\\"<inMsg is incompatible type \\\" .. formerType .. \\\">\\\" end\\\
    local theMsg = inMsg\\\
    -- process common DCS stuff like /n \\\
    theMsg = dcsCommon.processStringWildcards(theMsg) -- call old inherited\\\
    -- process <z>\\\
    theMsg = cfxZones.processZoneStatics(theMsg, theZone)\\\
    -- process <t>, <lat>, <lon>, <ele>, <mgrs>\\\
    theMsg = cfxZones.processSimpleZoneDynamics(theMsg, theZone, timeFormat, imperialUnits)\\\
    -- process <v: flag>, <rsp: flag> <rrnd>\\\
    theMsg = cfxZones.processDynamicValues(theMsg, theZone, responses)\\\
    -- process <t: flag>\\\
    theMsg = cfxZones.processDynamicTime(theMsg, theZone, timeFormat)\\\
    -- process <lat/lon/ele/mgrs/lle/latlon/alt/vel/hdg/rhdg/type/player: zone/unit>\\\
    theMsg = cfxZones.processDynamicLoc(theMsg, imperialUnits, responses)\\\
\\\
    return theMsg\\\
end\\\
\\\
--\\\
-- ============\\\
-- MOVING ZONES \\\
-- ============ \\\
-- \\\
-- Moving zones contain a link to their unit\\\
-- they are always located at an offset (x,z) or delta, phi \\\
-- to their master unit. delta phi allows adjustment for heading\\\
-- The cool thing about moving zones in cfx is that they do not\\\
-- require special handling, they are always updated \\\
-- and work with 'pointinzone' etc automatically\\\
\\\
-- Always works on cfx Zones, NEVER on DCS zones.\\\
--\\\
-- requires that readFromDCS has been done\\\
--\\\
function cfxZones.getDCSOrigin(aZone)\\\
    local o = {}\\\
    o.x = aZone.dcsOrigin.x\\\
    o.y = 0\\\
    o.z = aZone.dcsOrigin.z \\\
    return o\\\
end\\\
\\\
function cfxZones.getLinkedUnit(theZone)\\\
    if not theZone then return nil end \\\
    if not theZone.linkedUnit then return nil end \\\
    if not Unit.isExist(theZone.linkedUnit) then return nil end \\\
    return theZone.linkedUnit \\\
end\\\
\\\
function cfxZones.getPoint(aZone, getHeight) -- always works, even linked, returned point can be reused\\\
-- returned y (when using getHeight) is that of the land, else 0 \\\
    if not getHeight then getHeight = false end \\\
    if aZone.linkedUnit then \\\
        local theUnit = aZone.linkedUnit\\\
        -- has a link. is link existing?\\\
        if Unit.isExist(theUnit) then \\\
            -- updates zone position \\\
            cfxZones.centerZoneOnUnit(aZone, theUnit)\\\
            local dx = aZone.dx\\\
            local dy = aZone.dy\\\
            if aZone.useHeading then \\\
                dx, dy = cfxZones.calcHeadingOffset(aZone, theUnit)\\\
            end\\\
            cfxZones.offsetZone(aZone, dx, dy)\\\
        end\\\
    end\\\
    local thePos = {}\\\
    thePos.x = aZone.point.x\\\
    thePos.z = aZone.point.z\\\
    if not getHeight then \\\
        thePos.y = 0 -- aZone.y \\\
    else \\\
        thePos.y = land.getHeight({x = thePos.x, y = thePos.z})\\\
    end\\\
    \\\
    return thePos \\\
end\\\
\\\
function cfxZones.linkUnitToZone(theUnit, theZone, dx, dy) -- note: dy is really Z, don't get confused!!!!\\\
    theZone.linkedUnit = theUnit\\\
    if not dx then dx = 0 end\\\
    if not dy then dy = 0 end \\\
    theZone.dx = dx\\\
    theZone.dy = dy \\\
    theZone.rxy = math.sqrt(dx * dx + dy * dy) -- radius \\\
    local unitHeading = dcsCommon.getUnitHeading(theUnit)\\\
    local bearingOffset = math.atan2(dy, dx) -- rads \\\
    if bearingOffset < 0 then bearingOffset = bearingOffset + 2 * 3.141592 end \\\
\\\
    local dPhi = bearingOffset - unitHeading\\\
    if dPhi < 0 then dPhi = dPhi + 2 * 3.141592 end\\\
    if (theZone.verbose and theZone.useHeading) then \\\
        trigger.action.outText(\\\"Zone is at <\\\" .. math.floor(57.2958 * dPhi) .. \\\"> relative to unit heading\\\", 30)\\\
    end\\\
    theZone.dPhi = dPhi -- constant delta between unit heading and \\\
    -- direction to zone \\\
    theZone.uHdg = unitHeading -- original unit heading to turn other \\\
    -- units if need be \\\
    --trigger.action.outText(\\\"Link setup: dx=<\\\" .. dx .. \\\">, dy=<\\\" .. dy .. \\\"> unit original hdg = <\\\" .. math.floor(57.2958 * unitHeading)  .. \\\">\\\", 30)\\\
end\\\
\\\
function cfxZones.zonesLinkedToUnit(theUnit) -- returns all zones linked to this unit \\\
    if not theUnit then return {} end \\\
    local linkedZones = {}\\\
    for idx, theZone in pairs (cfxZones.zones) do \\\
        if theZone.linkedUnit == theUnit then \\\
            table.insert(linkedZones, theZone)\\\
        end\\\
    end\\\
    return linkedZones\\\
end\\\
\\\
function cfxZones.calcHeadingOffset(aZone, theUnit)\\\
    -- recalc dx and dy based on ry and current heading \\\
    -- since 0 degrees is [0,1] = [0,r] the calculation of \\\
    -- rotated coords can be simplified from \\\
    -- xr = x cos phi - y sin phi = -r sin phi\\\
    -- yr = y cos phi + x sin phi = r cos phi \\\
    local unitHeading = dcsCommon.getUnitHeading(theUnit)\\\
    -- add heading offset \\\
    local zoneBearing = unitHeading + aZone.dPhi \\\
    if zoneBearing > 2 * 3.141592 then zoneBearing = zoneBearing - 2 * 3.141592 end \\\
                    \\\
    -- in DCS, positive x is north (wtf?) and positive z is east \\\
    local dy = (-aZone.rxy) * math.sin(zoneBearing)\\\
    local dx = aZone.rxy * math.cos(zoneBearing)\\\
    \\\
    --trigger.action.outText(\\\"zone bearing is \\\" .. math.floor(zoneBearing * 57.2958) .. \\\" dx = <\\\" .. dx .. \\\"> , dy = <\\\" .. dy .. \\\">\\\", 30)\\\
    return dx, -dy -- note: dy is z coord!!!!\\\
end\\\
\\\
function cfxZones.updateMovingZones()\\\
    cfxZones.updateSchedule = timer.scheduleFunction(cfxZones.updateMovingZones, {}, timer.getTime() + 1/cfxZones.ups)\\\
    -- simply scan all cfx zones for the linkName property, and if present\\\
    -- update the zone's points\\\
    for aName,aZone in pairs(cfxZones.zones) do\\\
        -- only do this if ther is a linkName property, \\\
        -- else this zone isn't linked. link name is harmonized from \\\
        -- both linkUnit non-DML and linedUnit DML        \\\
        if aZone.linkName then \\\
            if aZone.linkBroken then \\\
                -- try to relink \\\
                cfxZones.initLink(aZone)\\\
            else --if aZone.linkName then  \\\
                -- always re-acquire linkedUnit via Unit.getByName()\\\
                -- this way we gloss over any replacements via spawns\\\
                aZone.linkedUnit = Unit.getByName(aZone.linkName)\\\
            end\\\
            \\\
            if aZone.linkedUnit then \\\
                local theUnit = aZone.linkedUnit\\\
                -- has a link. is link existing?\\\
                if theUnit:isExist() then \\\
                    cfxZones.centerZoneOnUnit(aZone, theUnit)\\\
                    local dx = aZone.dx \\\
                    local dy = aZone.dy -- this is actually z \\\
                    if aZone.useHeading then \\\
                        dx, dy = cfxZones.calcHeadingOffset(aZone, theUnit)\\\
                    end\\\
                    cfxZones.offsetZone(aZone, dx, dy)\\\
                else \\\
                    -- we lost link (track level)\\\
                    aZone.linkBroken = true \\\
                    aZone.linkedUnit = nil \\\
                end\\\
            else \\\
                -- we lost link (top level)\\\
                aZone.linkBroken = true \\\
                aZone.linkedUnit = nil \\\
            end\\\
        else \\\
            -- this zone isn't linked\\\
        end\\\
    end\\\
end\\\
\\\
function cfxZones.initLink(theZone)\\\
\\\
    theZone.linkBroken = true \\\
    theZone.linkedUnit = nil \\\
    theUnit = Unit.getByName(theZone.linkName)\\\
    if theUnit then\\\
\\\
        local dx = 0\\\
        local dz = 0\\\
        if theZone.useOffset or theZone.useHeading then \\\
            local A = cfxZones.getDCSOrigin(theZone)\\\
            local B = theUnit:getPoint()\\\
            local delta = dcsCommon.vSub(A,B) \\\
            dx = delta.x \\\
            dz = delta.z\\\
        end\\\
        cfxZones.linkUnitToZone(theUnit, theZone, dx, dz) -- also sets theZone.linkedUnit\\\
\\\
        if theZone.verbose then \\\
            trigger.action.outText(\\\"Link established for zone <\\\" .. theZone.name .. \\\"> to unit <\\\" .. theZone.linkName .. \\\">: dx=<\\\" .. math.floor(dx) .. \\\">, dz=<\\\" .. math.floor(dz) .. \\\"> dist = <\\\" .. math.floor(math.sqrt(dx * dx + dz * dz)) .. \\\">\\\" , 30)\\\
        end \\\
        theZone.linkBroken = nil \\\
\\\
    else \\\
        if theZone.verbose then \\\
            trigger.action.outText(\\\"Linked unit: no unit <\\\" .. theZone.linkName .. \\\"> to link <\\\" .. theZone.name .. \\\"> to\\\", 30)\\\
        end\\\
    end\\\
end\\\
\\\
function cfxZones.startMovingZones()\\\
    -- read all zones, and look for a property called 'linkedUnit'\\\
    -- which will make them a linked zone if there is a unit that exists\\\
    -- also suppors 'useOffset' and 'useHeading'\\\
    for aName,aZone in pairs(cfxZones.zones) do\\\
        \\\
        local lU = nil \\\
        -- check if DCS zone has the linkUnit new attribute introduced in \\\
        -- late 2022 with 2.8\\\
        if aZone.dcsZone.linkUnit then \\\
            local theID = aZone.dcsZone.linkUnit \\\
            lU = dcsCommon.getUnitNameByID(theID)\\\
            if not lU then \\\
                trigger.action.outText(\\\"WARNING: Zone <\\\" .. aZone.name .. \\\">: cannot resolve linked unit ID <\\\" .. theID .. \\\">\\\", 30)\\\
                lU = \\\"***DML link err***\\\"\\\
            end\\\
        elseif cfxZones.hasProperty(aZone, \\\"linkedUnit\\\") then \\\
            lU = cfxZones.getZoneProperty(aZone, \\\"linkedUnit\\\")\\\
        end\\\
        \\\
        -- sanity check \\\
        if aZone.dcsZone.linkUnit and cfxZones.hasProperty(aZone, \\\"linkedUnit\\\") then \\\
            trigger.action.outText(\\\"WARNING: Zone <\\\" .. aZone.name .. \\\"> has dual unit link definition. Will use link to unit <\\\" .. lU .. \\\">\\\", 30)\\\
        end\\\
        \\\
        if lU then \\\
            aZone.linkName = lU\\\
            aZone.useOffset = cfxZones.getBoolFromZoneProperty(aZone, \\\"useOffset\\\", false)\\\
            aZone.useHeading = cfxZones.getBoolFromZoneProperty(aZone, \\\"useHeading\\\", false)\\\
            \\\
            cfxZones.initLink(aZone)\\\
\\\
        end\\\
        \\\
    end\\\
end\\\
\\\
\\\
--\\\
-- ===========\\\
-- INIT MODULE\\\
-- ===========\\\
--\\\
\\\
function cfxZones.initZoneVerbosity()\\\
    for aName,aZone in pairs(cfxZones.zones) do\\\
        -- support for zone-local verbose flag \\\
        aZone.verbose = cfxZones.getBoolFromZoneProperty(aZone, \\\"verbose\\\", false)\\\
    end\\\
end\\\
\\\
function cfxZones.init()\\\
    -- read all zones into my own db\\\
    cfxZones.readFromDCS(true) -- true: erase old\\\
\\\
    -- pre-read zone owner for all zones\\\
    local pZones = cfxZones.zonesWithProperty(\\\"owner\\\")\\\
    for n, aZone in pairs(pZones) do\\\
        aZone.owner = cfxZones.getCoalitionFromZoneProperty(aZone, \\\"owner\\\", 0)\\\
    end\\\
        \\\
    -- enable all zone's verbose flags if present\\\
    -- must be done BEFORE we start the moving zones \\\
    cfxZones.initZoneVerbosity()\\\
    \\\
    -- now initialize moving zones\\\
    cfxZones.startMovingZones()\\\
    cfxZones.updateMovingZones() -- will auto-repeat\\\
    \\\
    trigger.action.outText(\\\"cf/x Zones v\\\".. cfxZones.version .. \\\": loaded, zones:\\\" .. dcsCommon.getSizeOfTable(cfxZones.zones), 30)\\\
\\\
end\\\
\\\
-- get everything rolling\\\
cfxZones.init()\\\
\");a_do_script(\"-- cfxCommander - issue dcs commands to groups etc\\\
--\\\
-- supports scheduling\\\
-- *** EXTENDS ZONES: 'pathing' attribute \\\
--\\\
cfxCommander = {}\\\
cfxCommander.version = \\\"1.1.3\\\"\\\
--[[-- VERSION HISTORY\\\
 - 1.0.5 - createWPListForGroupToPointViaRoads: detect no road found \\\
 - 1.0.6 - build in more group checks in assign wp list \\\
         - added sanity checks for doScheduledTask\\\
         - assignWPListToGroup now can schedule tasks \\\
         - makeGroupGoThere supports scheduling\\\
         - makeGroupGoTherePreferringRoads supports scheduling \\\
         - scheduleTaskForGroup supports immediate execution\\\
         - makeGroupHalt\\\
 - 1.0.7 - warning if road shorter than direct\\\
         - forceOffRoad option\\\
         - noRoadsAtAll option \\\
 - 1.1.0 - load libs \\\
         - pathing zones. Currently only supports \\\
         - offroad to override road-usage\\\
         - pathing zones are overridden by noRoadsAtAll\\\
         - CommanderConfig zones \\\
 - 1.1.1 - default pathing for pathing zone is normal, not offroad \\\
 - 1.1.2 - makeGroupTransmit \\\
         - makeGroupStopTransmitting\\\
         - verbose check before path warning\\\
         - added delay defaulting for most scheduling functions \\\
 - 1.1.3 - isExist() guard improvements for multiple methods\\\
         - cleaned up comments\\\
 \\\
--]]--\\\
\\\
cfxCommander.requiredLibs = {\\\
    \\\"dcsCommon\\\", -- common is of course needed for everything\\\
    \\\"cfxZones\\\", -- zones management for pathing zones \\\
}\\\
\\\
cfxCommander.verbose = false \\\
cfxCommander.forceOffRoad = true -- if true, vehicles path follow roads, but may drive offroad (they follow vertex points from path but not the road as they are still commanded 'offroad')\\\
cfxCommander.noRoadsAtAll = true  -- if true, always go direct, overrides forceOffRoad when true. Always a two-point path. Here, there, bang! \\\
cfxCommander.pathZones = {} -- zones that can override road settings\\\
\\\
--\\\
-- path zone\\\
--\\\
function cfxCommander.processPathingZone(aZone) -- process attribute and add to zone\\\
    local pathing = cfxZones.getStringFromZoneProperty(aZone, \\\"pathing\\\", \\\"normal\\\") -- must be \\\"offroad\\\" to force offroad\\\
    pathing = pathing:lower()\\\
    -- currently no validation of attribute \\\
    aZone.pathing = pathing\\\
end \\\
\\\
function cfxCommander.addPathingZone(aZone)\\\
    table.insert(cfxCommander.pathZones, aZone)\\\
end \\\
\\\
function cfxCommander.hasPathZoneFor(here, there)\\\
    for idx, aZone in pairs(cfxCommander.pathZones) do \\\
        if cfxZones.pointInZone(here, aZone) then return aZone end \\\
        if cfxZones.pointInZone(there, aZone) then return aZone end\\\
    end\\\
    return nil\\\
end\\\
\\\
--\\\
-- Config Zone Reading if present \\\
--\\\
function cfxCommander.readConfigZone()\\\
    -- note: must match exactly!!!!\\\
    local theZone = cfxZones.getZoneByName(\\\"CommanderConfig\\\") \\\
    if not theZone then \\\
        trigger.action.outText(\\\"+++cmdr: no config zone!\\\", 30) \\\
        return \\\
    end \\\
    \\\
    trigger.action.outText(\\\"+++cmdr: found config zone!\\\", 30) \\\
    \\\
    cfxCommander.verbose = cfxZones.getBoolFromZoneProperty(theZone, \\\"verbose\\\", false)\\\
    cfxCommander.forceOffRoad = cfxZones.getBoolFromZoneProperty(theZone, \\\"forceOffRoad\\\", false) -- if true, vehicles path follow roads, but may drive offroad\\\
    cfxCommander.noRoadsAtAll = cfxZones.getBoolFromZoneProperty(theZone, \\\"noRoadsAtAll\\\", false)\\\
\\\
end\\\
\\\
--\\\
-- Options are key, value pairs. Scheduler when you are creating groups\\\
-- \\\
\\\
function cfxCommander.doOption(data) \\\
    if cfxCommander.verbose then \\\
        trigger.action.outText(\\\"Commander: setting option \\\" .. data.key .. \\\" --> \\\" .. data.value, 30)\\\
    end\\\
\\\
    local theController = data.group:getController()\\\
    theController:setOption(data.key, data.value)\\\
end\\\
\\\
function cfxCommander.scheduleOptionForGroup(group, key, value, delay) \\\
    local data = {}\\\
    if not delay then delay = 0.1 end \\\
    data.group = group\\\
    data.key = key\\\
    data.value = value \\\
    timer.scheduleFunction(cfxCommander.doOption, data, timer.getTime() + delay)\\\
end\\\
\\\
--\\\
-- performCommand is a special version of issuing a command\\\
-- that can be easily schduled by pushing the commandData on \\\
-- the stack with scheduling it \\\
-- group or name must be filled to get the group,\\\
-- and the command table is what is going to be passed to the setCommand\\\
-- commands are given in an array, so you can stack commands \\\
function cfxCommander.performCommands(commandData)\\\
    -- see if we have a group\\\
    if not commandData.group then \\\
        commandData.group = Group.getByName(commandData.name) -- better be inited!\\\
    end\\\
    -- get the AI\\\
    local theController = commandData.group:getController()\\\
    for i=1, #commandData.commands do\\\
        if cfxCommander.verbose then \\\
            trigger.action.outText(\\\"Commander: performing \\\" .. commandData.commands[i].id, 30)\\\
        end\\\
        theController:setCommand(commandData.commands[i])\\\
    end\\\
    \\\
    return nil -- a timer called us, so we return no desire to be rescheduled\\\
end\\\
\\\
function cfxCommander.scheduleCommands(data, delay)\\\
    if not delay then delay = 1 end \\\
    timer.scheduleFunction(cfxCommander.performCommands, data, timer.getTime() + delay)\\\
end\\\
\\\
function cfxCommander.scheduleSingleCommand(group, command, delay) \\\
    if not delay then delay = 1 end \\\
    local data = createCommandDataTableFor(group)\\\
    cfxCommander.addCommand(data, command)\\\
    cfxCommander.scheduleCommands(data, delay)\\\
end\\\
\\\
\\\
function cfxCommander.createCommandDataTableFor(group, name)\\\
    local cD = {}\\\
    if not group then \\\
        cD.name = name\\\
    else\\\
        cD.group = group\\\
    end\\\
    cD.commands={}\\\
    return cD\\\
end\\\
\\\
function cfxCommander.addCommand(theCD, theCommand)\\\
    if not theCD then return end \\\
    if not theCommand then return end \\\
    \\\
    table.insert(theCD.commands, theCommand)\\\
end\\\
\\\
function cfxCommander.createSetFrequencyCommand(freq, modulator)\\\
    local theCmd = {}\\\
    if not freq then freq = 100 end \\\
    if not modulator then modulator = 0 end -- AM = 0, default\\\
    theCmd.id = 'SetFrequency'\\\
    theCmd.params = {}\\\
    theCmd.params.frequency = freq * 10000 -- 88 --> 880000. 124 --> 1.24 MHz\\\
    theCmd.params.modulation = modulator\\\
    return theCmd\\\
end\\\
\\\
-- oneShot is optional. if present and anything but false, will cause message to \\\
-- me sent only once, no loops\\\
function cfxCommander.createTransmissionCommand(filename, oneShot)\\\
    local looping = true\\\
    if not filename then filename = \\\"dummy\\\" end \\\
    if oneShot then looping = false end\\\
    local theCmd = {}\\\
    theCmd.id = 'TransmitMessage'\\\
    theCmd.params = {}\\\
    theCmd.params.loop = looping\\\
    theCmd.params.file = \\\"l10n/DEFAULT/\\\" .. filename -- need to prepend the resource string\\\
    return theCmd\\\
end\\\
\\\
function cfxCommander.createStopTransmissionCommand()\\\
    local theCmd = {}\\\
    theCmd.id = 'stopTransmission'\\\
    theCmd.params = {}\\\
    return theCmd\\\
end\\\
\\\
--\\\
-- tasks\\\
-- \\\
\\\
function cfxCommander.doScheduledTask(data) \\\
    if cfxCommander.verbose then \\\
        trigger.action.outText(\\\"Commander: setting task \\\" .. data.task.id .. \\\" for group \\\" .. data.group:getName(), 30)\\\
    end\\\
    local theGroup = data.group \\\
    if not theGroup then return end \\\
    if not Group.isExist(theGroup) then return end \\\
--    if not theGroup.isExist then return end\\\
    \\\
    local theController = theGroup:getController()\\\
    theController:pushTask(data.task)\\\
end\\\
\\\
function cfxCommander.scheduleTaskForGroup(group, task, delay)\\\
    if not delay then delay = 0 end \\\
    local data = {}\\\
    data.group = group\\\
    data.task = task\\\
    if delay < 0.001 then \\\
        cfxCommander.doScheduledTask(data) -- immediate execution\\\
        return \\\
    end\\\
    timer.scheduleFunction(cfxCommander.doScheduledTask, data, timer.getTime() + delay)\\\
end\\\
\\\
function cfxCommander.createAttackGroupCommand(theGroupToAttack)\\\
    local task = {}\\\
    task.id = 'AttackGroup'\\\
    task.params = {}\\\
    task.params.groupID = theGroupToAttack:getID()\\\
    return task\\\
end\\\
\\\
function cfxCommander.createEngageGroupCommand(theGroupToAttack)\\\
    local task = {}\\\
    task.id = 'EngageGroup'\\\
    task.params = {}\\\
    task.params.groupID = theGroupToAttack:getID()\\\
    return task\\\
end\\\
\\\
--\\\
-- waypoints, routes etc \\\
--\\\
\\\
-- basic waypoint is for ground units. point can be xyz or xy \\\
function cfxCommander.createBasicWaypoint(point, speed, formation)\\\
    local wp = {}\\\
    wp.x = point.x\\\
    -- support xyz and xy format\\\
    if point.z then \\\
        wp.y = point.z\\\
    else\\\
        wp.y = point.y\\\
    end\\\
    \\\
    if not speed then speed = 6 end -- 6 m/s = 20 kph\\\
    wp.speed = speed \\\
    \\\
    if cfxCommander.forceOffRoad then \\\
        formation = \\\"Off Road\\\"\\\
    end\\\
    \\\
    if not formation then formation = \\\"Off Road\\\" end\\\
    -- legal formations:\\\
    -- Off road\\\
    -- On Road -- second letter upper case?\\\
    -- Cone \\\
    -- Rank\\\
    -- Diamond\\\
    -- Vee\\\
    -- EchelonR\\\
    -- EchelonL\\\
    wp.action = formation -- silly name, but that's how ME does it\\\
    wp.type = 'Turning Point'\\\
    return wp\\\
\\\
end\\\
\\\
function cfxCommander.buildTaskFromWPList(wpList)\\\
    -- build the task that will make a group follow the WP list\\\
    -- we do this by creating a \\\"Mission\\\" task around the WP List\\\
    -- WP list is consumed by this action\\\
    local missionTask = {}\\\
    missionTask.id = \\\"Mission\\\"\\\
    missionTask.params = {}\\\
    missionTask.params.route = {}\\\
    missionTask.params.route.points=wpList\\\
    return missionTask\\\
end\\\
\\\
function cfxCommander.assignWPListToGroup(group, wpList, delay)\\\
    if not delay then delay = 0 end \\\
    if not group then return end \\\
    if type(group) == 'string' then -- group name, nice mist trick \\\
        group = Group.getByName(group)\\\
    end\\\
    if not group then return end \\\
    if not Group.isExist(group) then return end \\\
    \\\
    local theTask = cfxCommander.buildTaskFromWPList(wpList)\\\
    local ctrl = group:getController()\\\
\\\
--[[--\\\
    if delay < 0.001 then -- immediate action\\\
        if ctrl then\\\
            ctrl:setTask(theTask)\\\
        end\\\
    else \\\
        -- delay execution of this command by the specified amount \\\
        -- of seconds \\\
        cfxCommander.scheduleTaskForGroup(group, theTask, delay)\\\
    end\\\
--]]--\\\
    cfxCommander.scheduleTaskForGroup(group, theTask, delay)\\\
end\\\
\\\
function cfxCommander.createWPListForGroupToPoint(group, point, speed, formation)\\\
    if type(group) == 'string' then -- group name\\\
        group = Group.getByName(group)\\\
    end\\\
\\\
    local wpList = {}\\\
    -- here we are, and we want to go there. In DCS, this means that\\\
    -- we need to create a wp list consisting of here and there\\\
    local here = dcsCommon.getGroupLocation(group)\\\
    local wpHere = cfxCommander.createBasicWaypoint(here, speed, formation)\\\
    local wpThere = cfxCommander.createBasicWaypoint(point, speed, formation)\\\
    wpList[1] = wpHere\\\
    wpList[2] = wpThere\\\
    return wpList\\\
end\\\
\\\
-- make a ground units group head to a waypoint by replacing the entire mission\\\
-- with a two-waypoint lsit from (here) to there at speed and formation. formation\\\
-- default is 'off road'\\\
function cfxCommander.makeGroupGoThere(group, there, speed, formation, delay)\\\
    if not delay then delay = 0 end \\\
    if type(group) == 'string' then -- group name\\\
        group = Group.getByName(group)\\\
    end\\\
    local wp = cfxCommander.createWPListForGroupToPoint(group, there, speed, formation)\\\
    \\\
    cfxCommander.assignWPListToGroup(group, wp, delay)\\\
end\\\
\\\
function cfxCommander.calculatePathLength(roadPoints)\\\
    local totalLen = 0\\\
    if #roadPoints < 2 then return 0 end\\\
    for i=1, #roadPoints-1 do\\\
        totalLen = totalLen + dcsCommon.dist(roadPoints[i], roadPoints[i+1])\\\
    end\\\
    return totalLen\\\
end\\\
\\\
-- make ground units go from here (group location) to there, using roads if possible\\\
function cfxCommander.createWPListForGroupToPointViaRoads(group, point, speed)\\\
    if type(group) == 'string' then -- group name\\\
        group = Group.getByName(group)\\\
    end\\\
\\\
    local wpList = {}\\\
    -- here we are, and we want to go there. In DCS, this means that\\\
    -- we need to create a wp list consisting of here and there\\\
    -- when going via roads, we add to more wayoints:\\\
    -- go on-roads and leaveRoads. \\\
    -- only if we can get these two additional points, we do that, else we \\\
    -- fall back to direct route \\\
    \\\
    local here = dcsCommon.getGroupLocation(group)\\\
\\\
    -- now generate a list of all points from here to there that uses roads\\\
    local rawRoadPoints = land.findPathOnRoads('roads', here.x, here.z, point.x, point.z)\\\
    -- this is the entire path. calculate the length and make \\\
    -- sure that path on-road isn't more than twice as long \\\
    -- that can happen if a bridge is out or we need to go around a hill\\\
    if not rawRoadPoints or #rawRoadPoints<3 then \\\
        trigger.action.outText(\\\"+++ no roads leading there. Taking direct approach\\\", 30)\\\
        return cfxCommander.createWPListForGroupToPoint(group, point, speed)\\\
    end\\\
    \\\
    local pathLength = cfxCommander.calculatePathLength(rawRoadPoints)\\\
    local direct = dcsCommon.dist(here, point)\\\
    if pathLength < direct and cfxCommander.verbose then \\\
        trigger.action.outText(\\\"+++dcsC: WARNING road path (\\\" .. pathLength .. \\\") shorter than direct route(\\\" .. direct .. \\\"), will not path correctly\\\", 30)\\\
    end\\\
    \\\
    if pathLength > (2 * direct) then \\\
        -- road takes too long, take direct approach\\\
        --trigger.action.outText(\\\"+++ road path (\\\" .. pathLength .. \\\") > twice direct route(\\\" .. direct .. \\\"), commencing direct off-road\\\", 30)\\\
        return cfxCommander.createWPListForGroupToPoint(group, point, speed)\\\
    end\\\
    \\\
    --trigger.action.outText(\\\"+++ \\\".. group:getName() .. \\\": choosing road path l=\\\" .. pathLength .. \\\" over direct route d=\\\" .. direct, 30)\\\
    \\\
    -- if we are here, the road trip is valid \\\
    for idx, wp in pairs(rawRoadPoints) do \\\
        -- createBasic... supports w.xy format\\\
        local theNewWP = cfxCommander.createBasicWaypoint(wp, speed, \\\"On Road\\\") -- force off road for better compatibility?\\\
        table.insert(wpList, theNewWP)\\\
    end\\\
    \\\
    \\\
    \\\
    -- now make first and last entry OFF Road\\\
    local wpc = wpList[1]\\\
    wpc.action = \\\"Off Road\\\"\\\
    wpc = wpList[#wpList]\\\
    wpc.action = \\\"Off Road\\\"\\\
\\\
    return wpList\\\
end\\\
\\\
function cfxCommander.makeGroupGoTherePreferringRoads(group, there, speed, delay)\\\
    if type(group) == 'string' then -- group name\\\
        group = Group.getByName(group)\\\
    end\\\
    if not delay then delay = 0 end \\\
\\\
\\\
    if cfxCommander.noRoadsAtAll then \\\
        -- we don't even follow roads, completely forced off\\\
        cfxCommander.makeGroupGoThere(group, there, speed, \\\"Off Road\\\", delay)\\\
        return \\\
    end\\\
\\\
    -- see if we have an override situation \\\
    -- for one of the two points where a pathing Zone \\\
    -- overrides the roads setting \\\
    if #cfxCommander.pathZones > 0 then  \\\
        local here = dcsCommon.getGroupLocation(group)\\\
        local oRide = cfxCommander.hasPathZoneFor(here, there)\\\
        if oRide and oRide.pathing == \\\"offroad\\\" then \\\
            -- yup, override road preference\\\
            cfxCommander.makeGroupGoThere(group, there, speed, \\\"Off Road\\\", delay)\\\
            return \\\
        end\\\
    end\\\
\\\
    -- viaRoads will only use roads if the road trip isn't more than twice \\\
    -- as long as the direct route \\\
    local wp = cfxCommander.createWPListForGroupToPointViaRoads(group, there, speed)\\\
    cfxCommander.assignWPListToGroup(group, wp, delay)\\\
end\\\
\\\
\\\
function cfxCommander.makeGroupHalt(group, delay)\\\
    if not group then return end \\\
    if not Group.isExist(group) then return end \\\
    if not delay then delay = 0 end \\\
    local theTask = {id = 'Hold', params = {}}\\\
    cfxCommander.scheduleTaskForGroup(group, theTask, delay)\\\
end\\\
\\\
function cfxCommander.makeGroupTransmit(group, tenKHz, filename, oneShot, delay)\\\
    if not group then return end \\\
    if not tenKHz then tenKHz = 20 end -- default to 200KHz\\\
    if not delay then delay = 1.0 end \\\
    if not filename then return end \\\
    if not oneShot then oneShot = false end \\\
    \\\
    -- now build the transmission command\\\
    local theCommands = cfxCommander.createCommandDataTableFor(group)\\\
    local cmd = cfxCommander.createSetFrequencyCommand(tenKHz) -- freq in 10000 Hz\\\
    cfxCommander.addCommand(theCommands, cmd)\\\
    cmd = cfxCommander.createTransmissionCommand(filename, oneShot)\\\
    cfxCommander.addCommand(theCommands, cmd)\\\
    cfxCommander.scheduleCommands(theCommands, delay)\\\
end \\\
\\\
function cfxCommander.makeGroupStopTransmitting(group, delay)\\\
    if not delay then delay = 1 end \\\
    if not group then return end \\\
    local theCommands = cfxCommander.createCommandDataTableFor(group)\\\
    local cmd = cfxCommander.createStopTransmissionCommand()\\\
    cfxCommander.addCommand(theCommands, cmd)\\\
    cfxCommander.scheduleCommands(theCommands, delay)\\\
end\\\
\\\
\\\
function cfxCommander.start()\\\
    -- make sure we have loaded all relevant libraries \\\
    if not dcsCommon.libCheck(\\\"cfx Commander\\\", cfxCommander.requiredLibs) then \\\
        trigger.action.outText(\\\"cf/x Commander aborted: missing libraries\\\", 30)\\\
        return false \\\
    end\\\
    \\\
    -- identify and process all 'pathing' zones\\\
    local pathZones = cfxZones.getZonesWithAttributeNamed(\\\"pathing\\\")\\\
    \\\
    -- now create a spawner for all, add them to the spawner updater, and spawn for all zones that are not\\\
    -- paused \\\
    for k, aZone in pairs(pathZones) do \\\
        cfxCommander.processPathingZone(aZone) -- process attribute and add to zone\\\
        cfxCommander.addPathingZone(aZone) -- remember it so we can smoke it\\\
    end\\\
    \\\
    -- read config overides \\\
    cfxCommander.readConfigZone()\\\
    \\\
    return true\\\
end\\\
\\\
if cfxCommander.start() then \\\
    trigger.action.outText(\\\"cfxCommander v\\\" .. cfxCommander.version .. \\\" loaded\\\", 30)\\\
else \\\
    trigger.action.outText(\\\"+++cfxCommander load FAILED\\\", 30)\\\
    cfxCommander = nil\\\
end\\\
\\\
--[[-- known issues\\\
\\\
- troops remain motionless until all are repaired or produced after cature\\\
- long roads / roads not taken in persia \\\
- all troops red and blue become motionless when one zone is occupied\\\
- after capture, the troop capturing remains, all others can go on. one will always remain there \\\
- rethink the factor to add to road, and simply add 100m \\\
\\\
 TODO: break long distances into smaller paths, and gravitate towards pathing zones if they have a 'gravitate' or similar attribute \\\
--]]--\\\
\");a_do_script(\"cfxGroundTroops = {}\\\
cfxGroundTroops.version = \\\"1.7.8\\\"\\\
cfxGroundTroops.ups = 1\\\
cfxGroundTroops.verbose = false \\\
cfxGroundTroops.requiredLibs = {\\\
    \\\"dcsCommon\\\", -- common is of course needed for everything\\\
                 -- pretty stupid to check for this since we \\\
                 -- need common to invoke the check, but anyway\\\
    \\\"cfxCommander\\\", -- generic data module for weight \\\
    -- cfxOwnedZones is optional \\\
}\\\
-- ground troops: a module to manage ground toops. makes groups of ground troops\\\
-- patrol and engage enemies and signal idle\\\
-- understands cfxOwnedZones orders 'attackOwnedZone' and will re-direct\\\
-- troops when a zone was captured by interacting with cfxOwnedZones to \\\
-- find the nearest non-owned zone and direct the group there \\\
\\\
-- USAGE\\\
-- Allocate a group in game and issue them marching orders towars a goal \\\
-- then createGroundTroops to allocate a structure used by this \\\
-- module and addTroopsToPool to have them then managed by this \\\
-- module \\\
\\\
cfxGroundTroops.deployedTroops = {} -- indexed by group name \\\
\\\
--[[--\\\
 version history\\\
   1.3.0 - added \\\"wait-\\\" prefix to have toops do nothing \\\
         - added lazing \\\
   1.3.1 - sound for lazing msg is \\\"UI_SCI-FI_Tone_Bright_Dry_20_stereo.wav\\\"\\\
         - lazing --> lasing in text \\\
   1.3.2 - set ups to 2 \\\
   1.4.0 - queued updates except for lazers \\\
   1.4.1 - makeTroopsEngageZone now issues hold before moving on 5 seconds later\\\
         - getTroopReport\\\
           - include size of group \\\
   1.4.2 - uses unitIsInfantry from dcsCommon \\\
   1.5.0 - new scheduled updates per troop to reduce processor load \\\
         - tiebreak code \\\
   1.5.1 - small bugfix in scheduled code \\\
   1.5.2 - checkSchedule \\\
         - speed warning in scheduler\\\
         - go off road when speed warning too much \\\
   1.5.3 - monitor troops \\\
         - managed queue for ground troops \\\
         - on second switch to offroad now removed from MQ\\\
   1.5.4 - removed debugging messages\\\
   1.5.5 - removed bug in troop report reading nil destination \\\
   1.6.0 - check modules \\\
   1.6.1 - troopsCallback management so you can be informed if a \\\
           troop you have added to the pool is dead or has achieved a goal.\\\
           callback will list reasons \\\"dead\\\" and \\\"arrived\\\"\\\
           updateAttackers\\\
   1.6.2 - also accept 'lase' as 'laze', translate directly \\\
   1.7.0 - now can use groundTroopsConfig zone\\\
   1.7.1 - addTroopsDeadCallback() renamed to addTroopsCallback() \\\
         - invokeCallbacksFor also accepts and passes on data block\\\
         - troops is always passed in data block as .troops \\\
   1.7.2 - callback when group is neutralized on guard orders\\\
         - callback when group is being engaged under guard orders \\\
   1.7.3 - callbacks for lase:tracking and lase:stop \\\
   1.7.4 - verbose flag, warnings suppressed \\\
   1.7.5 - some troop.group hardening with isExist()\\\
   1.7.6 - fixed switchToOffroad \\\
   1.7.7 - no longer case sensitive for orders \\\
   1.7.7 - updateAttackers() now inspects 'moving' status and invokes makeTroopsEngageZone\\\
         - makeTroopsEngageZone() sets 'moving' status to true\\\
         - createGroundTroops() sets moving status to false \\\
         - updateZoneAttackers() uses moving  \\\
   1.7.8 - better guards before invoking ownedZones\\\
\\\
  an entry into the deployed troop table has the following attributes\\\
  - group - the group \\\
  - orders: \\\"guard\\\" - will guard the spot and look for enemies in range\\\
            \\\"patrol\\\" - will walk between way points back and forth \\\
            \\\"laze\\\" - will stay in place and try to laze visible vehicles in range\\\
            \\\"attackOwnedZone\\\" - interface to cfxOwnedZones module, seeks out\\\
              enemy zones to attack and capture them\\\
            \\\"wait-<some other orders>\\\" do nothing. the \\\"wait\\\" prefix will be removed some time and <some other order> then revealed. Used at least by heloTroops\\\
            \\\"train\\\" - target dummies. ROE=HOLD, no ground loop \\\
            \\\"attack\\\" - transition to destination, once there, stop and \\\
            switch to guard. requires destination zone be set to a valid cfxZone\\\
  - coalition - the coalition from the group\\\
  - enemy - if set, the group this group it is engaging. this means the group is fighting and not idle\\\
  - name - name of group, dan be freely changed\\\
  - signature - \\\"cfx\\\" to tell apart from dcs groups \\\
  - range = range to look for enemies. default is 300m. In \\\"laze\\\" orders, range to laze\\\
  - lazeTarget - target currently lazing\\\
  - lazeCode - laser code. default is 1688\\\
  - moving - has been given orders to move somewhere already. used for first movement order with attack orders \\\
\\\
 \\\
 usage:\\\
 take a dcs group of ground troops and create a cfx ground troop record with \\\
  createGroundTroops()\\\
 then add this to the manager with \\\
  addGroundTroopsToPool()\\\
 \\\
 you can control what the group is to do by changing the cfx troop attribute orders \\\
 you can install a callback that will notify you if a troop reached a goal or\\\
 was killed with addTroopsCallback() which will also give a reason\\\
 callback pattern is myCallback(reason, theGroup, orders, data) with troop being the \\\
 group, and orders the original orders, and reason a string containing why the \\\
 callback was invoked. Currently defined reasons are\\\
   - \\\"dead\\\" - entire group was killed \\\
   - \\\"arrived\\\" - at least a part of group arrived at destination (only with some orders)\\\
--]]--\\\
\\\
--\\\
-- UPDATE MODELS\\\
-- standard is update all every time: fastest, but may cause \\\
-- performance issues\\\
-- queued will work one every pass (except for lazed), distributing the load much better \\\
-- schedueld installs a callback for each group separately and thus distributes the load over time much better \\\
\\\
cfxGroundTroops.queuedUpdates = false -- set to true to process one group per turn. To work this way, scheduledUpdates must be false \\\
cfxGroundTroops.scheduledUpdates = true -- set to false to allow queing of standard updates. overrides queuedUpdates \\\
cfxGroundTroops.monitorNumbers = false -- set to true to debug managed group size \\\
\\\
cfxGroundTroops.standardScheduleInterval = 30 -- 30 seconds between calls\\\
cfxGroundTroops.guardUpdateInterval = 30 -- every 30 seconds we check up on guards\\\
cfxGroundTroops.trackingUpdateInterval = 0.5 -- 0.5 seconds for lazer tracking etc \\\
\\\
cfxGroundTroops.maxManagedTroops = 67 -- -1 is infinite, any positive number turn on cap on managed troops and palces excess troops in queue \\\
cfxGroundTroops.troopQueue = {} -- FIFO stack \\\
-- return the best tracking interval for this type of orders \\\
\\\
--\\\
-- READ CONFIG ZONE TO OVERRIDE SETTING\\\
--\\\
function cfxGroundTroops.readConfigZone()\\\
    -- note: must match exactly!!!!\\\
    local theZone = cfxZones.getZoneByName(\\\"groundTroopsConfig\\\") \\\
    if not theZone then \\\
        if cfxGroundTroops.verbose then \\\
            trigger.action.outText(\\\"***gndT: NO config zone!\\\", 30) \\\
        end\\\
        theZone = cfxZones.createSimpleZone(\\\"groundTroopsConfig\\\") \\\
    end \\\
        \\\
    -- ok, for each property, load it if it exists\\\
    if cfxZones.hasProperty(theZone, \\\"queuedUpdates\\\")  then \\\
        cfxGroundTroops.queuedUpdates = cfxZones.getBoolFromZoneProperty(theZone, \\\"queuedUpdates\\\", false)\\\
    end\\\
    \\\
    if cfxZones.hasProperty(theZone, \\\"scheduledUpdates\\\")  then \\\
        cfxGroundTroops.scheduledUpdates = cfxZones.getBoolFromZoneProperty(theZone, \\\"scheduledUpdates\\\", false)\\\
    end\\\
    \\\
    if cfxZones.hasProperty(theZone, \\\"maxManagedTroops\\\")  then \\\
        cfxGroundTroops.maxManagedTroops = cfxZones.getNumberFromZoneProperty(theZone, \\\"maxManagedTroops\\\", 65)\\\
    end\\\
    \\\
    if cfxZones.hasProperty(theZone, \\\"monitorNumbers\\\")  then \\\
        cfxGroundTroops.monitorNumbers = cfxZones.getBoolFromZoneProperty(theZone, \\\"monitorNumbers\\\", false)\\\
    end\\\
    \\\
    if cfxZones.hasProperty(theZone, \\\"standardScheduleInterval\\\")  then \\\
        cfxGroundTroops.standardScheduleInterval = cfxZones.getNumberFromZoneProperty(theZone, \\\"standardScheduleInterval\\\", 30)\\\
    end\\\
    \\\
    if cfxZones.hasProperty(theZone, \\\"guardUpdateInterval\\\")  then \\\
        cfxGroundTroops.guardUpdateInterval = cfxZones.getNumberFromZoneProperty(theZone, \\\"guardUpdateInterval\\\", 30)\\\
    end\\\
    \\\
    if cfxZones.hasProperty(theZone, \\\"trackingUpdateInterval\\\")  then \\\
        cfxGroundTroops.trackingUpdateInterval = cfxZones.getNumberFromZoneProperty(theZone, \\\"trackingUpdateInterval\\\", 0.5)\\\
    end\\\
    \\\
    if cfxZones.hasProperty(theZone, \\\"verbose\\\")  then \\\
        cfxGroundTroops.verbose = cfxZones.getBoolFromZoneProperty(theZone, \\\"verbose\\\", false)\\\
    end\\\
\\\
    if cfxGroundTroops.verbose then \\\
        trigger.action.outText(\\\"+++gndT: read config zone!\\\", 30) \\\
    end\\\
end\\\
\\\
\\\
-- \\\
-- Callback handling\\\
--\\\
\\\
cfxGroundTroops.troopsCallback = {}\\\
\\\
function cfxGroundTroops.addTroopsCallback(theCallback)\\\
    table.insert(cfxGroundTroops.troopsCallback, theCallback)\\\
end\\\
\\\
function cfxGroundTroops.invokeCallbacksFor(reason, troops, data)\\\
    if not data then data = {} end\\\
    data.troops = troops \\\
    for idx, theCB in pairs (cfxGroundTroops.troopsCallback) do \\\
        theCB(reason, troops.group, troops.orders, data)\\\
    end\\\
end\\\
\\\
function cfxGroundTroops.getScheduleInterval(orders)\\\
    if orders == \\\"laze\\\" then \\\
        return cfxGroundTroops.trackingUpdateInterval\\\
    end\\\
    return cfxGroundTroops.standardScheduleInterval\\\
end\\\
\\\
-- create controller commands to attack a group \\\"enemies\\\"\\\
-- enemies are an attribute of the troop structure\\\
-- usually called from a group on guard when idling \\\
function cfxGroundTroops.makeTroopsEngageEnemies(troop)\\\
    local group = troop.group\\\
    if not Group.isExist(group) then \\\
        trigger.action.outText(\\\"+++gndT: troup don't exist, dropping\\\", 30)\\\
        return \\\
    end\\\
    \\\
    local enemies = troop.enemy\\\
    local from = dcsCommon.getGroupLocation(group)\\\
    if not from then return end -- the commandos died\\\
    local there = dcsCommon.getGroupLocation(enemies)\\\
    if not there then return end\\\
    \\\
    -- we lerp to 2/3 of enemy location\\\
    there = dcsCommon.vLerp(from, there, 0.66) \\\
    \\\
    local speed = 10 -- m/s = 10 km/h -- wait. 10 m/s is 36 km/h \\\
    cfxCommander.makeGroupGoThere(group, there, speed)\\\
    local attask = cfxCommander.createAttackGroupCommand(enemies)\\\
    cfxCommander.scheduleTaskForGroup(group, attask, 0.5)\\\
    troop.moving = true \\\
end\\\
\\\
-- make the troops engage a cfxZone passed in the destination \\\
-- attribute \\\
function cfxGroundTroops.makeTroopsEngageZone(troop)\\\
    local group = troop.group\\\
    if not group:isExist() then \\\
        trigger.action.outText(\\\"+++gndT: make troops engage zone: troops do not exist, exiting\\\", 30)\\\
        return \\\
    end\\\
    \\\
    local enemyZone = troop.destination -- must be cfxZone \\\
    local from = dcsCommon.getGroupLocation(group)\\\
    if not from then return end -- the group died\\\
    local there = enemyZone.point -- access zone position\\\
    if not there then return end\\\
        \\\
    local speed = 14 -- m/s; 10 m/s = 36 km/h\\\
    \\\
    -- make troops stop in 1 second, then start in 5 seconds to give AI respite \\\
    cfxCommander.makeGroupHalt(group, 1) -- 1 second delay\\\
    cfxCommander.makeGroupGoTherePreferringRoads(group, there, speed, 5)\\\
\\\
    -- remember that we have issued a move order \\\
    troop.moving = true     \\\
end\\\
\\\
function cfxGroundTroops.switchToOffroad(troops)\\\
    -- we may need to test if we already did this, \\\
    -- but not for now \\\
    \\\
    -- this is called when troops are stuck \\\
    -- on their route for longer than allowed\\\
    -- we now force a direct approach \\\
    local group = troops.group\\\
    if not group:isExist() then \\\
        return\\\
    end \\\
    \\\
    local enemies = troops.destination\\\
    local from = dcsCommon.getGroupLocation(group)\\\
    if not from then return end -- the commandos died\\\
    local there = enemies.point\\\
    if not there then return end\\\
        \\\
    local speed = 14 -- m/s; 10 m/s = 36 km/h\\\
    \\\
    cfxCommander.makeGroupHalt(group, 0) -- no delay, halt now\\\
    cfxCommander.makeGroupGoThere(group, there, speed, \\\"Off Road\\\", 5)\\\
    \\\
    troops.lastOrderDate = timer.getTime()\\\
    troops.speedWarning = 0\\\
end\\\
\\\
--\\\
-- update loop for troops that have 'attackOwnedZones' as \\\
-- their orders\\\
-- if they have no destination zone, or the zone they are \\\
-- are heading for is already owned by their side, then look for \\\
-- the closest enemy zone, and cut attack orders to move there \\\
function cfxGroundTroops.getClosestEnemyZone(troop)\\\
    local p = dcsCommon.getGroupLocation(troop.group)\\\
    local tempZone = cfxZones.createSimpleZone(\\\"tz\\\", p, 100)\\\
    tempZone.owner = troop.side\\\
    local newTarget = cfxOwnedZones.getNearestEnemyOwnedZone(tempZone, true) -- 'true' will also target neutral zones \\\
    return newTarget\\\
end\\\
\\\
function cfxGroundTroops.updateZoneAttackers(troop)\\\
    if not troop then return end \\\
    if not cfxOwnedZones then \\\
        trigger.action.outText(\\\"+++gndT: update zone attackers requires ownedZones\\\", 30)\\\
        return \\\
    end\\\
    troop.insideDestination = false -- mark as not inside \\\
    \\\
    local newTargetZone = cfxGroundTroops.getClosestEnemyZone(troop)\\\
    if not newTargetZone then\\\
        -- all target zones are friendly, go to guard mode\\\
        troop.orders = \\\"guard\\\"\\\
        return \\\
    end\\\
    \\\
    if newTargetZone ~= troop.destination then \\\
        troop.destination = newTargetZone \\\
        cfxGroundTroops.makeTroopsEngageZone(troop)\\\
        troop.lastOrderDate = timer.getTime()\\\
        troop.speedWarning = 0\\\
        return\\\
    end\\\
    \\\
    -- if we get here, we should be under way to our nearest enemy zone\\\
    if not troop.moving then \\\
        cfxGroundTroops.makeTroopsEngageZone(troop)\\\
        return \\\
    end \\\
    \\\
    -- if we get here, we are under way to troop.destination\\\
    -- check if we are inside the zone, and if so, set variable to true \\\
    local p = dcsCommon.getGroupLocation(troop.group)\\\
    troop.insideDestination = cfxZones.isPointInsideZone(p, troop.destination)\\\
    \\\
    -- if we get here, we need no change \\\
    \\\
end\\\
\\\
-- attackers simply travel to their destination (zone), and then switch to \\\
-- guard orders once they arrive \\\
function cfxGroundTroops.updateAttackers(troop) \\\
    if not troop then return end \\\
    if not troop.destination then return end \\\
    if not troop.group:isExist() then return end \\\
    \\\
    -- if we are not moving, we need to issue move oders now\\\
    -- this can happen if previously, there was a 'wait' command \\\
    -- and this now was removed so we end up in the method \\\
    if not troop.moving then \\\
        cfxGroundTroops.makeTroopsEngageZone(troop)\\\
        return \\\
    end \\\
    \\\
    \\\
    if cfxZones.isGroupPartiallyInZone(troop.group, troop.destination) then\\\
        -- we have arrived\\\
        -- we could now also initiate a general callback with reason\\\
        cfxGroundTroops.invokeCallbacksFor(\\\"arrived\\\", troop)\\\
        troop.orders = \\\"guard\\\"\\\
        return \\\
    end\\\
    \\\
    \\\
--    if we get here, we need no change \\\
end\\\
\\\
-- update loop for a group that has \\\"guard\\\" orders.\\\
-- basically it stands around and looks for enemies \\\
-- until it finds a group, and then engages the enemy\\\
-- when engaged, it is not looking for other enemies\\\
-- 'engaged' means that the troop.enemy attribute is set\\\
 \\\
function cfxGroundTroops.updateGuards(troop)\\\
    if not troop.group:isExist() then \\\
        return \\\
    end \\\
    \\\
    local theEnemy = troop.enemy\\\
    if theEnemy then \\\
        -- see if enemy is dead \\\
        if not dcsCommon.isGroupAlive(theEnemy) then \\\
            troop.enemy = nil\\\
            -- yup, zed's dead. next time around, we won't be checking this again\\\
            trigger.action.outText(troop.name .. \\\" has neutralized enemy forces\\\", 30)\\\
            --DONE: invoke callback for defeating troops\\\
            local data = {}\\\
            data.enemy = theEnemy\\\
            cfxGroundTroops.invokeCallbacksFor(\\\"neutralized\\\", troop, data)\\\
            return\\\
        end\\\
        -- yes, we are still engaged\\\
        return \\\
    end\\\
    \\\
    -- we are currently unengaged. look for an enemy\\\
    if not troop.range then troop.range = 300 end\\\
    troop.coalition = troop.group:getCoalition()\\\
    local enemyCoal = dcsCommon.getEnemyCoalitionFor(troop.coalition)\\\
    local cat = Group.Category.GROUND\\\
    local p = dcsCommon.getGroupLocation(troop.group)\\\
    local enemies, enemyDist = dcsCommon.getClosestLivingGroupToPoint(p, enemyCoal, cat) \\\
    local maxRange = troop.range -- meters \\\
    -- if we have enemies then schedule a path to go there\\\
    if enemies and (enemyDist < maxRange) then \\\
        troop.enemy = enemies\\\
        --timer.scheduleFunction(cfxGroundTroops.makeGroupEngageEnemies, troop, timer.getTime() + 1.0)\\\
        cfxGroundTroops.makeTroopsEngageEnemies(troop)\\\
        trigger.action.outText(troop.name .. \\\" is engaging enemy forces at range \\\" .. math.floor(enemyDist) .. \\\"meters\\\", 30)\\\
        --DONE: invoke callback for engaging troops, pass data \\\
        local data = {}\\\
        data.enemy = enemies\\\
        cfxGroundTroops.invokeCallbacksFor(\\\"engaging\\\", troop, data)\\\
    elseif enemies then \\\
        --trigger.action.outText(troop.name .. \\\" enemiy out of range: \\\" .. math.floor(enemyDist) .. \\\"meters\\\", 30)\\\
    else \\\
        --trigger.action.outText(troop.name .. \\\" no enemies\\\", 30)\\\
    end\\\
end\\\
\\\
--\\\
-- update loop for units that laze targets.\\\
-- they can only laze if they are alive, but update \\\
-- will take care of that, so when we are here, there \\\
-- is at least one of them alive\\\
-- \\\
\\\
function cfxGroundTroops.findLazeTarget(troop)\\\
    local here = troop.group:getUnit(1):getPoint()\\\
    troop.coalition = troop.group:getCoalition()\\\
    local enemyCoal = dcsCommon.getEnemyCoalitionFor(troop.coalition)\\\
    --local enemySide = dcsCommon.getEnemyCoalitionFor(troop.side)\\\
    local cat = Group.Category.GROUND\\\
    local enemyGroups = dcsCommon.getLivingGroupsAndDistInRangeToPoint(here, troop.range, enemyCoal, cat) \\\
    -- we now have a list of possible targets in range\\\
    if #enemyGroups < 1 then     \\\
        -- no targets in range\\\
        return nil \\\
    end\\\
\\\
    here = {x = here.x, y = here.y + 2.0, z = here.z} -- raise by 2.0m\\\
    \\\
    -- iterate through the list until we find the first target \\\
    -- that fits the bill and return it\\\
--    trigger.action.outText(\\\"+++ looking at \\\" .. #enemyGroups .. \\\" laze groups\\\", 30)\\\
    for i=1, #enemyGroups do    \\\
        -- get all units for this group \\\
        local aGroup = enemyGroups[i].group -- remember, they are in a {dist, group} tuple\\\
        local theUnits = aGroup:getUnits()\\\
        -- iterate all units \\\
        for udx, aUnit in pairs(theUnits) do \\\
            if (aUnit:isExist() and aUnit:getLife() > 1) then \\\
                -- unit lives \\\
                -- now, we need to filter infantry. we do this by \\\
                -- pre-fetching the typeString\\\
                --troop.lazeTargetType = aUnit:getTypeName()\\\
                -- and checking if the name contains some infantry-\\\
                -- typical strings. Idea taken from JTAC script \\\
                local isInfantry =  dcsCommon.unitIsInfantry(theUnit)\\\
    \\\
                \\\
                if not isInfantry then \\\
                    -- this is a vehicle, is it in line of sight?\\\
                    -- raise the point 2m above ground for both points\\\
                    -- as done in jtac script\\\
                    local there = aUnit:getPoint()  \\\
                    there = {x = there.x, y = there.y + 2.0, z = there.z}\\\
                   \\\
                    if land.isVisible(here, there) then \\\
                        -- we found a visible vehicle in \\\
                        -- the nearest group to us in range \\\
                        -- that is visible!\\\
                        return aUnit\\\
                    else \\\
                        --trigger.action.outText(\\\"+++ \\\".. aUnit:getName() ..\\\"cant be seen\\\", 30)\\\
                    end -- if visible\\\
                else \\\
                    -- trigger.action.outText(\\\"+++ \\\".. aUnit:getName() ..\\\" (\\\".. troop.lazeTargetType .. \\\") is infantry\\\", 30)\\\
                end -- if not infantry \\\
            end -- if alive \\\
        end -- for all units\\\
    end -- for all enemy groups\\\
    --trigger.action.outText(\\\"+++ find nearest laze target did not find anything to laze\\\", 30)\\\
    return nil -- no unit found \\\
end\\\
\\\
function cfxGroundTroops.lazerOff(troop)\\\
    if troop.lazerPointer then \\\
        troop.lazerPointer:destroy()\\\
    end\\\
    troop.lazerPointer = nil \\\
    troop.lazingUnit = nil \\\
end\\\
\\\
function cfxGroundTroops.trackLazer(troop)\\\
    -- the only thing that must be set when entering here is\\\
    -- lazeTarget. We set up the rest\\\
    if not troop.lazingUnit then \\\
        troop.lazingUnit = troop.group:getUnit(1) -- get first unit\\\
        if troop.lazingUnit:getLife() < 1 then \\\
            trigger.action.outText(\\\"+++ LazingUnit is dead, getUnit works differently from what docs say, need to filter for lively units\\\", 30)\\\
        end\\\
    end\\\
    \\\
    if not troop.lazerPointer then\\\
        local there = troop.lazeTarget:getPoint()\\\
        troop.lazerPointer = Spot.createLaser(troop.lazingUnit,{x = 0, y = 2, z = 0}, there, 1688)\\\
        troop.lazeTargetType = troop.lazeTarget:getTypeName()\\\
        trigger.action.outTextForCoalition(troop.side, troop.name .. \\\" tally target - lasing \\\" .. troop.lazeTargetType .. \\\"!\\\", 30)\\\
         trigger.action.outSoundForCoalition(troop.side, \\\"UI_SCI-FI_Tone_Bright_Dry_20_stereo.wav\\\")\\\
        troop.lastLazerSpot = there -- remember last spot\\\
        local data = {}\\\
        data.enemy = troop.lazeTarget\\\
        data.tracker = troop.lazingUnit\\\
        cfxGroundTroops.invokeCallbacksFor(\\\"lase:tracking\\\", troop, data)\\\
        return\\\
    end\\\
    \\\
    -- if true then return end \\\
    \\\
    -- if we get here, we update the lazerPointer\\\
    local there = troop.lazeTarget:getPoint()\\\
    -- we may only want to update the laser spot when dist > trigger\\\
    troop.lazerPointer:setPoint(there)\\\
    -- we may want to report dist\\\
    troop.lastLazerSpot = there\\\
end\\\
\\\
function cfxGroundTroops.updateLaze(troop)\\\
    -- check if we have a laze target. \\\
    -- check if lazing unit was killed, and therefore lost target\\\
    if troop.lazingUnit then \\\
        -- check that unit still alive\\\
        if troop.lazingUnit:isExist() and \\\
        troop.lazingUnit:getLife() >= 1 then\\\
        else \\\
            cfxGroundTroops.lazerOff(troop)\\\
            troop.lazeTarget = nil\\\
            trigger.action.outTextForCoalition(troop.side, troop.name .. \\\" reports lasing \\\" .. troop.lazeTargetType .. \\\" interrupted. Re-acquiring.\\\", 30)\\\
            trigger.action.outSoundForCoalition(troop.side, \\\"UI_SCI-FI_Tone_Bright_Dry_20_stereo.wav\\\")\\\
            troop.lazingUnit = nil \\\
            cfxGroundTroops.invokeCallbacksFor(\\\"lase:stop\\\", troop)\\\
            return -- we'll re-acquire through a new unit next round\\\
        end\\\
    end\\\
    \\\
    -- if we get here, a lazing unit \\\
    --local here = troop.lazingUnit:getPoint()\\\
    \\\
    if troop.lazeTarget then \\\
        -- check if that target is alive and in range\\\
        if troop.lazeTarget:isExist() and troop.lazeTarget:getLife() >= 1 then\\\
            -- note: when we laze a target, we know that we have a lazing unit\\\
            local here = troop.lazingUnit:getPoint()\\\
            -- check if it has moved out of range \\\
            local there = troop.lazeTarget:getPoint()\\\
            if dcsCommon.dist(here, there) > troop.range then \\\
                -- troop out of range\\\
                trigger.action.outTextForCoalition(troop.side, troop.name .. \\\" lost sight of lazed target \\\" .. troop.lazeTargetType, 30)\\\
                trigger.action.outSoundForCoalition(troop.side, \\\"UI_SCI-FI_Tone_Bright_Dry_20_stereo.wav\\\")\\\
                troop.lazeTarget = nil\\\
                cfxGroundTroops.lazerOff(troop)\\\
                troop.lazingUnit = nil\\\
                cfxGroundTroops.invokeCallbacksFor(\\\"lase:stop\\\", troop)\\\
                return \\\
            end\\\
            \\\
            -- if we get here, we need to update the target point \\\
            cfxGroundTroops.trackLazer(troop)\\\
            return\\\
        else\\\
            -- target died\\\
            trigger.action.outTextForCoalition(troop.side, troop.name .. \\\" confirms kill for \\\" .. troop.lazeTargetType, 30)\\\
            trigger.action.outSoundForCoalition(troop.side, \\\"UI_SCI-FI_Tone_Bright_Dry_20_stereo.wav\\\")\\\
            troop.lazeTarget = nil\\\
            cfxGroundTroops.lazerOff(troop)\\\
            troop.lazingUnit = nil\\\
            cfxGroundTroops.invokeCallbacksFor(\\\"lase:stop\\\", troop)\\\
            return\\\
        end        \\\
    end\\\
    \\\
    -- if we get here, we must look for a laze target \\\
    troop.lazeTarget = cfxGroundTroops.findLazeTarget(troop)\\\
    if troop.lazeTarget then \\\
        cfxGroundTroops.trackLazer(troop) -- will also set up lazing unit \\\
    end\\\
end\\\
\\\
\\\
function cfxGroundTroops.updateWait(troop)\\\
    -- currently nothing to do\\\
    \\\
end\\\
\\\
function cfxGroundTroops.updateTroops(troop)\\\
    -- if orders start with \\\"wait-\\\" then the troops \\\
    -- simply do nothing\\\
    if dcsCommon.stringStartsWith(troop.orders, \\\"wait-\\\") then\\\
        -- the troops are waiting to be picked update\\\
        -- when they are dropped again, thre prefix to \\\
        -- their order is removed, and the 'real' orders \\\
        -- are revealed. For now, do nothing\\\
        cfxGroundTroops.updateWait(troop)\\\
    --REMEMBER: LOWER CASE ONLY!\\\
    elseif troop.orders == \\\"guard\\\" then \\\
        cfxGroundTroops.updateGuards(troop)\\\
    \\\
    elseif troop.orders == \\\"attackownedzone\\\" then \\\
        cfxGroundTroops.updateZoneAttackers(troop)\\\
\\\
    elseif troop.orders == \\\"laze\\\" then \\\
        cfxGroundTroops.updateLaze(troop)\\\
    \\\
    elseif troop.orders == \\\"attackzone\\\" then \\\
        cfxGroundTroops.updateAttackers(troop)\\\
        \\\
    else \\\
        trigger.action.outText(\\\"+++ updated troops \\\" .. troop.name .. \\\" have unknown orders \\\" .. troop.orders, 30)\\\
    end\\\
    \\\
end\\\
\\\
--\\\
-- we have to systems to process during update: \\\
-- once all, and one per turn, with the exception \\\
-- of lazers, who get updated every turn\\\
-- \\\
\\\
--\\\
-- all at once \\\
--\\\
function cfxGroundTroops.update()\\\
    cfxGroundTroops.updateSchedule = timer.scheduleFunction(cfxGroundTroops.update, {}, timer.getTime() + 1/cfxGroundTroops.ups)\\\
    -- iterate all my troops and build next \\\
    -- versions pool\\\
    local liveTroops = {} -- filtered table, indexed by name \\\
    for idx, troop in pairs(cfxGroundTroops.deployedTroops) do \\\
        local group = troop.group \\\
        if not dcsCommon.isGroupAlive(group) then \\\
            -- group dead. remove from pool\\\
            -- this happens by not copying it into the poos\\\
            cfxGroundTroops.invokeCallbacksFor(\\\"dead\\\", troop) -- notify anyone who is interested that we are no longer proccing these \\\
        else \\\
            -- work with this groop according to its orders\\\
            cfxGroundTroops.updateTroops(troop)\\\
            -- since group is alive remember it for next loop\\\
            liveTroops[idx] = troop -- do NOT use insert as we have indexed table by name\\\
        end\\\
    end\\\
    -- liveTroops holds all troops that are still alive and will\\\
    -- be revisited next loop\\\
    cfxGroundTroops.deployedTroops = liveTroops\\\
end\\\
\\\
--\\\
-- UpdateQueued looks for the first unordered (.receivedOrders == false) group\\\
-- and processes them. if orders are 'laze', it will always be ordered \\\
--\\\
\\\
\\\
function cfxGroundTroops.updateQueued()\\\
    cfxGroundTroops.updateSchedule = timer.scheduleFunction(cfxGroundTroops.updateQueued, {}, timer.getTime() + 1/cfxGroundTroops.ups)\\\
    -- iterate all my troops and build next \\\
    -- versions pool\\\
    local liveTroops = {}\\\
    local hasOrdered = false -- so far, no orders have been given \\\
    for idx, troop in pairs(cfxGroundTroops.deployedTroops) do \\\
        local group = troop.group \\\
        if not dcsCommon.isGroupAlive(group) then \\\
            -- group dead. remove from pool\\\
            -- this happens by not copying it to liveTroops \\\
            -- trigger.action.outText(\\\"+++ removing ground troops \\\" .. troop.name, 30)\\\
            cfxGroundTroops.invokeCallbacksFor(\\\"dead\\\", troop) -- notify anyone who is interested that we are no longer proccing these \\\
        else \\\
            -- check if this is a lazer \\\
            if troop.orders == \\\"laze\\\" then \\\
                -- lazers are updated each turn \\\
                cfxGroundTroops.updateLaze(troop)\\\
            else \\\
                if not hasOrdered and not (troop.receivedOrders) then \\\
                -- work with this groop according to its orders\\\
                cfxGroundTroops.updateTroops(troop)\\\
                troop.receivedOrders = true -- this one has received orders \\\
                hasOrdered = true \\\
                end \\\
            end\\\
            liveTroops[idx] = troop -- do NOT use insert as we have indexed table\\\
        end\\\
    end\\\
    -- liveTroops holds all troops that are still alive and will\\\
    -- be revisited next loop\\\
    cfxGroundTroops.deployedTroops = liveTroops\\\
    \\\
    -- if no orders have been passed, clear all troop's .receivedOrders flag \\\
    -- and the loop starts anew next loop \\\
    if not hasOrdered then \\\
        for idx, troop in pairs(cfxGroundTroops.deployedTroops) do\\\
            troop.receivedOrders = nil  \\\
        end\\\
    end\\\
end\\\
\\\
--\\\
-- in updateCheckOnly we simply check the ground queue \\\
-- if there are troops added that need scheduling (i.e. have \\\
-- been passed in by addTroops and schedule them \\\
--\\\
function cfxGroundTroops.updateCheckOnly()\\\
    -- re-schedule myself in 1 second \\\
    timer.scheduleFunction(cfxGroundTroops.updateCheckOnly, {}, timer.getTime() + 1)\\\
    \\\
    -- iterate through all troops, and \\\
    -- see if there are any that have not been scheduled \\\
    -- to schedule them for updates in 1 second\\\
    -- that will be the first time that they are scheduled,\\\
    -- all others will be self-scheduled \\\
    for idx, troop in pairs(cfxGroundTroops.deployedTroops) do \\\
        if not troop.hasBeenScheduled then \\\
            local params = {troop}\\\
            troop.hasBeenScheduled = true \\\
            troop.updateID = timer.scheduleFunction(cfxGroundTroops.updateSingleScheduled, params, timer.getTime() + 1)\\\
            --trigger.action.outText(\\\"+++groundT: scheduling troops <\\\".. troop.group:getName() ..\\\"> with orders <\\\" .. troop.orders .. \\\">\\\", 30)\\\
        end\\\
    end\\\
    -- note that alive checks are now done during the scheduled\\\
    -- update, not every time for all\\\
\\\
end\\\
\\\
function cfxGroundTroops.updateSingleScheduled(params)\\\
    local troops = params[1]\\\
    troops.updateID = nil -- erase update id \\\
    if not troops then \\\
        trigger.action.outText(\\\"+++groundT WARNING: nil troop in updateSingle\\\", 30)\\\
        return -- no further action required, no longer updates\\\
    end\\\
    \\\
    local group = troops.group \\\
    -- see if we have been taken out of the pool or updated\\\
    -- if so, exit \\\
    \\\
    if not group:isExist() then \\\
        -- simply never again look at it. \\\
        return \\\
    end\\\
    \\\
    if cfxGroundTroops.deployedTroops[troops.group:getName()] ~= troops then \\\
        -- trigger.action.outText(\\\"+++groundT NOTE: troops <\\\".. troops.group:getName() ..\\\"> was removed from pool. Cancel Update\\\", 30)\\\
        return -- no further reschedule\\\
    end\\\
    \\\
    -- see if scheduling is turned off\\\
    if not troops.reschedule then \\\
        trigger.action.outText(\\\"+++groundT NOTE: no longer updating <\\\".. troops.group:getName() ..\\\"> per reschedule param\\\", 30)\\\
        return \\\
    end\\\
    \\\
    -- now, check if still alive \\\
    if not dcsCommon.isGroupAlive(group) then \\\
        -- group dead, no longer updates \\\
        --trigger.action.outText(\\\"+++groundT NOTE: <\\\".. troops.group:getName() ..\\\"> dead, removing\\\", 30)\\\
        cfxGroundTroops.invokeCallbacksFor(\\\"dead\\\", troops) -- notify anyone who is interested that we are no longer proccing these \\\
        cfxGroundTroops.removeTroopsFromPool(troops)\\\
        return -- nothing else to do\\\
    end\\\
    \\\
    -- now, execute the update itself, standard update \\\
    --trigger.action.outText(\\\"+++groundT: singleU troop <\\\".. troops.group:getName() ..\\\"> with orders <\\\" .. troops.orders .. \\\">\\\", 30)\\\
    cfxGroundTroops.updateTroops(troops)\\\
    \\\
    -- check max speed of group. if < 0.1 then note and increase \\\
    -- speedWarning. if not, reset speed warning \\\
    if troops.orders == \\\"attackownedzone\\\" and dcsCommon.getGroupMaxSpeed(troops.group) < 0.1 then \\\
        if not troops.speedWarning then troops.speedWarning = 0 end\\\
        troops.speedWarning = troops.speedWarning + 1\\\
    else\\\
        troops.speedWarning = 0 -- reset\\\
    end\\\
    \\\
    if troops.speedWarning > 5 then -- make me 5\\\
        lastOrder = timer.getTime() - troops.lastOrderDate \\\
        --trigger.action.outText(\\\"+++groundT WARNING: <\\\".. troops.group:getName() ..\\\"> (S:\\\".. troops.side .. \\\") to \\\" .. troops.destination.name .. \\\": stopped for \\\" .. troops.speedWarning .. \\\" iters, orderage=\\\" .. lastOrder, 30)\\\
        -- this may be a matter of too many waypoints. \\\
        -- maybe issue orders to go to their destination directly?\\\
        -- now force an order to go directly.\\\
        if troops.speedWarning > 5 then \\\
            if troops.isOffroad then \\\
                -- we already switched to off-road. take me \\\
                -- out of the managed queue, I'm not going \\\
                -- anywhere\\\
                -- trigger.action.outText(\\\"+++groundT <\\\".. troops.group:getName() ..\\\"> is going nowhere. Removed from managed troops\\\", 30)\\\
                cfxGroundTroops.removeTroopsFromPool(troops)\\\
            else \\\
                cfxGroundTroops.switchToOffroad(troops)\\\
                -- trigger.action.outText(\\\"+++groundT <\\\".. troops.group:getName() ..\\\"> SWITCHED TO OFFROAD\\\", 30)\\\
                troops.isOffroad = true -- so we know that we already did that\\\
            end\\\
        end \\\
    end\\\
    \\\
    -- now reschedule updte for my best time \\\
    local updateTime = cfxGroundTroops.getScheduleInterval(troops.orders)\\\
    troops.updateID = timer.scheduleFunction(cfxGroundTroops.updateSingleScheduled, params, timer.getTime() + updateTime)\\\
end\\\
\\\
\\\
--\\\
-- PILEUP and TIE BRAKERS\\\
--\\\
-- there may come a situation where troops gather in \\\
-- one zone because the zone isn't won - some other troops \\\
-- are there and noone moves. \\\
-- a tie-break is required\\\
--\\\
\\\
-- checkpile up: every so often, we test if we have run into a \\\
-- pileup-situation. this happens if there are more than n \\\
-- units with group-attacker order in the same zone, and that \\\
-- zone is their destination \\\
-- this can be easily detected by the insideDestination flag \\\
-- checkPileUp should be run every minute or so \\\
 \\\
function cfxGroundTroops.checkPileUp()\\\
    -- schedule my next call \\\
    --trigger.action.outText(\\\"+++groundT: pileup check\\\", 30)\\\
    timer.scheduleFunction(cfxGroundTroops.checkPileUp, {}, timer.getTime() + 60)\\\
    local thePiles = {}\\\
    if not cfxOwnedZones then \\\
        -- trigger.action.outText(\\\"+++groundT: pileUp - owned zones not yet ready\\\", 30)\\\
        return \\\
    end\\\
    \\\
    -- create a list of all piles \\\
    for idx, oz in pairs(cfxOwnedZones.zones) do \\\
        local newPile = {}\\\
        newPile[1] = 0 -- no red inZone here \\\
        newPile[2] = 0 -- no blue inZone here \\\
        newPile.zone = oz -- the zone we are looking at \\\
        thePiles[oz] = newPile \\\
    end\\\
    \\\
    -- now iterate through all currently alive groups and \\\
    -- attribute them to their piles \\\
    for idx, troop in pairs(cfxGroundTroops.deployedTroops) do \\\
        -- get each group and count them if they are inside\\\
        -- their destination \\\
        if troop.insideDestination and troop.group:isExist() then\\\
            local side = troop.group:getCoalition()\\\
            local thePile = thePiles[troop.destination]\\\
            local theSide = troop.group:getCoalition()\\\
            thePile[theSide] = thePile[theSide] + 1 -- we count groups, not units  \\\
        end\\\
    end\\\
    \\\
    -- a pileup happens, if there are more than 3 groups in destination zone\\\
    -- with NO other troops present (usually the case)\\\
    -- or when there are 5 groups more than the number for the other side \\\
    -- so now scan all piles\\\
    for idx, thePile in pairs(thePiles) do \\\
        -- check red pileup \\\
        if thePile[1] > 3 and thePile[2] == 0 then \\\
            -- simple pileup. 3 groups, no others except defenders and \\\
            -- perhaps transients \\\
            cfxGroundTroops.breakTie(thePile, 1)\\\
        elseif thePile[1] >= thePile[2] + 5 then \\\
            -- numerical pileup \\\
            cfxGroundTroops.breakTie(thePile, 1)\\\
        end\\\
        \\\
        -- check blue loside \\\
        if thePile[2] >= 3 and thePile[1] == 0 then \\\
            -- simple pileup. 3 groups, no others except defenders and \\\
            -- perhaps transients \\\
            cfxGroundTroops.breakTie(thePile, 2)\\\
        elseif thePile[2] >= thePile[1] + 5 then \\\
            -- numerical pileup \\\
            cfxGroundTroops.breakTie(thePile, 2)\\\
        end\\\
    end\\\
end\\\
\\\
function cfxGroundTroops.breakTie(thePile, winner)\\\
    trigger.action.outText(\\\"+++ groundT: TIEBREAK - winner is \\\" .. winner .. \\\" in zone \\\" .. thePile.zone.name .. \\\": \\\" .. thePile[1] .. \\\":\\\" .. thePile[2] , 30)\\\
    -- now add some code to do the actual tie breaking: remove all units that \\\
    -- are inside the zone and who belong to the other side \\\
    local loser = 1 -- red default \\\
    local theZone = thePile.zone \\\
    if winner == 1 then loser = 2 end \\\
    -- now get all ground groups for the losing side\\\
    local losingGround = coalition.getGroups(loser, Group.Category.GROUND)\\\
    for idx, theGroup in pairs(losingGround) do \\\
        -- if alive, check if inside the zone \\\
        if theGroup:isExist() and dcsCommon.isGroupAlive(theGroup) then \\\
            -- make sure it's not a transient\\\
            if not isDeployedGroundTroop(theGroup) then \\\
                local p = dcsCommon.getGroupLocation(theGroup) \\\
                if cfxZones.isPointInsideZone(p, theZone) then \\\
                    trigger.action.outText(\\\"+++ groundT: TIEBREAK - destroying group \\\" .. theGroup:getName() , 30)\\\
                    -- we delete this group now\\\
                    theGroup:destroy()\\\
                end\\\
            end\\\
        end\\\
    end\\\
end\\\
\\\
--\\\
-- sanity checks for rescheduling\\\
--\\\
function cfxGroundTroops.checkSchedules()\\\
    timer.scheduleFunction(cfxGroundTroops.checkSchedules, {}, timer.getTime() + 10)\\\
    for idx, troop in pairs(cfxGroundTroops.deployedTroops) do\\\
        -- check if troop is not scheduled \\\
        -- if this happens to a group more than a certain times,\\\
        -- it has somehow dropped out of the reschedule \\\
        -- plan and needs to be scheduled \\\
        if troop.updateID == nil then \\\
            troop.unscheduleCount = troop.unscheduleCount + 1\\\
            if (troop.unscheduleCount > 1) and troop.group:isExist() then \\\
                trigger.action.outText(\\\"+++ groundT: unscheduled group  \\\" .. troop.group:getName() .. \\\" cnt=\\\" .. troop.unscheduleCount , 30)\\\
            end \\\
        end\\\
    end\\\
end\\\
\\\
--\\\
-- REPORTING \\\
--\\\
-- \\\
-- get a report of troops as string \\\
-- \\\
function cfxGroundTroops.getTroopReport(theSide, ignoreInfantry)\\\
    if not ignoreInfantry then ignoreInfantry = false end \\\
    local report = \\\"GROUND FORCES REPORT\\\"\\\
    for idx, troop in pairs(cfxGroundTroops.deployedTroops) do \\\
        if troop.side == theSide and troop.group:isExist() then \\\
            local unitNum = troop.group:getSize()\\\
            report = report .. \\\"\\\\n\\\" .. troop.name .. \\\" (\\\".. unitNum ..\\\"): <\\\" .. troop.orders .. \\\">\\\" \\\
            if troop.orders == \\\"attackownedzone\\\" then \\\
                if troop.destination then     \\\
                    report = report .. \\\" move towards \\\" .. troop.destination.name \\\
                else \\\
                    report = report .. \\\" (selecting destination)\\\"\\\
                end\\\
            end\\\
        end\\\
    end\\\
    report = report .. \\\"\\\\n---END REPORT\\\\n\\\"\\\
    return report \\\
end\\\
\\\
\\\
--\\\
-- CREATE / ADD / REMOVE \\\
--\\\
\\\
--\\\
-- createGroundTroop\\\
-- use this to create a cfxGroundTroops from a dcs group\\\
--\\\
function cfxGroundTroops.createGroundTroops(inGroup, range, orders) \\\
    local newTroops = {}\\\
    if not orders then \\\
        orders = \\\"guard\\\" \\\
    end\\\
    if orders:lower() == \\\"lase\\\" then \\\
        orders = \\\"laze\\\" -- we use WRONG spelling here, cause we're cool. yeah, right.\\\
    end\\\
    newTroops.insideDestination = false\\\
    newTroops.unscheduleCount = 0 -- will count up as we aren't scheduled\\\
    newTroops.speedWarning = 0\\\
    newTroops.isOffroad = false -- if true, we switched to direct orders, not roads, after standstill\\\
    newTroops.group = inGroup\\\
    newTroops.orders = orders:lower()\\\
    newTroops.coalition = inGroup:getCoalition()\\\
    newTroops.side = newTroops.coalition -- because we'e been using both.\\\
    newTroops.name = inGroup:getName()\\\
    newTroops.moving = false -- set to not have received move orders yet \\\
    newTroops.signature = \\\"cfx\\\" -- to verify this is groundTroop group, not dcs groups\\\
    if not range then range = 300 end\\\
    newTroops.range = range\\\
    return newTroops\\\
end\\\
\\\
function cfxGroundTroops.addGroundTroopsToPool(troops) -- troops MUST be a table that I understand, with \\\
    if not troops then return end\\\
    if troops.signature ~= \\\"cfx\\\" then \\\
        trigger.action.outText(\\\"+++ adding ground troops with unsupported troop signature\\\", 30)\\\
        return \\\
    end\\\
    if not troops.orders then troops.orders = \\\"guard\\\" end \\\
    troops.orders = troops.orders:lower()\\\
    troops.reschedule = true -- in case we use scheduled update \\\
    -- we now add to internal array. this is worked on by all \\\
    -- update meths, on scheduled upadtes, it is only used to \\\
    -- pick up, and do the initial schedule, after that they \\\
    -- all re-schedule themselves \\\
    troops.hasBeenScheduled = false -- so far, no updates \\\
    -- hasBeenScheduled is used by updateCheckOnly when scheduled \\\
    -- updates are used. \\\
    \\\
    -- now add to actively managed table or queue it if enabled\\\
    if cfxGroundTroops.maxManagedTroops > 0 and dcsCommon.getSizeOfTable(cfxGroundTroops.deployedTroops) >= cfxGroundTroops.maxManagedTroops then \\\
        -- we need to queue \\\
        table.insert(cfxGroundTroops.troopQueue, troops)\\\
    else\\\
        -- add to deployed set\\\
        cfxGroundTroops.deployedTroops[troops.group:getName()] = troops\\\
    end\\\
end\\\
\\\
function cfxGroundTroops.removeTroopsFromPool(troops)\\\
    \\\
    if not troops then return end \\\
    if troops.signature ~= \\\"cfx\\\" then return end\\\
\\\
    if not troops.group:isExist() then \\\
        trigger.action.outText(\\\"warning: removeFromPool called with inexistant group\\\", 30)\\\
        return \\\
    end\\\
    \\\
    if cfxGroundTroops.deployedTroops[troops.group:getName()] then \\\
        local troop = cfxGroundTroops.deployedTroops[troops.group:getName()]\\\
        troops.reschedule = false -- so a reschedule wont update any more\\\
        cfxGroundTroops.deployedTroops[troops.group:getName()] = nil\\\
        return \\\
    end\\\
    \\\
    -- if we get here, we need to check if perhaps the troops \\\
    -- are in the queue\\\
    for i=1, #cfxGroundTroops.troopQueue do \\\
        if cfxGroundTroops.troopQueue[i] == troops then \\\
            table.remove(cfxGroundTroops.troopQueue, i)\\\
            return\\\
        end\\\
    end\\\
end\\\
\\\
function isDeployedGroundTroop(aGroup) \\\
    if not aGroup then return false end \\\
    -- see if its already managed\\\
    if cfxGroundTroops.deployedTroops[aGroup:getName()] ~= nil then \\\
        return true \\\
    end \\\
    \\\
    -- see if it's in the queue \\\
    for i=1, #cfxGroundTroops.troopQueue do \\\
        if cfxGroundTroops.troopQueue[i] == troops then \\\
            return true\\\
        end\\\
    end\\\
    -- if we get here, it's neither managed nor queued\\\
    return false \\\
--    return cfxGroundTroops.deployedTroops[aGroup:getName()] ~= nil \\\
end\\\
\\\
function cfxGroundTroops.getGroundTroopsForGroup(aGroup) \\\
    if not (cfxGroundTroops.deployedTroops[aGroup:getName()]) then\\\
        -- see if it's queued \\\
        for i=1, #cfxGroundTroops.troopQueue do \\\
            local troops = cfxGroundTroops.troopQueue[i]\\\
            if troops.group == aGroup then \\\
                return troops\\\
            end\\\
        end\\\
        \\\
        if cfxGroundTroops.verbose then \\\
            trigger.action.outText(\\\"+++gndT - WARNING: cannot find group \\\" .. aGroup:getName() .. \\\" for troop retrieval. Known troops are:\\\", 30)\\\
        end \\\
        for k,v in pairs(cfxGroundTroops.deployedTroops) do \\\
            trigger.action.outText(\\\"+++ \\\".. k .. \\\": has v: \\\" .. v.name, 30)\\\
        end\\\
        return nil\\\
    end\\\
    \\\
    return cfxGroundTroops.deployedTroops[aGroup:getName()]\\\
end\\\
\\\
function cfxGroundTroops.monitorQueues()\\\
    timer.scheduleFunction(cfxGroundTroops.monitorQueues, {}, timer.getTime() + 5)\\\
    \\\
    -- calculate the numbers \\\
    local num = dcsCommon.getSizeOfTable(cfxGroundTroops.deployedTroops)\\\
    \\\
    local msg = \\\"+++ gndT - Groups Managed: <\\\" .. num .. \\\">\\\"\\\
    -- display the numbers\\\
    if cfxGroundTroops.maxManagedTroops > 0 then \\\
        msg = msg .. \\\" capped at \\\" .. cfxGroundTroops.maxManagedTroops .. \\\", q size is <\\\" .. #cfxGroundTroops.troopQueue .. \\\">\\\"\\\
    end\\\
    trigger.action.outText(msg, 30)\\\
end\\\
\\\
\\\
-- manageQueue: if depth of deployedTroops is below max and we have \\\
-- items in queue, pop off first one and put in managed table \\\
-- checked once every 2 seconds \\\
function cfxGroundTroops.manageQueues() \\\
    timer.scheduleFunction(cfxGroundTroops.manageQueues, {}, timer.getTime() + 2)\\\
    if cfxGroundTroops.maxManagedTroops < 1 then return end\\\
    \\\
    -- if we get here, we have a limit on managed \\\
    -- items \\\
    if #cfxGroundTroops.troopQueue < 1 then return end \\\
    \\\
    -- if we here, there are items waiting in the queue\\\
    while dcsCommon.getSizeOfTable(cfxGroundTroops.deployedTroops) < cfxGroundTroops.maxManagedTroops and #cfxGroundTroops.troopQueue > 0 do \\\
        -- trnasfer items from the front to the managed queue \\\
        local theTroops = cfxGroundTroops.troopQueue[1]\\\
        table.remove(cfxGroundTroops.troopQueue, 1)\\\
        if theTroops.group:isExist() then \\\
            cfxGroundTroops.deployedTroops[theTroops.group:getName()] = theTroops\\\
        end\\\
        -- trigger.action.outText(\\\"+++gT: dequed and activaed \\\" .. theTroops.group:getName(), 30)\\\
    end\\\
end\\\
\\\
\\\
function cfxGroundTroops.start()\\\
    if not dcsCommon.libCheck(\\\"cfx Ground Troops\\\",\\\
                              cfxGroundTroops.requiredLibs)\\\
    then \\\
        trigger.action.outText(\\\"cf/x Ground Troops aborted: missing libraries\\\", 30)\\\
        return false \\\
    end\\\
    \\\
    -- read optional config zone \\\
    cfxGroundTroops.readConfigZone()\\\
    \\\
    if cfxGroundTroops.scheduledUpdates then \\\
        cfxGroundTroops.queuedUpdates = false \\\
        cfxGroundTroops.updateCheckOnly()\\\
        cfxGroundTroops.checkSchedules() -- check regularly if all troops have been updated by checking their ID\\\
    elseif cfxGroundTroops.queuedUpdates then \\\
        cfxGroundTroops.updateQueued()\\\
    else     \\\
        cfxGroundTroops.update()\\\
    end \\\
    -- now install a regular pileup check \\\
    timer.scheduleFunction(cfxGroundTroops.checkPileUp, {}, timer.getTime() + 60) \\\
    \\\
    if cfxGroundTroops.monitorNumbers then \\\
        timer.scheduleFunction(cfxGroundTroops.monitorQueues, {}, timer.getTime() + 5) \\\
    end\\\
    \\\
    if cfxGroundTroops.maxManagedTroops > 0 then\\\
        timer.scheduleFunction(cfxGroundTroops.manageQueues, {}, timer.getTime() + 1) \\\
    end \\\
    \\\
    trigger.action.outText(\\\"cf/x Ground Troops v\\\" .. cfxGroundTroops.version .. \\\" started\\\", 30)\\\
    \\\
    if not cfxOwnedZones then \\\
        --trigger.action.outText(\\\"+++groundT: pileUp - owned zones not yet ready\\\", 30)\\\
    end\\\
    return true \\\
end\\\
\\\
if not cfxGroundTroops.start() then \\\
    cfxGroundTroops = nil \\\
    trigger.action.outText(\\\"cfxGroundTroops aborted load\\\", 30)\\\
end\\\
\\\
--[[--\\\
 TO DO \\\
 \\\
 - implement 'patrol' orders!!! \\\
   \\\
   when ordering a new route, issue a command to stop in 1 second\\\
 and another with new marching orders in 5 seconds \\\
 look at setTask() and resetTask() for controller\\\
 - change group logic to set itself up to 'requestOrders' with group as parameter, so they can decide themselves how quickly they want to be re-tasked\\\
 \\\
 - DONE enqueue and dequeue methods with capped ground troops size \\\
 - named locs have strategic values attached (default = 1), and distance is divided by strat value to get at priority when rerouting \\\
 \\\
 - difficulty increase: make enemy troops better by raining their spawned level \\\
 \\\
 - check out simple slot block SSB (pre-moose) to see if we can implement slot blocking for downed pilots \\\
 \\\
 - new 'wanda' (wander) module to make airports more lively: zone, have individuals/single vehicle wander around. two waypoints (start and stop), that are zones, and whenever they reach one or are at speed 0, they get a new one. may have pause before they go to next. \\\
 variant on above: selection of zones that are somehow connected, and destinations are made between these for patrolling zone. can force order, loop, and ping-pong. \\\
--]]--\");a_do_script(\"cfxOwnedZones = {}\\\
cfxOwnedZones.version = \\\"2.0.0\\\"\\\
cfxOwnedZones.verbose = false \\\
cfxOwnedZones.announcer = true \\\
cfxOwnedZones.name = \\\"cfxOwnedZones\\\" \\\
--[[-- VERSION HISTORY\\\
\\\
2.0.0 - factored from cfxOwnedZones 1.x, separating out production\\\
\\\
--]]--\\\
cfxOwnedZones.requiredLibs = {\\\
    \\\"dcsCommon\\\", \\\
    \\\"cfxZones\\\",  \\\
}\\\
\\\
cfxOwnedZones.zones = {}\\\
cfxOwnedZones.ups = 1\\\
cfxOwnedZones.initialized = false \\\
--[[--\\\
 owned zones is a module that manages conquerable zones and keeps a record\\\
 of who owns the zone based on rules  \\\
\\\
 \\\
 *** EXTENTDS ZONES ***, so compatible with cfxZones, pilotSafe (limited airframes), may conflict with FARPZones \\\
\\\
\\\
 owned zones are identified by the 'owner' property. It can be initially set to nothing (default), NEUTRAL, RED or BLUE\\\
\\\
 when a zone changes hands, a callback can be installed to be told of that fact\\\
 callback has the format (zone, newOwner, formerOwner) with zone being the Zone, and new owner and former owners\\\
 --]]--\\\
 \\\
cfxOwnedZones.conqueredCallbacks = {}\\\
\\\
--\\\
-- callback handling\\\
--\\\
\\\
function cfxOwnedZones.addCallBack(conqCallback)\\\
    local cb = {}\\\
    cb.callback = conqCallback -- we use this so we can add more data later\\\
    cfxOwnedZones.conqueredCallbacks[conqCallback] = cb\\\
    \\\
end\\\
\\\
function cfxOwnedZones.invokeConqueredCallbacks(aZone, newOwner, lastOwner)\\\
    for key, cb in pairs (cfxOwnedZones.conqueredCallbacks) do \\\
        cb.aZone = aZone -- set these up for if we need them later\\\
        cb.newOwner = newOwner\\\
        cb.lastOwner = lastOwner\\\
        -- invoke callback\\\
        cb.callback(aZone, newOwner, lastOwner)\\\
    end\\\
end\\\
\\\
function cfxOwnedZones.side2name(theSide)\\\
    if theSide == 1 then return \\\"REDFORCE\\\" end\\\
    if theSide == 2 then return \\\"BLUEFORCE\\\" end\\\
    return \\\"Neutral\\\"\\\
end\\\
\\\
function cfxOwnedZones.conqTemplate(aZone, newOwner, lastOwner) \\\
    if true then return end -- do not output\\\
\\\
    if lastOwner == 0 then \\\
        trigger.action.outText(cfxOwnedZones.side2name(newOwner) .. \\\" have taken possession zone \\\" .. aZone.name, 30)\\\
        return \\\
    end\\\
    \\\
    trigger.action.outText(\\\"Zone \\\" .. aZone.name .. \\\" was taken by \\\".. cfxOwnedZones.side2name(newOwner) .. \\\" from \\\" .. cfxOwnedZones.side2name(lastOwner), 30)\\\
end\\\
\\\
--\\\
-- M I S C\\\
--\\\
\\\
function cfxOwnedZones.drawZoneInMap(aZone)\\\
    -- will save markID in zone's markID\\\
    if aZone.markID then \\\
        trigger.action.removeMark(aZone.markID)\\\
    end \\\
    if aZone.hidden then return end \\\
    \\\
    local lineColor = {1.0, 0, 0, 1.0} -- red \\\
    local fillColor = {1.0, 0, 0, 0.2} -- red \\\
    local owner = aZone.owner -- cfxOwnedZones.getOwnerForZone(aZone)\\\
    if owner == 2 then \\\
        lineColor = {0.0, 0, 1.0, 1.0}\\\
        fillColor = {0.0, 0, 1.0, 0.2}\\\
    elseif owner == 0 then \\\
        lineColor = {0.8, 0.8, 0.8, 1.0}\\\
        fillColor = {0.8, 0.8, 0.8, 0.2}\\\
    end\\\
    \\\
    local theShape = 2 -- circle\\\
    local markID = dcsCommon.numberUUID()\\\
\\\
    trigger.action.circleToAll(-1, markID, aZone.point, aZone.radius, lineColor, fillColor, 1, true, \\\"\\\")\\\
    aZone.markID = markID \\\
    \\\
end\\\
\\\
function cfxOwnedZones.getOwnedZoneByName(zName)\\\
    for zKey, theZone in pairs (cfxOwnedZones.zones) do \\\
        if theZone.name == zName then return theZone end \\\
    end\\\
    return nil\\\
end\\\
\\\
function cfxOwnedZones.addOwnedZone(aZone)\\\
    local owner = aZone.owner --cfxZones.getCoalitionFromZoneProperty(aZone, \\\"owner\\\", 0) -- is already readm read it again\\\
    \\\
    if cfxZones.hasProperty(aZone, \\\"conquered!\\\") then \\\
        aZone.conqueredFlag = cfxZones.getStringFromZoneProperty(aZone, \\\"conquered!\\\", \\\"*<cfxnone>\\\")\\\
    end\\\
    if cfxZones.hasProperty(aZone, \\\"redCap!\\\") then \\\
        aZone.redCap = cfxZones.getStringFromZoneProperty(aZone, \\\"redCap!\\\", \\\"none\\\")\\\
    end\\\
    if cfxZones.hasProperty(aZone, \\\"redLost!\\\") then \\\
        aZone.redLost = cfxZones.getStringFromZoneProperty(aZone, \\\"redLost!\\\", \\\"none\\\")\\\
    end\\\
    if cfxZones.hasProperty(aZone, \\\"blueCap!\\\") then \\\
        aZone.blueCap = cfxZones.getStringFromZoneProperty(aZone, \\\"blueCap!\\\", \\\"none\\\")\\\
    end\\\
    if cfxZones.hasProperty(aZone, \\\"blueLost!\\\") then \\\
        aZone.blueLost = cfxZones.getStringFromZoneProperty(aZone, \\\"blueLost!\\\", \\\"none\\\")\\\
    end\\\
    if cfxZones.hasProperty(aZone, \\\"neutral!\\\") then \\\
        aZone.neutralCap = cfxZones.getStringFromZoneProperty(aZone, \\\"neutral!\\\", \\\"none\\\")\\\
    end\\\
    if cfxZones.hasProperty(aZone, \\\"ownedBy\\\") then \\\
        aZone.ownedBy = cfxZones.getStringFromZoneProperty(aZone, \\\"ownedBy\\\", \\\"none\\\")\\\
    end\\\
\\\
    aZone.ownedTriggerMethod = cfxZones.getStringFromZoneProperty(aZone, \\\"triggerMethod\\\", \\\"change\\\")\\\
    if cfxZones.hasProperty(aZone, \\\"ownedTriggerMethod\\\") then \\\
        aZone.ownedTriggerMethod = cfxZones.getStringFromZoneProperty(aZone, \\\"ownedTriggerMethod\\\", \\\"change\\\")\\\
    end\\\
        \\\
    aZone.unbeatable = cfxZones.getBoolFromZoneProperty(aZone, \\\"unbeatable\\\", false)\\\
    aZone.untargetable = cfxZones.getBoolFromZoneProperty(aZone, \\\"untargetable\\\", false)\\\
    \\\
    aZone.hidden = cfxZones.getBoolFromZoneProperty(aZone, \\\"hidden\\\", false)\\\
    cfxOwnedZones.zones[aZone] = aZone \\\
    cfxOwnedZones.drawZoneInMap(aZone)\\\
end\\\
\\\
--\\\
-- U P D A T E \\\
--\\\
\\\
function cfxOwnedZones.bangNeutral(value)\\\
    if not cfxOwnedZones.neutralTriggerFlag then return end \\\
    local newVal = trigger.misc.getUserFlag(cfxOwnedZones.neutralTriggerFlag) + value \\\
    trigger.action.setUserFlag(cfxOwnedZones.neutralTriggerFlag, newVal)\\\
end\\\
\\\
function cfxOwnedZones.bangRed(value)\\\
    if not cfxOwnedZones.redTriggerFlag then return end \\\
    local newVal = trigger.misc.getUserFlag(cfxOwnedZones.redTriggerFlag) + value \\\
    trigger.action.setUserFlag(cfxOwnedZones.redTriggerFlag, newVal)\\\
end\\\
\\\
function cfxOwnedZones.bangBlue(value)\\\
    if not cfxOwnedZones.blueTriggerFlag then return end \\\
    local newVal = trigger.misc.getUserFlag(cfxOwnedZones.blueTriggerFlag) + value \\\
    trigger.action.setUserFlag(cfxOwnedZones.blueTriggerFlag, newVal)\\\
end\\\
\\\
function cfxOwnedZones.bangSide(theSide, value)\\\
    if theSide == 2 then \\\
        cfxOwnedZones.bangBlue(value)\\\
        return \\\
    end \\\
    if theSide == 1 then \\\
        cfxOwnedZones.bangRed(value)\\\
        return \\\
    end \\\
    cfxOwnedZones.bangNeutral(value)\\\
end\\\
\\\
function cfxOwnedZones.zoneConquered(aZone, theSide, formerOwner) -- 0 = neutral 1 = RED 2 = BLUE \\\
    local who = \\\"REDFORCE\\\"\\\
    if theSide == 2 then who = \\\"BLUEFORCE\\\" \\\
    elseif theSide == 0 then who = \\\"NEUTRAL\\\" end\\\
    \\\
    if cfxOwnedZones.announcer then \\\
        if theSide == 0 then \\\
            trigger.action.outText(aZone.name .. \\\" has become NEUTRAL\\\", 30)\\\
        else \\\
            trigger.action.outText(who .. \\\" have secured zone \\\" .. aZone.name, 30)\\\
        end\\\
        aZone.owner = theSide -- just to be sure \\\
        -- play different sounds depending on who's won\\\
        if theSide == 1 then \\\
            trigger.action.outSoundForCoalition(1, cfxOwnedZones.winSound)\\\
            trigger.action.outSoundForCoalition(2, cfxOwnedZones.loseSound)\\\
        elseif theSide == 2 then  \\\
            trigger.action.outSoundForCoalition(2, cfxOwnedZones.winSound)\\\
            trigger.action.outSoundForCoalition(1, cfxOwnedZones.loseSound)\\\
        else \\\
            -- no sound played, new owner is neutral \\\
        end\\\
    end \\\
\\\
    if aZone.conqueredFlag then \\\
        cfxZones.pollFlag(aZone.conqueredFlag, \\\"inc\\\", aZone)\\\
    end \\\
    \\\
    if theSide == 1 and aZone.redCap then \\\
        cfxZones.pollFlag(aZone.redCap, \\\"inc\\\", aZone)\\\
    end\\\
    \\\
    if formerOwner == 1 and aZone.redLost then \\\
        cfxZones.pollFlag(aZone.redLost, \\\"inc\\\", aZone)\\\
    end\\\
    \\\
    if theSide == 2 and aZone.blueCap then \\\
        cfxZones.pollFlag(aZone.blueCap, \\\"inc\\\", aZone)\\\
    end\\\
    \\\
    if formerOwner == 2 and aZone.blueLost then \\\
        cfxZones.pollFlag(aZone.blueLost, \\\"inc\\\", aZone)\\\
    end\\\
    \\\
    if theSide == 0 and aZone.neutralCap then \\\
        cfxZones.pollFlag(aZone.neutralCap, \\\"inc\\\", aZone)\\\
    end\\\
    \\\
    -- invoke callbacks now\\\
    cfxOwnedZones.invokeConqueredCallbacks(aZone, theSide, formerOwner)\\\
    \\\
    -- bang! flag support \\\
    cfxOwnedZones.bangSide(theSide, 1) -- winner \\\
    cfxOwnedZones.bangSide(formerOwner, -1) -- loser \\\
    \\\
    -- update map\\\
    cfxOwnedZones.drawZoneInMap(aZone) -- update status in map. will erase previous version \\\
\\\
end\\\
\\\
function cfxOwnedZones.update()\\\
    -- to speed this up we might only want to check the first unit \\\
    -- in group, and if inside, count the entire group as inside \\\
    -- new. unit counting update \\\
    cfxOwnedZones.updateSchedule = timer.scheduleFunction(cfxOwnedZones.update, {}, timer.getTime() + 1/cfxOwnedZones.ups)\\\
    -- iterate all groups and their units to count how many \\\
    -- units are in each zone \\\
    for idz, theZone in pairs(cfxOwnedZones.zones) do \\\
        theZone.numRed = 0\\\
        theZone.numBlue = 0 \\\
        -- count red units\\\
        local allRed = coalition.getGroups(1, Group.Category.GROUND)\\\
        for idx, aGroup in pairs(allRed) do \\\
            if Group.isExist(aGroup) then \\\
                if cfxOwnedZones.fastEval then \\\
                    -- we only check first unit that is alive\\\
                    local theUnit = dcsCommon.getGroupUnit(aGroup)\\\
                    if theUnit and cfxZones.unitInZone(theUnit, theZone) then\\\
                        theZone.numRed = theZone.numRed + aGroup:getSize()\\\
                    end\\\
                else \\\
                    local allUnits = aGroup:getUnits() \\\
                    for idy, theUnit in pairs(allUnits) do \\\
                        if cfxZones.unitInZone(theUnit, theZone) then \\\
                            theZone.numRed = theZone.numRed + 1\\\
                        end\\\
                    end\\\
                end\\\
            end\\\
        end\\\
        -- count blue units \\\
        local allBlue = coalition.getGroups(2, Group.Category.GROUND)\\\
        for idx, aGroup in pairs(allBlue) do \\\
            if Group.isExist(aGroup) then \\\
                if cfxOwnedZones.fastEval then \\\
                    -- we only check first unit that is alive\\\
                    local theUnit = dcsCommon.getGroupUnit(aGroup)\\\
                    if theUnit and cfxZones.unitInZone(theUnit, theZone) then\\\
                        theZone.numBlue = theZone.numBlue + aGroup:getSize()\\\
                    end\\\
                else \\\
                    local allUnits = aGroup:getUnits() \\\
                    for idy, theUnit in pairs(allUnits) do \\\
                        if cfxZones.unitInZone(theUnit, theZone) then\\\
                            theZone.numBlue = theZone.numBlue + 1\\\
                        end\\\
                    end\\\
                end\\\
            end\\\
        end\\\
        -- trigger.action.outText(theZone.name .. \\\" blue: \\\" .. theZone.numBlue .. \\\" red \\\" .. theZone.numRed, 30)\\\
        local lastOwner = theZone.owner\\\
        local newOwner = 0 -- neutral is default \\\
        if theZone.unbeatable then -- Parker Lewis can't lose. Neither this zone.\\\
            newOwner = lastOwner \\\
        end\\\
        \\\
        -- determine new owner \\\
        if theZone.unbeatable then \\\
            -- we do nothing \\\
        elseif theZone.numRed < 1 and theZone.numBlue < 1 then \\\
            -- no troops here. Become neutral?\\\
            if cfxOwnedZones.numKeep < 1 then \\\
                newOwner = lastOwner -- keep it, else turns neutral\\\
            else \\\
                -- noone here, zone becomes neutral\\\
                newOwner = 0 -- not strictly required. to be explicit \\\
            end\\\
        elseif theZone.numRed < 1 then \\\
            -- only blue here. enough to keep? \\\
            if theZone.numBlue >= cfxOwnedZones.numCap then \\\
                newOwner = 2 -- blue owns it\\\
            elseif lastOwner == 2 and theZone.numBlue >= cfxOwnedZones.numKeep then \\\
                -- enough to keep if owned before\\\
                newOwner = 2\\\
            else \\\
                newOwner = 0 -- just to make it explicit\\\
            end \\\
        elseif theZone.numBlue < 1 then \\\
            -- only red here. enough to keep?\\\
            if theZone.numRed >= cfxOwnedZones.numCap then \\\
                newOwner = 1 \\\
            elseif lastOwner == 1 and theZone.numRed >= cfxOwnedZones.numKeep then \\\
                newOwner = 1 \\\
            else \\\
                newOwner = 0 \\\
            end                 \\\
        else \\\
            -- blue and red units here.\\\
            -- owner keeps hanging on only they have enough \\\
            -- units left\\\
            if cfxOwnedZones.easyContest then \\\
                -- this zone is immediately contested\\\
                newOwner = 0 -- just to be explicit \\\
            elseif cfxOwnedZones.numKeep < 1 then \\\
                -- old owner keeps it until none left \\\
                newOwner = lastOwner\\\
            else\\\
                if lastOwner == 1 then \\\
                    -- red can keep it as long as enough units here \\\
                    if theZone.numRed >= cfxOwnedZones.numKeep then \\\
                        newOwner = 1\\\
                    end -- else 0\\\
                elseif lastOwner == 2 then\\\
                    -- blue can keep it if enough units here\\\
                    if theZone.numBlue >= cfxOwnedZones.numKeep then \\\
                        newOwner = 2\\\
                    end -- else 0 \\\
                else -- stay 0 \\\
                end\\\
            end\\\
        end\\\
    \\\
        -- now see if owner changed, and react accordingly \\\
        if newOwner == lastOwner then \\\
            -- nothing happened, do nothing \\\
        else \\\
            trigger.action.outText(theZone.name .. \\\" change hands from  \\\" .. lastOwner .. \\\" to \\\" .. newOwner, 30)\\\
            if newOwner == 0 then -- zone turned neutral \\\
                cfxOwnedZones.zoneConquered(theZone, newOwner, lastOwner)\\\
            else\\\
                cfxOwnedZones.zoneConquered(theZone, newOwner, lastOwner)\\\
            end\\\
        end\\\
        theZone.owner = newOwner\\\
        \\\
        -- update ownership flag if exists\\\
        if theZone.ownedBy then \\\
            cfxZones.setFlagValue(theZone.ownedBy, theZone.owner, theZone)\\\
        end\\\
        \\\
    end -- iterating all zones \\\
\\\
end\\\
\\\
function cfxOwnedZones.sideOwnsAll(theSide) \\\
    for key, aZone in pairs(cfxOwnedZones.zones) do \\\
        if aZone.owner ~= theSide then \\\
            return false\\\
        end\\\
    end\\\
    -- if we get here, all your base are belong to us \\\
    return true\\\
end\\\
\\\
function cfxOwnedZones.hasOwnedZones() \\\
    for idx, zone in pairs (cfxOwnedZones.zones) do\\\
        return true -- even the first returns true\\\
    end\\\
    -- no owned zones\\\
    return false \\\
end\\\
\\\
-- getting closest owned zones etc\\\
-- required for groundTroops and factory attackers \\\
-- methods provided only for other modules (e.g. cfxGroundTroops or \\\
-- factoryZone \\\
--\\\
\\\
function cfxOwnedZones.collectZones(mode)\\\
    return cfxOwnedZones.zones \\\
    --if not mode then mode = \\\"OWNED\\\" end \\\
    -- Note: since cfxGroundTroops currently simply uses owner flag\\\
    -- we cannot migrate to a differentiation between factory and \\\
    -- owned. All produced attackers always attack owned zones.\\\
end\\\
\\\
function cfxOwnedZones.getEnemyZonesFor(aCoalition) \\\
    local enemyZones = {}\\\
    local allZones = cfxOwnedZones.collectZones()  \\\
    local ourEnemy = dcsCommon.getEnemyCoalitionFor(aCoalition)\\\
    for zKey, aZone in pairs(allZones) do \\\
        if aZone.owner == ourEnemy then -- only check enemy owned zones\\\
            -- note: will include untargetable zones \\\
            table.insert(enemyZones, aZone)            \\\
        end\\\
    end\\\
    return enemyZones\\\
end\\\
\\\
function cfxOwnedZones.getNearestOwnedZoneToPoint(aPoint)\\\
    local shortestDist = math.huge\\\
    local closestZone = nil\\\
    local allZones = cfxOwnedZones.collectZones() \\\
    \\\
    for zKey, aZone in pairs(allZones) do \\\
        local zPoint = cfxZones.getPoint(aZone) \\\
        currDist = dcsCommon.dist(zPoint, aPoint)\\\
        if aZone.untargetable ~= true and \\\
           currDist < shortestDist then \\\
            shortestDist = currDist\\\
            closestZone = aZone\\\
        end\\\
    end\\\
    \\\
    return closestZone, shortestDist\\\
end\\\
\\\
function cfxOwnedZones.getNearestOwnedZone(theZone)\\\
    local shortestDist = math.huge\\\
    local closestZone = nil\\\
    local aPoint = cfxZones.getPoint(theZone)\\\
    local allZones = cfxOwnedZones.collectZones()\\\
    for zKey, aZone in pairs(allZones) do\\\
        local zPoint = cfxZones.getPoint(aZone) \\\
        currDist = dcsCommon.dist(zPoint, aPoint)\\\
        if aZone.untargetable ~= true and currDist < shortestDist then \\\
            shortestDist = currDist\\\
            closestZone = aZone\\\
        end\\\
    end\\\
    \\\
    return closestZone, shortestDist\\\
end\\\
\\\
function cfxOwnedZones.getNearestEnemyOwnedZone(theZone, targetNeutral)\\\
    if not targetNeutral then targetNeutral = false else targetNeutral = true end\\\
    local shortestDist = math.huge\\\
    local closestZone = nil\\\
    local allZones = cfxOwnedZones.collectZones()\\\
    local ourEnemy = dcsCommon.getEnemyCoalitionFor(theZone.owner)\\\
    if not ourEnemy then return nil end -- we called for a neutral zone. they have no enemies \\\
    local zPoint = cfxZones.getPoint(theZone)\\\
    \\\
    for zKey, aZone in pairs(allZones) do \\\
        if targetNeutral then \\\
            -- return all zones that do not belong to us\\\
            if aZone.owner ~= theZone.owner then \\\
                local aPoint = cfxZones.getPoint(aZone)\\\
                currDist = dcsCommon.dist(aPoint, zPoint)\\\
                if aZone.untargetable ~= true and currDist < shortestDist then \\\
                    shortestDist = currDist\\\
                    closestZone = aZone\\\
                end\\\
            end\\\
        else \\\
            -- return zones that are taken by the Enenmy\\\
            if aZone.owner == ourEnemy then -- only check own zones\\\
                local aPoint = cfxZones.getPoint(aZone)\\\
                currDist = dcsCommon.dist(zPoint, aPoint)\\\
                if aZone.untargetable ~= true and currDist < shortestDist then \\\
                    shortestDist = currDist\\\
                    closestZone = aZone\\\
                end\\\
            end\\\
        end \\\
    end\\\
    \\\
    return closestZone, shortestDist\\\
end\\\
\\\
function cfxOwnedZones.getNearestFriendlyZone(theZone, targetNeutral)\\\
    if not targetNeutral then targetNeutral = false else targetNeutral = true end\\\
    local shortestDist = math.huge\\\
    local closestZone = nil\\\
    local ourEnemy = dcsCommon.getEnemyCoalitionFor(theZone.owner)\\\
    if not ourEnemy then return nil end -- we called for a neutral zone. they have no enemies nor friends, all zones would be legal.\\\
    local zPoint = cfxZones.getPoint(theZone)\\\
    local allZones = cfxOwnedZones.collectZones() \\\
\\\
    for zKey, aZone in pairs(allZones) do \\\
        if targetNeutral then \\\
            -- target all zones that do not belong to the enemy\\\
            if aZone.owner ~= ourEnemy then\\\
                local aPoint = cfxZones.getPoint(aZone)\\\
                currDist = dcsCommon.dist(zPoint, aPoint)\\\
                if aZone.untargetable ~= true and currDist < shortestDist then \\\
                    shortestDist = currDist\\\
                    closestZone = aZone\\\
                end\\\
            end\\\
        else \\\
            -- only target zones that are taken by us\\\
            if aZone.owner == theZone.owner then -- only check own zones\\\
                local aPoint = cfxZones.getPoint(aZone)\\\
                currDist = dcsCommon.dist(zPoint, aPoint)\\\
                if aZone.untargetable ~= true and currDist < shortestDist then \\\
                    shortestDist = currDist\\\
                    closestZone = aZone\\\
                end\\\
            end\\\
        end \\\
    end\\\
    \\\
    return closestZone, shortestDist\\\
end\\\
\\\
function cfxOwnedZones.enemiesRemaining(aZone)\\\
    if cfxOwnedZones.getNearestEnemyOwnedZone(aZone) then return true end\\\
    return false\\\
end\\\
\\\
--\\\
-- load / save data \\\
--\\\
\\\
function cfxOwnedZones.saveData()\\\
    -- this is called from persistence when it's time to \\\
    -- save data. returns a table with all my data \\\
    local theData = {}\\\
    local allZoneData = {}\\\
    -- iterate all my zones and create data \\\
    for idx, theZone in pairs(cfxOwnedZones.zones) do\\\
        local zoneData = {}\\\
\\\
        if theZone.conqueredFlag then \\\
            zoneData.conquered = cfxZones.getFlagValue(theZone.conqueredFlag, theZone)\\\
        end \\\
\\\
        zoneData.owner = theZone.owner \\\
        allZoneData[theZone.name] = zoneData\\\
    end\\\
    \\\
    -- now iterate all attack groups that we have spawned and that \\\
    -- (maybe) are still alive \\\
    -- now write the info for the flags that we output for #red, etc\\\
    local flagInfo = {}\\\
    flagInfo.neutral = cfxZones.getFlagValue(cfxOwnedZones.neutralTriggerFlag, cfxOwnedZones)\\\
    flagInfo.red = cfxZones.getFlagValue(cfxOwnedZones.redTriggerFlag, cfxOwnedZones)\\\
    flagInfo.blue = cfxZones.getFlagValue(cfxOwnedZones.blueTriggerFlag, cfxOwnedZones)\\\
    -- assemble the data \\\
    theData.zoneData = allZoneData\\\
    theData.flagInfo = flagInfo\\\
    \\\
    -- return it \\\
    return theData\\\
end\\\
\\\
function cfxOwnedZones.loadData()\\\
    -- remember to draw in map with new owner \\\
    if not persistence then return end \\\
    local theData = persistence.getSavedDataForModule(\\\"cfxOwnedZones\\\")\\\
    if not theData then \\\
        if cfxOwnedZones.verbose then \\\
            trigger.action.outText(\\\"owdZ: no save date received, skipping.\\\", 30)\\\
        end\\\
        return\\\
    end\\\
    -- theData contains the following tables:\\\
    --   zoneData: per-zone data \\\
    --   flagInfo: module-global flags \\\
    --   attackers: all spawned attackers that we feed to groundTroops\\\
    local allZoneData = theData.zoneData \\\
    for zName, zData in pairs(allZoneData) do \\\
        -- access zone \\\
        local theZone = cfxOwnedZones.getOwnedZoneByName(zName)\\\
        if theZone then \\\
            theZone.owner = zData.owner \\\
            if zData.conquered then \\\
                cfxZones.setFlagValue(theZone.conqueredFlag, zData.conquered, theZone)\\\
            end\\\
            -- update mark in map \\\
            cfxOwnedZones.drawZoneInMap(theZone)\\\
        else \\\
            trigger.action.outText(\\\"owdZ: load - data mismatch: cannot find zone <\\\" .. zName .. \\\">, skipping zone.\\\", 30)\\\
        end\\\
    end\\\
    \\\
    -- now process module global flags \\\
    local flagInfo = theData.flagInfo\\\
    if flagInfo then \\\
        cfxZones.setFlagValue(cfxOwnedZones.neutralTriggerFlag, flagInfo.neutral, cfxOwnedZones)\\\
        cfxZones.setFlagValue(cfxOwnedZones.redTriggerFlag, flagInfo.red, cfxOwnedZones)\\\
        cfxZones.setFlagValue(cfxOwnedZones.blueTriggerFlag, flagInfo.blue, cfxOwnedZones)\\\
    end\\\
end\\\
\\\
 \\\
--\\\
function cfxOwnedZones.readConfigZone(theZone)\\\
    if not theZone then theZone = cfxZones.createSimpleZone(\\\"ownedZonesConfig\\\") end \\\
    \\\
    cfxOwnedZones.name = \\\"cfxOwnedZones\\\" -- just in case, so we can access with cfxZones \\\
    cfxOwnedZones.verbose = cfxZones.getBoolFromZoneProperty(theZone, \\\"verbose\\\", false)\\\
    cfxOwnedZones.announcer = cfxZones.getBoolFromZoneProperty(theZone, \\\"announcer\\\", true)\\\
    \\\
    cfxOwnedZones.redTriggerFlag = cfxZones.getStringFromZoneProperty(theZone, \\\"r!\\\", \\\"*<cfxnone>\\\")\\\
    cfxOwnedZones.blueTriggerFlag = cfxZones.getStringFromZoneProperty(theZone, \\\"b!\\\", \\\"*<cfxnone>\\\")\\\
    cfxOwnedZones.neutralTriggerFlag = cfxZones.getStringFromZoneProperty(theZone, \\\"n!\\\", \\\"*<cfxnone>\\\")\\\
\\\
    -- numKeep, numCap, fastEval, easyContest\\\
    cfxOwnedZones.numCap = cfxZones.getNumberFromZoneProperty(theZone, \\\"numCap\\\", 1) -- minimal number of units required to cap zone \\\
    cfxOwnedZones.numKeep = cfxZones.getNumberFromZoneProperty(theZone, \\\"numKeep\\\", 0) -- number required to keep zone \\\
    cfxOwnedZones.fastEval = cfxZones.getBoolFromZoneProperty(theZone, \\\"fastEval\\\", true)\\\
    cfxOwnedZones.easyContest = cfxZones.getBoolFromZoneProperty(theZone, \\\"easyContest\\\", false)\\\
    -- winSound, loseSound \\\
    cfxOwnedZones.winSound = cfxZones.getStringFromZoneProperty(theZone, \\\"winSound\\\", \\\"Quest Snare 3.wav\\\" )\\\
    cfxOwnedZones.loseSound = cfxZones.getStringFromZoneProperty(theZone, \\\"loseSound\\\", \\\"Death BRASS.wav\\\")\\\
end\\\
\\\
function cfxOwnedZones.init()\\\
    -- check libs\\\
    if not dcsCommon.libCheck(\\\"cfx Owned Zones\\\", \\\
        cfxOwnedZones.requiredLibs) then\\\
        return false \\\
    end\\\
\\\
    -- read my config zone\\\
    local theZone = cfxZones.getZoneByName(\\\"ownedZonesConfig\\\") \\\
    cfxOwnedZones.readConfigZone(theZone)\\\
\\\
    \\\
    -- collect all owned zones by their 'owner' property \\\
    -- start the process\\\
    local pZones = cfxZones.zonesWithProperty(\\\"owner\\\")\\\
    \\\
    -- now add all zones to my zones table, and convert the owner property into \\\
    -- a proper attribute \\\
    for k, aZone in pairs(pZones) do\\\
        cfxOwnedZones.addOwnedZone(aZone)\\\
    end\\\
    \\\
    if persistence then \\\
        -- sign up for persistence \\\
        callbacks = {}\\\
        callbacks.persistData = cfxOwnedZones.saveData\\\
        persistence.registerModule(\\\"cfxOwnedZones\\\", callbacks)\\\
        -- now load my data \\\
        cfxOwnedZones.loadData()\\\
    end\\\
    \\\
    initialized = true \\\
    cfxOwnedZones.updateSchedule = timer.scheduleFunction(cfxOwnedZones.update, {}, timer.getTime() + 1/cfxOwnedZones.ups)\\\
    \\\
    trigger.action.outText(\\\"cx/x owned zones v\\\".. cfxOwnedZones.version .. \\\" started\\\", 30)\\\
    return true \\\
end\\\
\\\
if not cfxOwnedZones.init() then \\\
    trigger.action.outText(\\\"cf/x Owned Zones aborted: missing libraries\\\", 30)\\\
    cfxOwnedZones = nil \\\
end\\\
\\\
\\\
\\\
\");a_do_script(\"factoryZone = {}\\\
factoryZone.version = \\\"1.0.0\\\"\\\
factoryZone.verbose = false \\\
factoryZone.name = \\\"factoryZone\\\" \\\
\\\
--[[-- VERSION HISTORY\\\
\\\
1.0.0 - refactored production part from cfxOwnedZones 1.xpcall\\\
\\\
--]]--\\\
factoryZone.requiredLibs = {\\\
    \\\"dcsCommon\\\",\\\
    \\\"cfxZones\\\",  \\\
    \\\"cfxCommander\\\", -- to make troops do stuff\\\
    \\\"cfxOwnedZones\\\" -- attackers rely on this \\\
}\\\
\\\
factoryZone.zones = {} -- my factory zones \\\
factoryZone.ups = 1\\\
factoryZone.initialized = false \\\
factoryZone.defendingTime = 100 -- seconds until new defenders are produced\\\
factoryZone.attackingTime = 300 -- seconds until new attackers are produced \\\
factoryZone.shockTime = 200 -- 'shocked' period of inactivity\\\
factoryZone.repairTime = 200 -- time until we raplace one lost unit, also repairs all other units to 100%  \\\
\\\
-- persistence: all attackers we ever sent out.\\\
-- is regularly verified and cut to size \\\
factoryZone.spawnedAttackers = {}\\\
\\\
-- factoryZone is a module that manages production of units\\\
-- inside zones and can switch production based on who owns the \\\
-- zone. Zone ownership can by dynamic (by using OwnedZones or \\\
-- using scripts to change the 'owner' flag\\\
--\\\
-- *** EXTENTDS ZONES ***\\\
--\\\
-- zone attributes when owned\\\
--  owner: coalition that owns the zone. Managed externally\\\
--  status: FSM for spawning\\\
--  defendersRED/BLUE - coma separated type string for the group to spawn on defense cycle completion\\\
--  attackersRED/BLUE - as above for attack cycle. \\\
--  timeStamp - time when zone switched into current state \\\
--  spawnRadius - overrides zone's radius when placing defenders. can be use to place defenders inside or outside zone itself\\\
--  formation - defender's formation\\\
--  attackFormation - attackers formation \\\
--  attackRadius - radius of circle in which attackers are spawned. informs formation \\\
--  attackDelta - polar coord: r from zone center where attackers are spawned\\\
--  attackPhi - polar degrees where attackers are to be spawned\\\
--  paused - will not spawn. default is false \\\
--  unbeatable - can't be conquered by other side. default is false\\\
--  untargetable - will not be targeted by either side. make unbeatable\\\
--  owned zones untargetable, or they'll become a troop magnet for \\\
--  zoneAttackers \\\
\\\
--\\\
-- M I S C\\\
--\\\
\\\
\\\
function factoryZone.getFactoryZoneByName(zName)\\\
    for zKey, theZone in pairs (factoryZone.zones) do \\\
        if theZone.name == zName then return theZone end \\\
    end\\\
    return nil\\\
end\\\
\\\
function factoryZone.addFactoryZone(aZone)\\\
    aZone.worksFor = cfxZones.getCoalitionFromZoneProperty(aZone, \\\"factory\\\", 0) -- currently unused, have RED/BLUE separate types \\\
    aZone.state = \\\"init\\\"\\\
    aZone.timeStamp = timer.getTime()\\\
    aZone.defendersRED = cfxZones.getStringFromZoneProperty(aZone, \\\"defendersRED\\\", \\\"none\\\")\\\
    aZone.defendersBLUE = cfxZones.getStringFromZoneProperty(aZone, \\\"defendersBLUE\\\", \\\"none\\\")\\\
    if cfxZones.hasProperty(aZone, \\\"attackersRED\\\") then \\\
        -- legacy support\\\
        aZone.attackersRED = cfxZones.getStringFromZoneProperty(aZone, \\\"attackersRED\\\", \\\"none\\\")\\\
    else\\\
        aZone.attackersRED = cfxZones.getStringFromZoneProperty(aZone, \\\"productionRED\\\", \\\"none\\\")\\\
    end\\\
    \\\
    if cfxZones.hasProperty(aZone, \\\"attackersBLUE\\\") then     \\\
        -- legacy support \\\
        aZone.attackersBLUE = cfxZones.getStringFromZoneProperty(aZone, \\\"attackersBLUE\\\", \\\"none\\\")\\\
    else \\\
        aZone.attackersBLUE = cfxZones.getStringFromZoneProperty(aZone, \\\"productionBLUE\\\", \\\"none\\\")\\\
    end\\\
    \\\
    aZone.formation = cfxZones.getStringFromZoneProperty(aZone, \\\"formation\\\", \\\"circle_out\\\")\\\
    aZone.attackFormation = cfxZones.getStringFromZoneProperty(aZone, \\\"attackFormation\\\", \\\"circle_out\\\") -- cfxZones.getZoneProperty(aZone, \\\"attackFormation\\\")\\\
    aZone.spawnRadius = cfxZones.getNumberFromZoneProperty(aZone, \\\"spawnRadius\\\", aZone.radius-5) -- \\\"-5\\\" so they remaininside radius \\\
    aZone.attackRadius = cfxZones.getNumberFromZoneProperty(aZone, \\\"attackRadius\\\", aZone.radius)\\\
    aZone.attackDelta = cfxZones.getNumberFromZoneProperty(aZone, \\\"attackDelta\\\", 10) -- aZone.radius)\\\
    aZone.attackPhi = cfxZones.getNumberFromZoneProperty(aZone, \\\"attackPhi\\\", 0)\\\
    \\\
    aZone.paused = cfxZones.getBoolFromZoneProperty(aZone, \\\"paused\\\", false)\\\
    aZone.factoryOwner = aZone.owner -- copy so we can compare next round\\\
    \\\
    -- pause? and activate?\\\
    if cfxZones.hasProperty(aZone, \\\"pause?\\\") then \\\
        aZone.pauseFlag = cfxZones.getStringFromZoneProperty(aZone, \\\"pause?\\\", \\\"none\\\")\\\
        aZone.lastPauseValue = trigger.misc.getUserFlag(aZone.pauseFlag)\\\
    end\\\
    \\\
    if cfxZones.hasProperty(aZone, \\\"activate?\\\") then \\\
        aZone.activateFlag = cfxZones.getStringFromZoneProperty(aZone, \\\"activate?\\\", \\\"none\\\")\\\
        aZone.lastActivateValue = trigger.misc.getUserFlag(aZone.activateFlag)\\\
    end\\\
    \\\
    aZone.factoryTriggerMethod = cfxZones.getStringFromZoneProperty(aZone, \\\"triggerMethod\\\", \\\"change\\\")\\\
    if cfxZones.hasProperty(aZone, \\\"factoryTriggerMethod\\\") then \\\
        aZone.factoryTriggerMethod = cfxZones.getStringFromZoneProperty(aZone, \\\"factoryTriggerMethod\\\", \\\"change\\\")\\\
    end\\\
    \\\
    factoryZone.zones[aZone.name] = aZone \\\
    factoryZone.verifyZone(aZone)\\\
end\\\
\\\
function factoryZone.verifyZone(aZone)\\\
    -- do some sanity checks\\\
    if not cfxGroundTroops and (aZone.attackersRED ~= \\\"none\\\" or aZone.attackersBLUE ~= \\\"none\\\") then \\\
        trigger.action.outText(\\\"+++factZ: \\\" .. aZone.name .. \\\" attackers need cfxGroundTroops to function\\\", 30)\\\
    end\\\
    \\\
end\\\
\\\
--[[--\\\
function factoryZone.collectZones(mode)\\\
    if not mode then mode = \\\"OWNED\\\" end \\\
    -- Note: since cfxGroundTroops currently simply uses owner flag\\\
    -- we cannot migrate to a differentiation between factory and \\\
    -- owned. All produced attackers always attack owned zones.\\\
    \\\
    -- collect zones: all zones from DML, ownedZones, factory, owned&factory \\\
    -- controlled with config.targetZones parameter \\\
    -- CLASSIC = factory & target, ALL = all DML, FACTORY = factory zones only, OWNED = owned only.\\\
    if mode == \\\"ALL\\\" then \\\
        return cfxZones.zones\\\
        \\\
    elseif mode == \\\"FACTORY\\\" then\\\
        if cfxOwnedZones and cfxOwnedZones.zones then \\\
            return cfxOwnedZones.zones\\\
        end \\\
        if factoryZone.verbose then \\\
            trigger.action.outText(\\\"+++factZ: 'OWNED' targetZones attribute without cfxOwnedZones. Returning all zones.\\\", 30)\\\
        end\\\
        return cfxZones.zones\\\
        \\\
    elseif mode == \\\"FACTORY\\\" then\\\
        return factoryZone.zones\\\
\\\
    elseif mode == \\\"CLASSIC\\\" then\\\
        if not cfxOwnedZones and cfxOwnedZones.zones then \\\
            return factoryZone.zones \\\
        end\\\
        -- combine ownedZones and factoryZone\\\
        return dcsCommon.combineTables(cfxOwnedZones.zones, factoryZone.zones)\\\
    else \\\
        trigger.action.outText(\\\"+++factZ: illegal targetZones value <\\\" .. factoryZone.targetZones .. \\\">, using 'ALL'\\\", 30)\\\
        return cfxZones.zones \\\
    end\\\
end\\\
\\\
function factoryZone.getEnemyZonesFor(aCoalition) \\\
    -- when cfxOwnedZones is present, or it will return only those \\\
    -- else it scans all zones from cfxZones \\\
    local enemyZones = {}\\\
    local allZones = factoryZone.collectZones() --cfxZones.zones\\\
--    if cfxOwnedZones then \\\
--        allZones = cfxOwnedZones.zones\\\
--    end \\\
    local ourEnemy = dcsCommon.getEnemyCoalitionFor(aCoalition)\\\
    for zKey, aZone in pairs(allZones) do \\\
        if aZone.owner == ourEnemy then -- only check enemy owned zones\\\
            -- note: will include untargetable zones \\\
            table.insert(enemyZones, aZone)            \\\
        end\\\
    end\\\
    return enemyZones\\\
end\\\
\\\
function factoryZone.getNearestOwnedZoneToPoint(aPoint)\\\
    local shortestDist = math.huge\\\
    -- when cfxOwnedZones is present, or it will return only those \\\
    -- else it scans all zones from cfxZones \\\
    local closestZone = nil\\\
    local allZones = factoryZone.collectZones() --cfxZones.zones\\\
--    if cfxOwnedZones then \\\
--        allZones = cfxOwnedZones.zones\\\
--    end \\\
    for zKey, aZone in pairs(allZones) do \\\
        local zPoint = cfxZones.getPoint(aZone) \\\
        currDist = dcsCommon.dist(zPoint, aPoint)\\\
        if aZone.untargetable ~= true and \\\
           currDist < shortestDist then \\\
            shortestDist = currDist\\\
            closestZone = aZone\\\
        end\\\
    end\\\
    \\\
    return closestZone, shortestDist\\\
end\\\
\\\
function factoryZone.getNearestOwnedZone(theZone)\\\
    local shortestDist = math.huge\\\
    -- when cfxOwnedZones is present, or it will return only those \\\
    -- else it scans all zones from cfxZones \\\
    local closestZone = nil\\\
    local aPoint = cfxZones.getPoint(theZone)\\\
    local allZones = factoryZone.collectZones() --cfxZones.zones\\\
--    if cfxOwnedZones then \\\
--        allZones = cfxOwnedZones.zones\\\
--    end \\\
    for zKey, aZone in pairs(allZones) do\\\
        local zPoint = cfxZones.getPoint(aZone) \\\
        currDist = dcsCommon.dist(zPoint, aPoint)\\\
        if aZone.untargetable ~= true and currDist < shortestDist then \\\
            shortestDist = currDist\\\
            closestZone = aZone\\\
        end\\\
    end\\\
    \\\
    return closestZone, shortestDist\\\
end\\\
\\\
function factoryZone.getNearestEnemyOwnedZone(theZone, targetNeutral)\\\
    if not targetNeutral then targetNeutral = false else targetNeutral = true end\\\
    local shortestDist = math.huge\\\
    local closestZone = nil\\\
    -- when cfxOwnedZones is present, or it will return only those \\\
    -- else it scans all zones from cfxZones \\\
    local allZones = factoryZone.collectZones() --cfxZones.zones\\\
--    if cfxOwnedZones then \\\
--        allZones = cfxOwnedZones.zones\\\
--    end \\\
    local ourEnemy = dcsCommon.getEnemyCoalitionFor(theZone.owner)\\\
    if not ourEnemy then return nil end -- we called for a neutral zone. they have no enemies \\\
    local zPoint = cfxZones.getPoint(theZone)\\\
    \\\
    for zKey, aZone in pairs(allZones) do \\\
        if targetNeutral then \\\
            -- return all zones that do not belong to us\\\
            if aZone.owner ~= theZone.owner then \\\
                local aPoint = cfxZones.getPoint(aZone)\\\
                currDist = dcsCommon.dist(aPoint, zPoint)\\\
                if aZone.untargetable ~= true and currDist < shortestDist then \\\
                    shortestDist = currDist\\\
                    closestZone = aZone\\\
                end\\\
            end\\\
        else \\\
            -- return zones that are taken by the Enenmy\\\
            if aZone.owner == ourEnemy then -- only check own zones\\\
                local aPoint = cfxZones.getPoint(aZone)\\\
                currDist = dcsCommon.dist(zPoint, aPoint)\\\
                if aZone.untargetable ~= true and currDist < shortestDist then \\\
                    shortestDist = currDist\\\
                    closestZone = aZone\\\
                end\\\
            end\\\
        end \\\
    end\\\
    \\\
    return closestZone, shortestDist\\\
end\\\
\\\
function factoryZone.getNearestFriendlyZone(theZone, targetNeutral)\\\
    if not targetNeutral then targetNeutral = false else targetNeutral = true end\\\
    local shortestDist = math.huge\\\
    local closestZone = nil\\\
    local ourEnemy = dcsCommon.getEnemyCoalitionFor(theZone.owner)\\\
    if not ourEnemy then return nil end -- we called for a neutral zone. they have no enemies nor friends, all zones would be legal.\\\
    local zPoint = cfxZones.getPoint(theZone)\\\
    -- when cfxOwnedZones is present, or it will return only those \\\
    -- else it scans all zones from cfxZones \\\
    local allZones = factoryZone.collectZones() --cfxZones.zones\\\
--    if cfxOwnedZones then \\\
--        allZones = cfxOwnedZones.zones\\\
--    end\\\
    for zKey, aZone in pairs(allZones) do \\\
        if targetNeutral then \\\
            -- target all zones that do not belong to the enemy\\\
            if aZone.owner ~= ourEnemy then\\\
                local aPoint = cfxZones.getPoint(aZone)\\\
                currDist = dcsCommon.dist(zPoint, aPoint)\\\
                if aZone.untargetable ~= true and currDist < shortestDist then \\\
                    shortestDist = currDist\\\
                    closestZone = aZone\\\
                end\\\
            end\\\
        else \\\
            -- only target zones that are taken by us\\\
            if aZone.owner == theZone.owner then -- only check own zones\\\
                local aPoint = cfxZones.getPoint(aZone)\\\
                currDist = dcsCommon.dist(zPoint, aPoint)\\\
                if aZone.untargetable ~= true and currDist < shortestDist then \\\
                    shortestDist = currDist\\\
                    closestZone = aZone\\\
                end\\\
            end\\\
        end \\\
    end\\\
    \\\
    return closestZone, shortestDist\\\
end\\\
--]]--\\\
--[[--\\\
function factoryZone.enemiesRemaining(aZone)\\\
    if factoryZone.getNearestEnemyOwnedZone(aZone) then return true end\\\
    return false\\\
end\\\
--]]--\\\
\\\
function factoryZone.spawnAttackTroops(theTypes, aZone, aCoalition, aFormation)\\\
    local unitTypes = {} -- build type names\\\
    -- split theTypes into an array of types\\\
    unitTypes = dcsCommon.splitString(theTypes, \\\",\\\")\\\
    if #unitTypes < 1 then \\\
        table.insert(unitTypes, \\\"Soldier M4\\\") -- make it one m4 trooper as fallback\\\
        -- simply exit, no troops specified \\\
        if factoryZone.verbose then \\\
            trigger.action.outText(\\\"+++factZ: no attackers for \\\" .. aZone.name .. \\\". exiting\\\", 30)\\\
        end\\\
        return\\\
    end\\\
    \\\
    if factoryZone.verbose then \\\
        trigger.action.outText(\\\"+++factZ: spawning attackers for \\\" .. aZone.name, 30)\\\
    end\\\
            \\\
    local spawnPoint = {x = aZone.point.x, y = aZone.point.y, z = aZone.point.z} -- copy struct \\\
    \\\
    local rads = aZone.attackPhi * 0.01745\\\
    spawnPoint.x = spawnPoint.x + math.cos(aZone.attackPhi) * aZone.attackDelta\\\
    spawnPoint.y = spawnPoint.y + math.sin(aZone.attackPhi) * aZone.attackDelta \\\
    \\\
    local spawnZone = cfxZones.createSimpleZone(\\\"attkSpawnZone\\\", spawnPoint, aZone.attackRadius)\\\
    \\\
    local theGroup, theData = cfxZones.createGroundUnitsInZoneForCoalition (\\\
                aCoalition, -- theCountry,                            \\\
                aZone.name .. \\\" (A) \\\" .. dcsCommon.numberUUID(), -- must be unique \\\
                spawnZone,                                             \\\
                unitTypes,                                                     \\\
                aFormation, -- outward facing\\\
                0)\\\
    return theGroup, theData\\\
end\\\
\\\
function factoryZone.spawnDefensiveTroops(theTypes, aZone, aCoalition, aFormation)\\\
    local unitTypes = {} -- build type names\\\
    -- split theTypes into an array of types\\\
    unitTypes = dcsCommon.splitString(theTypes, \\\",\\\")\\\
    if #unitTypes < 1 then \\\
        table.insert(unitTypes, \\\"Soldier M4\\\") -- make it one m4 trooper as fallback\\\
        -- simply exit, no troops specified \\\
        if factoryZone.verbose then \\\
            trigger.action.outText(\\\"+++factZ: no defenders for \\\" .. aZone.name .. \\\". exiting\\\", 30)\\\
        end\\\
        return\\\
    end\\\
    \\\
    --local theCountry = dcsCommon.coalition2county(aCoalition) \\\
    local spawnZone = cfxZones.createSimpleZone(\\\"spawnZone\\\", aZone.point, aZone.spawnRadius)\\\
    local theGroup, theData = cfxZones.createGroundUnitsInZoneForCoalition (\\\
                aCoalition, --theCountry,                \\\
                aZone.name .. \\\" (D) \\\" .. dcsCommon.numberUUID(), -- must be unique \\\
                spawnZone,                                         unitTypes,\\\
                aFormation, -- outward facing\\\
                0)\\\
    return theGroup, theData\\\
end\\\
\\\
--\\\
-- U P D A T E \\\
--\\\
\\\
function factoryZone.sendOutAttackers(aZone)\\\
    -- sanity check: never done for neutral zones \\\
    if aZone.owner == 0 then \\\
        if aZone.verbose or factoryZone.verbose then \\\
            trigger.action.outText(\\\"+++factZ: SendAttackers invoked for NEUTRAL zone <\\\" .. aZone.name .. \\\">\\\", 30)\\\
        end\\\
        return \\\
    end\\\
    \\\
    -- only spawn if there are zones to attack\\\
    if not cfxOwnedZones.enemiesRemaining(aZone) then \\\
        if factoryZone.verbose then \\\
            trigger.action.outText(\\\"+++factZ - no enemies, resting \\\".. aZone.name, 30)\\\
        end\\\
        return \\\
    end\\\
\\\
    if factoryZone.verbose then \\\
        trigger.action.outText(\\\"+++factZ - attack cycle for \\\".. aZone.name, 30)\\\
    end\\\
\\\
    -- step one: get the attackers \\\
    local attackers = aZone.attackersRED;\\\
    if (aZone.owner == 2) then attackers = aZone.attackersBLUE end\\\
\\\
    if attackers == \\\"none\\\" then return end \\\
\\\
    local theGroup, theData = factoryZone.spawnAttackTroops(attackers, aZone, aZone.owner, aZone.attackFormation)\\\
    \\\
    local troopData = {}\\\
    troopData.groupData = theData\\\
    troopData.orders = \\\"attackOwnedZone\\\" -- lazy coding! \\\
    troopData.side = aZone.owner\\\
    factoryZone.spawnedAttackers[theData.name] = troopData \\\
    \\\
    -- submit them to ground troops handler as zoneseekers \\\
    -- and our groundTroops module will handle the rest \\\
    if cfxGroundTroops then \\\
        local troops = cfxGroundTroops.createGroundTroops(theGroup)\\\
        troops.orders = \\\"attackOwnedZone\\\"\\\
        troops.side = aZone.owner\\\
        cfxGroundTroops.addGroundTroopsToPool(troops) -- hand off to ground troops\\\
    else \\\
        if factoryZone.verbose then \\\
            trigger.action.outText(\\\"+++ Owned Zones: no ground troops module on send out attackers\\\", 30)\\\
        end \\\
    end\\\
end\\\
\\\
\\\
function factoryZone.repairDefenders(aZone)\\\
    -- sanity check: never done for non-neutral zones \\\
    if aZone.owner == 0 then \\\
        if aZone.verbose or factoryZone.verbose then \\\
            trigger.action.outText(\\\"+++factZ: repairDefenders invoked for NEUTRAL zone <\\\" .. aZone.name .. \\\">\\\", 30)\\\
        end\\\
        return \\\
    end\\\
    \\\
    -- find a unit that is missing from my typestring and replace it \\\
    -- one by one until we are back to full strength\\\
    -- step one: get the defenders and create a type array \\\
    local defenders = aZone.defendersRED;\\\
    if (aZone.owner == 2) then defenders = aZone.defendersBLUE end\\\
    local unitTypes = {} -- build type names\\\
    \\\
    -- if none, we are done\\\
    if defenders == \\\"none\\\" then return end \\\
\\\
    -- split theTypes into an array of types    \\\
    allTypes = dcsCommon.trimArray(\\\
            dcsCommon.splitString(defenders, \\\",\\\")\\\
        )\\\
    local livingTypes = {} -- init to emtpy, so we can add to it if none are alive\\\
    if (aZone.defenders) then \\\
        -- some remain. add one of the killed\\\
        livingTypes = dcsCommon.getGroupTypes(aZone.defenders)\\\
        -- we now iterate over the living types, and remove their \\\
        -- counterparts from the allTypes. We then take the first that \\\
        -- is left\\\
        \\\
        if #livingTypes > 0 then \\\
            for key, aType in pairs (livingTypes) do \\\
                if not dcsCommon.findAndRemoveFromTable(allTypes, aType) then \\\
                    trigger.action.outText(\\\"+++factZ WARNING: found unmatched type <\\\" .. aType .. \\\"> while trying to repair defenders for \\\".. aZone.name, 30)\\\
                else \\\
                    -- all good\\\
                end \\\
            end\\\
        end \\\
    end\\\
    \\\
    -- when we get here, allTypes is reduced to those that have been killed \\\
    if #allTypes < 1 then \\\
        trigger.action.outText(\\\"+++factZ: WARNING: all types exist when repairing defenders for \\\".. aZone.name, 30)\\\
    else \\\
        table.insert(livingTypes, allTypes[1]) -- we simply use the first that we find\\\
    end\\\
    -- remove the old defenders\\\
    if aZone.defenders then \\\
        aZone.defenders:destroy()\\\
    end\\\
    \\\
    -- now livingTypes holds the full array of units we need to spawn \\\
    local theCountry = dcsCommon.getACountryForCoalition(aZone.owner) \\\
    local spawnZone = cfxZones.createSimpleZone(\\\"spawnZone\\\", aZone.point, aZone.spawnRadius)\\\
    local theGroup, theData = cfxZones.createGroundUnitsInZoneForCoalition (\\\
                aZone.owner, -- was wrongly: theCountry        \\\
                aZone.name .. dcsCommon.numberUUID(), -- must be unique \\\
                spawnZone,                                             \\\
                livingTypes, \\\
                \\\
                aZone.formation, -- outward facing\\\
                0)\\\
    aZone.defenders = theGroup\\\
    aZone.lastDefenders = theGroup:getSize()\\\
end\\\
\\\
function factoryZone.inShock(aZone)\\\
    -- a unit was destroyed, everyone else is in shock, no rerpairs \\\
    -- group can re-shock when another unit is destroyed \\\
end\\\
\\\
function factoryZone.spawnDefenders(aZone)\\\
    -- sanity check: never done for non-neutral zones \\\
    if aZone.owner == 0 then \\\
        if aZone.verbose or factoryZone.verbose then \\\
            trigger.action.outText(\\\"+++factZ: spawnDefenders invoked for NEUTRAL zone <\\\" .. aZone.name .. \\\">\\\", 30)\\\
        end\\\
        return \\\
    end\\\
    \\\
    local defenders = aZone.defendersRED;\\\
    \\\
    if (aZone.owner == 2) then defenders = aZone.defendersBLUE end\\\
    -- before we spawn new defenders, remove the old ones\\\
    if aZone.defenders then \\\
        if aZone.defenders:isExist() then \\\
            aZone.defenders:destroy()\\\
        end\\\
        aZone.defenders = nil\\\
    end\\\
    \\\
    -- if 'none', simply exit\\\
    if defenders == \\\"none\\\" then return end\\\
    \\\
    local theGroup, theData = factoryZone.spawnDefensiveTroops(defenders, aZone, aZone.owner, aZone.formation)\\\
    -- the troops reamin, so no orders to move, no handing off to ground troop manager\\\
    aZone.defenders = theGroup\\\
    aZone.defenderData = theData -- used for persistence \\\
    if theGroup then \\\
        aZone.lastDefenders = theGroup:getInitialSize() \\\
    else \\\
        trigger.action.outText(\\\"+++factZ: WARNING: spawned no defenders for \\\".. aZone.name, 30)\\\
        aZone.defenderData = nil \\\
    end \\\
end\\\
\\\
--\\\
-- per-zone update, run down the FSM to determine what to do.\\\
-- FSM uses timeStamp since when state was set. Possible states are \\\
--    - init -- has just been inited for the first time. will usually immediately produce defenders, \\\
--    and then transition to defending \\\
--  - catured -- has just been captured. transition to defending \\\
--  - defending -- wait until timer has reached goal, then produce defending units and transition to attacking. \\\
--  - attacking -- wait until timer has reached goal, and then produce attacking units and send them to closest enemy zone.\\\
--                 state is interrupted as soon as a defensive unit is lost. state then goes to defending with timer starting\\\
--  - idle - do nothing, zone's actions are turned off \\\
--  - shocked -- a unit was destroyed. group is in shock for a time until it starts repairing. If another unit is \\\
--               destroyed during the shocked period, the timer resets to zero and repairs are delayed\\\
--  - repairing -- as long as we aren't at full strength, units get replaced one by one until at full strength\\\
--                 each time the timer counts down, another missing unit is replaced, and all other unit's health \\\
--                 is reset to 100%\\\
--  \\\
--  a Zone with the paused attribute set to true will cause it to not do anything \\\
--\\\
-- check if defenders are specified\\\
function factoryZone.usesDefenders(aZone) \\\
    if aZone.owner == 0 then return false end \\\
    local defenders = aZone.defendersRED;    \\\
    if (aZone.owner == 2) then defenders = aZone.defendersBLUE end\\\
    return defenders ~= \\\"none\\\"\\\
end\\\
\\\
function factoryZone.usesAttackers(aZone) \\\
    if aZone.owner == 0 then return false end \\\
    local attackers = aZone.attackersRED;    \\\
    if (aZone.owner == 2) then defenders = aZone.attackersBLUE end\\\
    return attackers ~= \\\"none\\\"\\\
end\\\
\\\
function factoryZone.updateZoneProduction(aZone)\\\
    -- a zone can be paused, causing it to not progress anything\\\
    -- even if zone status is still init, will NOT produce anything\\\
    -- if paused is on.\\\
    if aZone.paused then return end \\\
\\\
    nextState = aZone.state;\\\
    \\\
    -- first, check if my defenders have been attacked and one of them has been killed\\\
    -- if so, we immediately switch to 'shocked' \\\
    if factoryZone.usesDefenders(aZone) and \\\
       aZone.defenders then \\\
        -- we have defenders\\\
        if aZone.defenders:isExist() then\\\
            -- isee if group was damaged \\\
            if not aZone.lastDefenders then\\\
                -- fresh group, probably from persistence, needs init \\\
                aZone.lastDefenders = -1 \\\
            end \\\
            if aZone.defenders:getSize() < aZone.lastDefenders then \\\
                -- yes, at least one unit destroyed\\\
                aZone.timeStamp = timer.getTime()\\\
                aZone.lastDefenders = aZone.defenders:getSize()\\\
                if aZone.lastDefenders == 0 then \\\
                    aZone.defenders = nil\\\
                end\\\
                aZone.state = \\\"shocked\\\"\\\
\\\
                return \\\
            else \\\
                aZone.lastDefenders = aZone.defenders:getSize()\\\
            end\\\
            \\\
        else \\\
            -- group was destroyed. erase link, and go into shock for the last time \\\
            aZone.state = \\\"shocked\\\"\\\
            aZone.timeStamp = timer.getTime()\\\
            aZone.lastDefenders = 0\\\
            aZone.defenders = nil\\\
            return \\\
        end\\\
    end\\\
    \\\
    \\\
    if aZone.state == \\\"init\\\" then \\\
        -- during init we instantly create the defenders since \\\
        -- we assume the zone existed already \\\
        if aZone.owner > 0 then \\\
            factoryZone.spawnDefenders(aZone)\\\
            -- now drop into attacking mode to produce attackers\\\
            nextState = \\\"attacking\\\"\\\
        else \\\
            nextState = \\\"idle\\\"\\\
        end\\\
        aZone.timeStamp = timer.getTime()\\\
    \\\
    elseif aZone.state == \\\"idle\\\" then\\\
        -- nothing to do, zone is effectively switched off.\\\
        -- used for neutal zones or when forced to turn off\\\
        -- in some special cases \\\
        \\\
    elseif aZone.state == \\\"captured\\\" then \\\
        -- start the clock on defenders\\\
        nextState = \\\"defending\\\"\\\
        aZone.timeStamp = timer.getTime()\\\
        if factoryZone.verbose then \\\
            trigger.action.outText(\\\"+++factZ: State \\\" .. aZone.state .. \\\" to \\\" .. nextState .. \\\" for \\\" .. aZone.name, 30)\\\
        end \\\
    elseif aZone.state == \\\"defending\\\" then \\\
        if timer.getTime() > aZone.timeStamp + factoryZone.defendingTime then \\\
            factoryZone.spawnDefenders(aZone)\\\
            -- now drop into attacking mode to produce attackers\\\
            nextState = \\\"attacking\\\"\\\
            aZone.timeStamp = timer.getTime()\\\
            if factoryZone.verbose then \\\
                trigger.action.outText(\\\"+++factZ: State \\\" .. aZone.state .. \\\" to \\\" .. nextState .. \\\" for \\\" .. aZone.name, 30)\\\
            end\\\
        end\\\
\\\
    elseif aZone.state == \\\"repairing\\\" then \\\
        -- we are currently rebuilding defenders unit by unit \\\
        if timer.getTime() > aZone.timeStamp + factoryZone.repairTime then \\\
            aZone.timeStamp = timer.getTime()\\\
            -- wait's up, repair one defender, then check if full strength\\\
            factoryZone.repairDefenders(aZone)\\\
            -- see if we are full strenght and if so go to attack, else set timer to reair the next unit\\\
            if aZone.defenders and aZone.defenders:isExist() and aZone.defenders:getSize() >= aZone.defenders:getInitialSize() then\\\
                -- we are at max size, time to produce some attackers\\\
                -- progress to next state \\\
                nextState = \\\"attacking\\\"\\\
                aZone.timeStamp = timer.getTime()\\\
                if factoryZone.verbose then \\\
                    trigger.action.outText(\\\"+++factZ: State \\\" .. aZone.state .. \\\" to \\\" .. nextState .. \\\" for \\\" .. aZone.name, 30)\\\
                end\\\
            end\\\
\\\
        end\\\
        \\\
    elseif aZone.state == \\\"shocked\\\" then \\\
        -- we are currently rebuilding defenders unit by unit \\\
        if timer.getTime() > aZone.timeStamp + factoryZone.shockTime then \\\
            nextState = \\\"repairing\\\"\\\
            aZone.timeStamp = timer.getTime()\\\
            if factoryZone.verbose then \\\
                trigger.action.outText(\\\"+++factZ: State \\\" .. aZone.state .. \\\" to \\\" .. nextState .. \\\" for \\\" .. aZone.name, 30)\\\
            end\\\
        end\\\
        \\\
    elseif aZone.state == \\\"attacking\\\" then \\\
        if timer.getTime() > aZone.timeStamp + factoryZone.attackingTime then \\\
            factoryZone.sendOutAttackers(aZone)\\\
            -- reset timer\\\
            aZone.timeStamp = timer.getTime()\\\
            if factoryZone.verbose then \\\
                trigger.action.outText(\\\"+++factZ: State \\\" .. aZone.state .. \\\" reset for \\\" .. aZone.name, 30)\\\
            end\\\
        end\\\
    else \\\
        -- unknown zone state \\\
    end\\\
    aZone.state = nextState\\\
end\\\
\\\
function factoryZone.GC()\\\
    -- GC run. remove all my dead remembered troops\\\
    local before = #factoryZone.spawnedAttackers\\\
    local filteredAttackers = {}\\\
    for gName, gData in pairs (factoryZone.spawnedAttackers) do \\\
        -- all we need to do is get the group of that name\\\
        -- and if it still returns units we are fine \\\
        local gameGroup = Group.getByName(gName)\\\
        if gameGroup and gameGroup:isExist() and gameGroup:getSize() > 0 then \\\
            filteredAttackers[gName] = gData\\\
        end\\\
    end\\\
    factoryZone.spawnedAttackers = filteredAttackers\\\
    if factoryZone.verbose then \\\
        trigger.action.outText(\\\"owned zones GC ran: before <\\\" .. before .. \\\">, after <\\\" .. #factoryZone.spawnedAttackers .. \\\">\\\", 30)\\\
    end\\\
end\\\
\\\
function factoryZone.update()\\\
    factoryZone.updateSchedule = timer.scheduleFunction(factoryZone.update, {}, timer.getTime() + 1/factoryZone.ups)\\\
    -- iterate all zones to see if ownership has \\\
    -- changed \\\
\\\
    for idz, theZone in pairs(factoryZone.zones) do \\\
        local lastOwner = theZone.factoryOwner\\\
        local newOwner = theZone.owner \\\
        if (newOwner ~= lastOwner) then \\\
            theZone.state = \\\"captured\\\"\\\
            theZone.timeStamp = timer.getTime()\\\
            theZone.factoryOwner = theZone.owner \\\
            if theZone.verbose or factoryZone.verbose then \\\
                trigger.action.outText(\\\"+++factZ: detected factory <\\\" .. theZone.name .. \\\"> changed ownership from <\\\" .. lastOwner .. \\\"> to <\\\" .. theZone.owner .. \\\">\\\", 30)\\\
            end\\\
        end\\\
        \\\
        -- see if pause/unpause was issued\\\
        if theZone.pauseFlag and cfxZones.testZoneFlag(theZone, theZone.pauseFlag, theZone.factoryTriggerMethod, \\\"lastPauseValue\\\") then\\\
            theZone.paused = true \\\
        end\\\
        \\\
        if theZone.activateFlag and cfxZones.testZoneFlag(theZone, theZone.activateFlag, theZone.factoryTriggerMethod, \\\"lastActivateValue\\\") then\\\
            theZone.paused = false \\\
        end\\\
        -- do production for this zone \\\
        factoryZone.updateZoneProduction(theZone)\\\
    end -- iterating all zones \\\
end\\\
\\\
function factoryZone.houseKeeping()\\\
    timer.scheduleFunction(factoryZone.houseKeeping, {}, timer.getTime() + 5 * 60) -- every 5 minutes \\\
    factoryZone.GC()\\\
end\\\
\\\
\\\
--\\\
-- load / save data \\\
--\\\
\\\
function factoryZone.saveData()\\\
    -- this is called from persistence when it's time to \\\
    -- save data. returns a table with all my data \\\
    local theData = {}\\\
    local allZoneData = {}\\\
    -- iterate all my zones and create data \\\
    for idx, theZone in pairs(factoryZone.zones) do\\\
        local zoneData = {}\\\
        if theZone.defenderData then \\\
            zoneData.defenderData = dcsCommon.clone(theZone.defenderData)\\\
            dcsCommon.synchGroupData(zoneData.defenderData)\\\
        end \\\
        zoneData.owner = theZone.owner \\\
        zoneData.state = theZone.state -- will prevent immediate spawn\\\
            -- since new zones are spawned with 'init'\\\
        allZoneData[theZone.name] = zoneData\\\
    end\\\
    \\\
    -- now iterate all attack groups that we have spawned and that \\\
    -- (maybe) are still alive \\\
    factoryZone.GC() -- start with a GC run to remove all dead \\\
    local livingAttackers = {}\\\
    for gName, gData in pairs (factoryZone.spawnedAttackers) do \\\
        -- all we need to do is get the group of that name\\\
        -- and if it still returns units we are fine \\\
        -- spawnedAttackers is a [groupName] table with {.groupData, .orders, .side}\\\
        local gameGroup = Group.getByName(gName)\\\
        if gameGroup and gameGroup:isExist() then \\\
            if gameGroup:getSize() > 0 then \\\
                local sData = dcsCommon.clone(gData)\\\
                dcsCommon.synchGroupData(sData.groupData)\\\
                livingAttackers[gName] = sData\\\
            end\\\
        end\\\
    end\\\
    \\\
    -- now write the info for the flags that we output for #red, etc\\\
    local flagInfo = {} -- no longer used \\\
\\\
    -- assemble the data \\\
    theData.zoneData = allZoneData\\\
    theData.attackers = livingAttackers\\\
    theData.flagInfo = flagInfo\\\
    \\\
    -- return it \\\
    return theData\\\
end\\\
\\\
function factoryZone.loadData()\\\
    -- remember to draw in map with new owner \\\
    if not persistence then return end \\\
    local theData = persistence.getSavedDataForModule(\\\"factoryZone\\\")\\\
    if not theData then \\\
        if factoryZone.verbose then \\\
            trigger.action.outText(\\\"factZ: no save date received, skipping.\\\", 30)\\\
        end\\\
        return\\\
    end\\\
    -- theData contains the following tables:\\\
    --   zoneData: per-zone data \\\
    --   flagInfo: module-global flags \\\
    --   attackers: all spawned attackers that we feed to groundTroops\\\
    local allZoneData = theData.zoneData \\\
    for zName, zData in pairs(allZoneData) do \\\
        -- access zone \\\
        local theZone = factoryZone.getOwnedZoneByName(zName)\\\
        if theZone then \\\
            if zData.defenderData then \\\
                if theZone.defenders and theZone.defenders:isExist() then\\\
                    -- should not happen, but so be it\\\
                    theZone.defenders:destroy()\\\
                end\\\
                local gData = zData.defenderData\\\
                local cty = gData.cty \\\
                local cat = gData.cat \\\
                theZone.defenders = coalition.addGroup(cty, cat, gData)\\\
                theZone.defenderData = zData.defenderData\\\
            end\\\
            theZone.owner = zData.owner \\\
            theZone.factoryOwner = theZone.owner \\\
            theZone.state = zData.state \\\
\\\
        else \\\
            trigger.action.outText(\\\"factZ: load - data mismatch: cannot find zone <\\\" .. zName .. \\\">, skipping zone.\\\", 30)\\\
        end\\\
    end\\\
    \\\
    -- now process all attackers \\\
    local allAttackers = theData.attackers\\\
    for gName, gdTroop in pairs(allAttackers) do \\\
        -- table is {.groupData, .orders, .side}\\\
        local gData = gdTroop.groupData \\\
        local orders = gdTroop.orders \\\
        local side = gdTroop.side \\\
        local cty = gData.cty \\\
        local cat = gData.cat \\\
        -- add to my own attacker queue so we can save later \\\
        local dClone = dcsCommon.clone(gdTroop)\\\
        factoryZone.spawnedAttackers[gName] = dClone \\\
        local theGroup = coalition.addGroup(cty, cat, gData)\\\
        if cfxGroundTroops then \\\
            local troops = cfxGroundTroops.createGroundTroops(theGroup)\\\
            troops.orders = orders\\\
            troops.side = side\\\
            cfxGroundTroops.addGroundTroopsToPool(troops) -- hand off to ground troops\\\
        end \\\
    end\\\
    \\\
    -- now process module global flags \\\
    local flagInfo = theData.flagInfo\\\
    if flagInfo then \\\
    end\\\
end\\\
\\\
 \\\
--\\\
function factoryZone.readConfigZone(theZone)\\\
    if not theZone then theZone = cfxZones.createSimpleZone(\\\"factoryZoneConfig\\\") end \\\
    factoryZone.name = \\\"factoryZone\\\" -- just in case, so we can access with cfxZones \\\
    factoryZone.verbose = cfxZones.getBoolFromZoneProperty(theZone, \\\"verbose\\\", false)\\\
    factoryZone.defendingTime = cfxZones.getNumberFromZoneProperty(theZone, \\\"defendingTime\\\", 100)\\\
    factoryZone.attackingTime = cfxZones.getNumberFromZoneProperty(theZone, \\\"attackingTime\\\", 300)\\\
    factoryZone.shockTime = cfxZones.getNumberFromZoneProperty(theZone, \\\"shockTime\\\", 200)\\\
    factoryZone.repairTime = cfxZones.getNumberFromZoneProperty(theZone, \\\"repairTime\\\", 200)\\\
    factoryZone.targetZones = \\\"OWNED\\\"\\\
    --[[\\\
    factoryZone.targetZones = string.upper(cfxZones.getStringFromZoneProperty(theZone, \\\"targetZones\\\", \\\"owned\\\")) -- CLASSIC = factory & target, ALL = all DML, FACTORY = factory zones only, OWNED = owned only.\\\
    if factoryZone.targetZones ~= \\\"CLASSIC\\\" and factoryZone.targetZones ~= \\\"ALL\\\" and factoryZone.targetZones ~= \\\"FACTORY\\\" and factoryZone.targetZones ~= \\\"OWNED\\\" then \\\
        trigger.action.outText(\\\"+++factZ: illegal 'targetZones' attribute value <>, using 'classic' instead.\\\", 30)\\\
        factoryZone.targetZones = \\\"CLASSIC\\\" \\\
    end\\\
    --]]\\\
end\\\
\\\
function factoryZone.init()\\\
    -- check libs\\\
    if not dcsCommon.libCheck(\\\"cfx Factory Zones\\\", \\\
        factoryZone.requiredLibs) then\\\
        return false \\\
    end\\\
\\\
    -- read my config zone\\\
    local theZone = cfxZones.getZoneByName(\\\"factoryZoneConfig\\\") \\\
    factoryZone.readConfigZone(theZone)\\\
\\\
    -- collect all zones by their 'factory' property \\\
    -- start the process\\\
    local pZones = cfxZones.zonesWithProperty(\\\"factory\\\")\\\
    \\\
    -- now add all zones to my zones table, and convert the owner property into \\\
    -- a proper attribute \\\
    for k, aZone in pairs(pZones) do\\\
        factoryZone.addFactoryZone(aZone)\\\
    end\\\
    \\\
    if persistence then \\\
        -- sign up for persistence \\\
        callbacks = {}\\\
        callbacks.persistData = factoryZone.saveData\\\
        persistence.registerModule(\\\"factoryZone\\\", callbacks)\\\
        -- now load my data \\\
        factoryZone.loadData()\\\
    end\\\
    \\\
    initialized = true \\\
    factoryZone.updateSchedule = timer.scheduleFunction(factoryZone.update, {}, timer.getTime() + 1/factoryZone.ups)\\\
    \\\
    -- start housekeeping \\\
    factoryZone.houseKeeping()\\\
    \\\
    trigger.action.outText(\\\"cx/x factory zones v\\\".. factoryZone.version .. \\\" started\\\", 30)\\\
    \\\
    return true \\\
end\\\
\\\
if not factoryZone.init() then \\\
    trigger.action.outText(\\\"cf/x Factory Zones aborted: missing libraries\\\", 30)\\\
    factoryZone = nil \\\
end\\\
\\\
\\\
-- add property to factory attribute to restrict production to that side, \\\
-- eg factory blue will only work for blue, else will work for any side \\\
-- currently not needed since we have defendersRED/BLUE and productionRED/BLUE\\\
\");",
            [2] = "a_out_text_delay(getValueDictByKey(\"DictKey_ActionText_6\"), 30, false, 0); mission.trig.func[2]=nil;",
            [3] = "a_out_text_delay(getValueDictByKey(\"DictKey_ActionText_7\"), 30, false, 0); mission.trig.func[3]=nil;",
        }, -- end of ["actions"]
        ["events"] = 
        {
        }, -- end of ["events"]
        ["custom"] = 
        {
        }, -- end of ["custom"]
        ["func"] = 
        {
            [2] = "if mission.trig.conditions[2]() then mission.trig.actions[2]() end",
            [3] = "if mission.trig.conditions[3]() then mission.trig.actions[3]() end",
        }, -- end of ["func"]
        ["flag"] = 
        {
            [1] = true,
            [2] = true,
            [3] = true,
        }, -- end of ["flag"]
        ["conditions"] = 
        {
            [1] = "return(true)",
            [2] = "return(c_flag_equals(10, 1) )",
            [3] = "return(c_flag_equals(10, 2) )",
        }, -- end of ["conditions"]
        ["customStartup"] = 
        {
        }, -- end of ["customStartup"]
        ["funcStartup"] = 
        {
            [1] = "if mission.trig.conditions[1]() then mission.trig.actions[1]() end",
        }, -- end of ["funcStartup"]
    }, -- end of ["trig"]
    ["pictureFileNameN"] = 
    {
    }, -- end of ["pictureFileNameN"]
    ["groundControl"] = 
    {
        ["passwords"] = 
        {
            ["artillery_commander"] = 
            {
            }, -- end of ["artillery_commander"]
            ["instructor"] = 
            {
            }, -- end of ["instructor"]
            ["observer"] = 
            {
            }, -- end of ["observer"]
            ["forward_observer"] = 
            {
            }, -- end of ["forward_observer"]
        }, -- end of ["passwords"]
        ["roles"] = 
        {
            ["artillery_commander"] = 
            {
                ["neutrals"] = 0,
                ["blue"] = 0,
                ["red"] = 0,
            }, -- end of ["artillery_commander"]
            ["instructor"] = 
            {
                ["neutrals"] = 0,
                ["blue"] = 0,
                ["red"] = 0,
            }, -- end of ["instructor"]
            ["observer"] = 
            {
                ["neutrals"] = 0,
                ["blue"] = 0,
                ["red"] = 0,
            }, -- end of ["observer"]
            ["forward_observer"] = 
            {
                ["neutrals"] = 0,
                ["blue"] = 0,
                ["red"] = 0,
            }, -- end of ["forward_observer"]
        }, -- end of ["roles"]
        ["isPilotControlVehicles"] = false,
    }, -- end of ["groundControl"]
    ["descriptionBlueTask"] = "DictKey_descriptionBlueTask_3",
    ["weather"] = 
    {
        ["atmosphere_type"] = 0,
        ["wind"] = 
        {
            ["at8000"] = 
            {
                ["speed"] = 0,
                ["dir"] = 0,
            }, -- end of ["at8000"]
            ["atGround"] = 
            {
                ["speed"] = 0,
                ["dir"] = 0,
            }, -- end of ["atGround"]
            ["at2000"] = 
            {
                ["speed"] = 0,
                ["dir"] = 0,
            }, -- end of ["at2000"]
        }, -- end of ["wind"]
        ["enable_fog"] = false,
        ["groundTurbulence"] = 0,
        ["halo"] = 
        {
            ["preset"] = "off",
        }, -- end of ["halo"]
        ["visibility"] = 
        {
            ["distance"] = 80000,
        }, -- end of ["visibility"]
        ["season"] = 
        {
            ["temperature"] = 20,
        }, -- end of ["season"]
        ["type_weather"] = 0,
        ["modifiedTime"] = false,
        ["cyclones"] = 
        {
        }, -- end of ["cyclones"]
        ["name"] = "Winter, clean sky",
        ["fog"] = 
        {
            ["thickness"] = 0,
            ["visibility"] = 0,
        }, -- end of ["fog"]
        ["qnh"] = 760,
        ["dust_density"] = 0,
        ["enable_dust"] = false,
        ["clouds"] = 
        {
            ["thickness"] = 200,
            ["density"] = 0,
            ["preset"] = "Preset2",
            ["base"] = 2500,
            ["iprecptns"] = 0,
        }, -- end of ["clouds"]
    }, -- end of ["weather"]
    ["theatre"] = "Caucasus",
    ["triggers"] = 
    {
        ["zones"] = 
        {
            [1] = 
            {
                ["radius"] = 500,
                ["zoneId"] = 165,
                ["color"] = 
                {
                    [1] = 1,
                    [2] = 1,
                    [3] = 1,
                    [4] = 0.15,
                }, -- end of ["color"]
                ["properties"] = 
                {
                    [1] = 
                    {
                        ["key"] = "factory",
                        ["value"] = "",
                    }, -- end of [1]
                    [2] = 
                    {
                        ["key"] = "owner",
                        ["value"] = "blue",
                    }, -- end of [2]
                    [3] = 
                    {
                        ["key"] = "defendersBLUE",
                        ["value"] = "Soldier M4",
                    }, -- end of [3]
                    [4] = 
                    {
                        ["key"] = "spawnRadius",
                        ["value"] = "5",
                    }, -- end of [4]
                    [5] = 
                    {
                        ["key"] = "attackersRED",
                        ["value"] = "BTR-80, BTR-80",
                    }, -- end of [5]
                    [6] = 
                    {
                        ["key"] = "defendersRED",
                        ["value"] = "Soldier M4",
                    }, -- end of [6]
                    [7] = 
                    {
                        ["key"] = "attackRadius",
                        ["value"] = "10",
                    }, -- end of [7]
                }, -- end of ["properties"]
                ["hidden"] = false,
                ["y"] = 647068.71144389,
                ["x"] = -284992.19590595,
                ["name"] = "Blue Owned One",
                ["type"] = 0,
            }, -- end of [1]
            [2] = 
            {
                ["radius"] = 500,
                ["zoneId"] = 330,
                ["color"] = 
                {
                    [1] = 1,
                    [2] = 1,
                    [3] = 1,
                    [4] = 0.15,
                }, -- end of ["color"]
                ["properties"] = 
                {
                    [1] = 
                    {
                        ["key"] = "owner",
                        ["value"] = "Blue",
                    }, -- end of [1]
                }, -- end of ["properties"]
                ["hidden"] = false,
                ["y"] = 647917.30074869,
                ["x"] = -284309.60055754,
                ["name"] = "Blue Owned Two",
                ["type"] = 0,
            }, -- end of [2]
            [3] = 
            {
                ["radius"] = 1000,
                ["zoneId"] = 331,
                ["color"] = 
                {
                    [1] = 1,
                    [2] = 1,
                    [3] = 0,
                    [4] = 0.14901960784314,
                }, -- end of ["color"]
                ["properties"] = 
                {
                    [1] = 
                    {
                        ["key"] = "r!",
                        ["value"] = "10",
                    }, -- end of [1]
                    [2] = 
                    {
                        ["key"] = "verbose",
                        ["value"] = "no",
                    }, -- end of [2]
                }, -- end of ["properties"]
                ["hidden"] = false,
                ["y"] = 650683.0217482,
                ["x"] = -281180.55598214,
                ["name"] = "ownedZonesConfig",
                ["type"] = 0,
            }, -- end of [3]
            [4] = 
            {
                ["radius"] = 1000,
                ["zoneId"] = 496,
                ["color"] = 
                {
                    [1] = 1,
                    [2] = 1,
                    [3] = 0,
                    [4] = 0.14901960784314,
                }, -- end of ["color"]
                ["properties"] = 
                {
                    [1] = 
                    {
                        ["key"] = "r!",
                        ["value"] = "10",
                    }, -- end of [1]
                    [2] = 
                    {
                        ["key"] = "attackingTime",
                        ["value"] = "15",
                    }, -- end of [2]
                    [3] = 
                    {
                        ["key"] = "defendingTime",
                        ["value"] = "10",
                    }, -- end of [3]
                    [4] = 
                    {
                        ["key"] = "shockTime",
                        ["value"] = "10",
                    }, -- end of [4]
                    [5] = 
                    {
                        ["key"] = "verbose",
                        ["value"] = "no",
                    }, -- end of [5]
                }, -- end of ["properties"]
                ["hidden"] = false,
                ["y"] = 650806.08846831,
                ["x"] = -283320.7801561,
                ["name"] = "factoryZoneConfig",
                ["heading"] = 0,
                ["type"] = 0,
            }, -- end of [4]
        }, -- end of ["zones"]
    }, -- end of ["triggers"]
    ["map"] = 
    {
        ["centerY"] = 647572.67813086,
        ["zoom"] = 30098.234524175,
        ["centerX"] = -282766.1126913,
    }, -- end of ["map"]
    ["coalitions"] = 
    {
        ["blue"] = 
        {
            [1] = 21,
            [2] = 11,
            [3] = 8,
            [4] = 80,
            [5] = 28,
            [6] = 26,
            [7] = 13,
            [8] = 5,
            [9] = 16,
            [10] = 6,
            [11] = 15,
            [12] = 20,
            [13] = 12,
            [14] = 40,
            [15] = 45,
            [16] = 9,
            [17] = 46,
            [18] = 10,
            [19] = 3,
            [20] = 4,
            [21] = 1,
            [22] = 2,
        }, -- end of ["blue"]
        ["neutrals"] = 
        {
            [1] = 70,
            [2] = 83,
            [3] = 23,
            [4] = 65,
            [5] = 86,
            [6] = 64,
            [7] = 25,
            [8] = 63,
            [9] = 76,
            [10] = 84,
            [11] = 29,
            [12] = 62,
            [13] = 30,
            [14] = 78,
            [15] = 87,
            [16] = 31,
            [17] = 61,
            [18] = 32,
            [19] = 33,
            [20] = 60,
            [21] = 17,
            [22] = 35,
            [23] = 69,
            [24] = 36,
            [25] = 59,
            [26] = 71,
            [27] = 79,
            [28] = 58,
            [29] = 57,
            [30] = 56,
            [31] = 55,
            [32] = 88,
            [33] = 73,
            [34] = 39,
            [35] = 89,
            [36] = 54,
            [37] = 77,
            [38] = 72,
            [39] = 41,
            [40] = 42,
            [41] = 44,
            [42] = 85,
            [43] = 75,
            [44] = 53,
            [45] = 22,
            [46] = 52,
            [47] = 66,
            [48] = 51,
            [49] = 74,
            [50] = 82,
            [51] = 7,
            [52] = 68,
            [53] = 50,
            [54] = 49,
            [55] = 48,
            [56] = 67,
            [57] = 90,
        }, -- end of ["neutrals"]
        ["red"] = 
        {
            [1] = 18,
            [2] = 24,
            [3] = 27,
            [4] = 81,
            [5] = 34,
            [6] = 37,
            [7] = 38,
            [8] = 0,
            [9] = 43,
            [10] = 19,
            [11] = 47,
        }, -- end of ["red"]
    }, -- end of ["coalitions"]
    ["descriptionText"] = "DictKey_descriptionText_1",
    ["pictureFileNameR"] = 
    {
    }, -- end of ["pictureFileNameR"]
    ["goals"] = 
    {
    }, -- end of ["goals"]
    ["descriptionNeutralsTask"] = "DictKey_descriptionNeutralsTask_4",
    ["descriptionRedTask"] = "DictKey_descriptionRedTask_2",
    ["pictureFileNameB"] = 
    {
    }, -- end of ["pictureFileNameB"]
    ["coalition"] = 
    {
        ["blue"] = 
        {
            ["bullseye"] = 
            {
                ["y"] = 617414,
                ["x"] = -291014,
            }, -- end of ["bullseye"]
            ["nav_points"] = 
            {
            }, -- end of ["nav_points"]
            ["name"] = "blue",
            ["country"] = 
            {
            }, -- end of ["country"]
        }, -- end of ["blue"]
        ["neutrals"] = 
        {
            ["bullseye"] = 
            {
                ["y"] = 0,
                ["x"] = 0,
            }, -- end of ["bullseye"]
            ["nav_points"] = 
            {
            }, -- end of ["nav_points"]
            ["name"] = "neutrals",
            ["country"] = 
            {
            }, -- end of ["country"]
        }, -- end of ["neutrals"]
        ["red"] = 
        {
            ["bullseye"] = 
            {
                ["y"] = 371700,
                ["x"] = 11557,
            }, -- end of ["bullseye"]
            ["nav_points"] = 
            {
            }, -- end of ["nav_points"]
            ["name"] = "red",
            ["country"] = 
            {
                [1] = 
                {
                    ["id"] = 81,
                    ["name"] = "CJTF Red",
                    ["plane"] = 
                    {
                        ["group"] = 
                        {
                            [1] = 
                            {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["radioSet"] = false,
                                ["task"] = "CAS",
                                ["uncontrolled"] = false,
                                ["route"] = 
                                {
                                    ["points"] = 
                                    {
                                        [1] = 
                                        {
                                            ["alt"] = 2000,
                                            ["action"] = "From Ground Area Hot",
                                            ["alt_type"] = "BARO",
                                            ["properties"] = 
                                            {
                                                ["addopt"] = 
                                                {
                                                }, -- end of ["addopt"]
                                            }, -- end of ["properties"]
                                            ["speed"] = 180.55555555556,
                                            ["task"] = 
                                            {
                                                ["id"] = "ComboTask",
                                                ["params"] = 
                                                {
                                                    ["tasks"] = 
                                                    {
                                                        [1] = 
                                                        {
                                                            ["enabled"] = true,
                                                            ["key"] = "CAS",
                                                            ["id"] = "EngageTargets",
                                                            ["number"] = 1,
                                                            ["auto"] = true,
                                                            ["params"] = 
                                                            {
                                                                ["targetTypes"] = 
                                                                {
                                                                    [1] = "Helicopters",
                                                                    [2] = "Ground Units",
                                                                    [3] = "Light armed ships",
                                                                }, -- end of ["targetTypes"]
                                                                ["priority"] = 0,
                                                            }, -- end of ["params"]
                                                        }, -- end of [1]
                                                        [2] = 
                                                        {
                                                            ["enabled"] = true,
                                                            ["auto"] = true,
                                                            ["id"] = "WrappedAction",
                                                            ["number"] = 2,
                                                            ["params"] = 
                                                            {
                                                                ["action"] = 
                                                                {
                                                                    ["id"] = "Option",
                                                                    ["params"] = 
                                                                    {
                                                                        ["value"] = 2,
                                                                        ["name"] = 1,
                                                                    }, -- end of ["params"]
                                                                }, -- end of ["action"]
                                                            }, -- end of ["params"]
                                                        }, -- end of [2]
                                                        [3] = 
                                                        {
                                                            ["enabled"] = true,
                                                            ["auto"] = true,
                                                            ["id"] = "WrappedAction",
                                                            ["number"] = 3,
                                                            ["params"] = 
                                                            {
                                                                ["action"] = 
                                                                {
                                                                    ["id"] = "Option",
                                                                    ["params"] = 
                                                                    {
                                                                        ["value"] = 1,
                                                                        ["name"] = 3,
                                                                    }, -- end of ["params"]
                                                                }, -- end of ["action"]
                                                            }, -- end of ["params"]
                                                        }, -- end of [3]
                                                        [4] = 
                                                        {
                                                            ["enabled"] = true,
                                                            ["auto"] = true,
                                                            ["id"] = "WrappedAction",
                                                            ["number"] = 4,
                                                            ["params"] = 
                                                            {
                                                                ["action"] = 
                                                                {
                                                                    ["id"] = "Option",
                                                                    ["params"] = 
                                                                    {
                                                                        ["variantIndex"] = 2,
                                                                        ["name"] = 5,
                                                                        ["formationIndex"] = 2,
                                                                        ["value"] = 131074,
                                                                    }, -- end of ["params"]
                                                                }, -- end of ["action"]
                                                            }, -- end of ["params"]
                                                        }, -- end of [4]
                                                        [5] = 
                                                        {
                                                            ["enabled"] = true,
                                                            ["auto"] = true,
                                                            ["id"] = "WrappedAction",
                                                            ["number"] = 5,
                                                            ["params"] = 
                                                            {
                                                                ["action"] = 
                                                                {
                                                                    ["id"] = "Option",
                                                                    ["params"] = 
                                                                    {
                                                                        ["value"] = true,
                                                                        ["name"] = 15,
                                                                    }, -- end of ["params"]
                                                                }, -- end of ["action"]
                                                            }, -- end of ["params"]
                                                        }, -- end of [5]
                                                        [6] = 
                                                        {
                                                            ["enabled"] = true,
                                                            ["auto"] = true,
                                                            ["id"] = "WrappedAction",
                                                            ["number"] = 6,
                                                            ["params"] = 
                                                            {
                                                                ["action"] = 
                                                                {
                                                                    ["id"] = "Option",
                                                                    ["params"] = 
                                                                    {
                                                                        ["targetTypes"] = 
                                                                        {
                                                                        }, -- end of ["targetTypes"]
                                                                        ["name"] = 21,
                                                                        ["value"] = "none;",
                                                                        ["noTargetTypes"] = 
                                                                        {
                                                                            [1] = "Fighters",
                                                                            [2] = "Multirole fighters",
                                                                            [3] = "Bombers",
                                                                            [4] = "Helicopters",
                                                                            [5] = "Infantry",
                                                                            [6] = "Fortifications",
                                                                            [7] = "Tanks",
                                                                            [8] = "IFV",
                                                                            [9] = "APC",
                                                                            [10] = "Artillery",
                                                                            [11] = "Unarmed vehicles",
                                                                            [12] = "AAA",
                                                                            [13] = "SR SAM",
                                                                            [14] = "MR SAM",
                                                                            [15] = "LR SAM",
                                                                            [16] = "Aircraft Carriers",
                                                                            [17] = "Cruisers",
                                                                            [18] = "Destroyers",
                                                                            [19] = "Frigates",
                                                                            [20] = "Corvettes",
                                                                            [21] = "Light armed ships",
                                                                            [22] = "Unarmed ships",
                                                                            [23] = "Submarines",
                                                                            [24] = "Cruise missiles",
                                                                            [25] = "Antiship Missiles",
                                                                            [26] = "AA Missiles",
                                                                            [27] = "AG Missiles",
                                                                            [28] = "SA Missiles",
                                                                            [29] = "UAVs",
                                                                        }, -- end of ["noTargetTypes"]
                                                                    }, -- end of ["params"]
                                                                }, -- end of ["action"]
                                                            }, -- end of ["params"]
                                                        }, -- end of [6]
                                                        [7] = 
                                                        {
                                                            ["enabled"] = true,
                                                            ["auto"] = true,
                                                            ["id"] = "WrappedAction",
                                                            ["number"] = 7,
                                                            ["params"] = 
                                                            {
                                                                ["action"] = 
                                                                {
                                                                    ["id"] = "Option",
                                                                    ["params"] = 
                                                                    {
                                                                        ["value"] = true,
                                                                        ["name"] = 19,
                                                                    }, -- end of ["params"]
                                                                }, -- end of ["action"]
                                                            }, -- end of ["params"]
                                                        }, -- end of [7]
                                                    }, -- end of ["tasks"]
                                                }, -- end of ["params"]
                                            }, -- end of ["task"]
                                            ["type"] = "TakeOffGroundHot",
                                            ["ETA"] = 0,
                                            ["ETA_locked"] = true,
                                            ["y"] = 646476.28912154,
                                            ["x"] = -281516.98219419,
                                            ["formation_template"] = "",
                                            ["speed_locked"] = true,
                                        }, -- end of [1]
                                    }, -- end of ["points"]
                                }, -- end of ["route"]
                                ["groupId"] = 1,
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 2000,
                                        ["alt_type"] = "BARO",
                                        ["livery_id"] = "Algerian AF Desert KU-03",
                                        ["skill"] = "Client",
                                        ["speed"] = 180.55555555556,
                                        ["type"] = "Su-25T",
                                        ["unitId"] = 1,
                                        ["psi"] = -2.0005586058913,
                                        ["y"] = 646476.28912154,
                                        ["x"] = -281516.98219419,
                                        ["name"] = "Observer",
                                        ["payload"] = 
                                        {
                                            ["pylons"] = 
                                            {
                                            }, -- end of ["pylons"]
                                            ["fuel"] = "3790",
                                            ["flare"] = 128,
                                            ["chaff"] = 128,
                                            ["gun"] = 100,
                                        }, -- end of ["payload"]
                                        ["heading"] = 2.0005586058913,
                                        ["callsign"] = 
                                        {
                                            [1] = 1,
                                            [2] = 1,
                                            [3] = 1,
                                            ["name"] = "Enfield11",
                                        }, -- end of ["callsign"]
                                        ["onboard_num"] = "010",
                                    }, -- end of [1]
                                }, -- end of ["units"]
                                ["y"] = 646476.28912154,
                                ["x"] = -281516.98219419,
                                ["name"] = "Observer",
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["uncontrollable"] = false,
                                ["frequency"] = 124,
                            }, -- end of [1]
                        }, -- end of ["group"]
                    }, -- end of ["plane"]
                }, -- end of [1]
                [2] = 
                {
                    ["id"] = 0,
                    ["vehicle"] = 
                    {
                        ["group"] = 
                        {
                            [1] = 
                            {
                                ["visible"] = false,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["uncontrollable"] = false,
                                ["task"] = "Ground Nothing",
                                ["taskSelected"] = true,
                                ["route"] = 
                                {
                                    ["spans"] = 
                                    {
                                        [1] = 
                                        {
                                            [1] = 
                                            {
                                                ["y"] = 646322.21584594,
                                                ["x"] = -284786.65905339,
                                            }, -- end of [1]
                                            [2] = 
                                            {
                                                ["y"] = 646873.41630661,
                                                ["x"] = -284949.62339747,
                                            }, -- end of [2]
                                        }, -- end of [1]
                                        [2] = 
                                        {
                                            [1] = 
                                            {
                                                ["y"] = 646873.41745905,
                                                ["x"] = -284949.62373301,
                                            }, -- end of [1]
                                            [2] = 
                                            {
                                                ["y"] = 647135.50907952,
                                                ["x"] = -285027.11911783,
                                            }, -- end of [2]
                                        }, -- end of [2]
                                        [3] = 
                                        {
                                            [1] = 
                                            {
                                                ["y"] = 648363.8196817,
                                                ["x"] = -285381.2515561,
                                            }, -- end of [1]
                                            [2] = 
                                            {
                                                ["y"] = 648363.8196817,
                                                ["x"] = -285381.2515561,
                                            }, -- end of [2]
                                        }, -- end of [3]
                                    }, -- end of ["spans"]
                                    ["points"] = 
                                    {
                                        [1] = 
                                        {
                                            ["alt"] = 9,
                                            ["type"] = "Turning Point",
                                            ["ETA"] = 0,
                                            ["alt_type"] = "BARO",
                                            ["formation_template"] = "",
                                            ["y"] = 646341.76210614,
                                            ["x"] = -284791.07931429,
                                            ["ETA_locked"] = true,
                                            ["speed"] = 16.666666666667,
                                            ["action"] = "On Road",
                                            ["task"] = 
                                            {
                                                ["id"] = "ComboTask",
                                                ["params"] = 
                                                {
                                                    ["tasks"] = 
                                                    {
                                                    }, -- end of ["tasks"]
                                                }, -- end of ["params"]
                                            }, -- end of ["task"]
                                            ["speed_locked"] = true,
                                        }, -- end of [1]
                                        [2] = 
                                        {
                                            ["alt"] = 8,
                                            ["type"] = "Turning Point",
                                            ["ETA"] = 34.487179806774,
                                            ["alt_type"] = "BARO",
                                            ["formation_template"] = "",
                                            ["y"] = 646873.7958935,
                                            ["x"] = -284948.32414154,
                                            ["ETA_locked"] = false,
                                            ["speed"] = 16.666666666667,
                                            ["action"] = "On Road",
                                            ["task"] = 
                                            {
                                                ["id"] = "ComboTask",
                                                ["params"] = 
                                                {
                                                    ["tasks"] = 
                                                    {
                                                    }, -- end of ["tasks"]
                                                }, -- end of ["params"]
                                            }, -- end of ["task"]
                                            ["speed_locked"] = true,
                                        }, -- end of [2]
                                        [3] = 
                                        {
                                            ["alt"] = 8,
                                            ["type"] = "Turning Point",
                                            ["ETA"] = 50.885691564845,
                                            ["alt_type"] = "BARO",
                                            ["formation_template"] = "",
                                            ["y"] = 647135.92525548,
                                            ["x"] = -285025.84719074,
                                            ["ETA_locked"] = false,
                                            ["speed"] = 16.666666666667,
                                            ["action"] = "On Road",
                                            ["task"] = 
                                            {
                                                ["id"] = "ComboTask",
                                                ["params"] = 
                                                {
                                                    ["tasks"] = 
                                                    {
                                                    }, -- end of ["tasks"]
                                                }, -- end of ["params"]
                                            }, -- end of ["task"]
                                            ["speed_locked"] = true,
                                        }, -- end of [3]
                                    }, -- end of ["points"]
                                }, -- end of ["route"]
                                ["groupId"] = 2,
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["skill"] = "Average",
                                        ["coldAtStart"] = false,
                                        ["type"] = "T-90",
                                        ["unitId"] = 3,
                                        ["y"] = 646341.76210614,
                                        ["x"] = -284791.07931429,
                                        ["name"] = "CU1",
                                        ["heading"] = 1.8606092202755,
                                        ["playerCanDrive"] = true,
                                    }, -- end of [1]
                                    [2] = 
                                    {
                                        ["skill"] = "Average",
                                        ["coldAtStart"] = false,
                                        ["type"] = "T-90",
                                        ["unitId"] = 2,
                                        ["y"] = 646313.00202629,
                                        ["x"] = -284782.54407493,
                                        ["name"] = "CU2",
                                        ["heading"] = 1.8592907204715,
                                        ["playerCanDrive"] = true,
                                    }, -- end of [2]
                                }, -- end of ["units"]
                                ["y"] = 646341.76210614,
                                ["x"] = -284791.07931429,
                                ["name"] = "Conquering Units",
                                ["start_time"] = 0,
                            }, -- end of [1]
                        }, -- end of ["group"]
                    }, -- end of ["vehicle"]
                    ["name"] = "Russia",
                }, -- end of [2]
            }, -- end of ["country"]
        }, -- end of ["red"]
    }, -- end of ["coalition"]
    ["sortie"] = "DictKey_sortie_5",
    ["version"] = 22,
    ["trigrules"] = 
    {
        [1] = 
        {
            ["rules"] = 
            {
            }, -- end of ["rules"]
            ["comment"] = "Load DML",
            ["eventlist"] = "",
            ["predicate"] = "triggerStart",
            ["actions"] = 
            {
                [1] = 
                {
                    ["text"] = "dcsCommon = {}\
dcsCommon.version = \"2.8.7\"\
--[[-- VERSION HISTORY\
 2.2.6 - compassPositionOfARelativeToB\
       - clockPositionOfARelativeToB\
 2.2.7 - isTroopCarrier \
       - distFlat\
 2.2.8 - fixed event2text \
 2.2.9 - getUnitAGL\
       - getUnitAlt\
       - getUnitSpeed \
       - getUnitHeading\
       - getUnitHeadingDegrees\
       - mag\
       - clockPositionOfARelativeToB with own heading \
 2.3.0 - unitIsInfantry\
 2.3.1 - bool2YesNo\
       - bool2Text\
 2.3.2 - getGroupAvgSpeed\
       - getGroupMaxSpeed\
 2.3.3 - getSizeOfTable\
 2.3.4 - isSceneryObject\
         coalition2county\
 2.3.5 - smallRandom\
         pickRandom uses smallRandom\
         airfield handling, parking \
         flight waypoint handling\
         landing waypoint creation\
         take-off waypoint creation\
 2.3.6 - createOverheadAirdromeRoutPintData(aerodrome)\
 2.3.7 - coalition2county - warning when creating UN \
 2.3.8 - improved headingOfBInDegrees, new getClockDirection\
 2.3.9 - getClosingVelocity\
       - dot product \
       - magSquare\
       - vMag\
 2.4.0 - libCheck\
 2.4.1 - grid/square/rect formation \
       - arrangeGroupInNColumns formation \
       - 2Columns formation deep and wide formation\
 2.4.2 - getAirbasesInRangeOfPoint\
 2.4.3 - lerp \
 2.4.4 - getClosestAirbaseTo\
       - fixed bug in containsString when strings equal\
 2.4.5 - added cargo and mass options to createStaticObjectData\
 2.4.6 - fixed randompercent \
 2.4.7 - smokeColor2Num(smokeColor)\
 2.4.8 - linkStaticDataToUnit()\
 2.4.9 - trim functions \
       - createGroundUnitData uses trim function to remove leading/trailing blanks\
         so now we can use blanks after comma to separate types \
       - dcsCommon.trimArray(\
       - createStaticObjectData uses trim for type \
       - getEnemyCoalitionFor understands strings, still returns number\
       - coalition2county also understands 'red' and 'blue'\
 2.5.0 - \"Line\" formation with one unit places unit at center     \
 2.5.1 - vNorm(a)  \
 2.5.1 - added SA-18 Igla manpad to unitIsInfantry()\
 2.5.2 - added copyArray method\
       - corrected heading in createStaticObjectData\
 2.5.3 - corrected rotateGroupData bug for cz \
       - removed forced error in failed pickRandom\
 2.5.4 - rotateUnitData()\
       - randomBetween()\
 2.5.5 - stringStartsWithDigit()\
       - stringStartsWithLetter()\
       - stringIsPositiveNumber()\
 2.5.6 - corrected stringEndsWith() bug with str\
 2.5.7 - point2text(p) \
 2.5.8 - string2GroupCat()\
 2.5.9 - string2ObjectCat()\
 2.6.0 - unified uuid, removed uuIdent\
 2.6.1 - removed bug in rotateUnitData: cy --> cz param passing  \
 2.6.2 - new combineTables()\
 2.6.3 - new tacan2freq()\
 2.6.4 - new processHMS()\
 2.6.5 - new bearing2compass()\
       - new bearingdegrees2compass()\
       - new latLon2Text() - based on mist \
 2.6.6 - new nowString() \
       - new str2num()\
       - new stringRemainsStartingWith()\
       - new stripLF()\
       - new removeBlanks()\
 2.6.7 - new menu2text()\
 2.6.8 - new getMissionName()\
       - new flagArrayFromString()\
 2.6.9 - new getSceneryObjectsInZone()\
       - new getSceneryObjectInZoneByName()\
 2.7.0 - new synchGroupData()\
         clone, topClone and copyArray now all nil-trap \
 2.7.1 - new isPlayerUnit() -- moved from cfxPlayer\
         new getAllExistingPlayerUnitsRaw - from cfxPlayer\
         new typeIsInfantry()\
 2.7.2 - new rangeArrayFromString()\
         fixed leading blank bug in flagArrayFromString\
         new incFlag()\
         new decFlag()\
         nil trap in stringStartsWith()\
         new getClosestFreeSlotForCatInAirbaseTo()\
 2.7.3 - new string2Array()\
       - additional guard for isPlayerUnit\
 2.7.4 - new array2string()\
 2.7.5 - new bitAND32()\
       - new LSR()\
       - new num2bin()\
 2.7.6 - new getObjectsForCatAtPointWithRadius()\
 2.7.7 - clone() has new stripMeta option. pass true to remove all meta tables \
       - dumpVar2Str detects meta tables \
       - rotateGroupData kills unit's psi value if it existed since it messes with heading \
       - rotateGroupData - changes psi to -heading if it exists rather than nilling\
 2.7.8 - new getGeneralDirection()\
       - new getNauticalDirection()\
       - more robust guards for getUnitSpeed\
 2.7.9 - new bool2Num(theBool)\
       - new aspectByDirection()\
       - createGroundGroupWithUnits corrected spelling of minDist, crashed scattered formation\
       - randomPointInCircle fixed erroneous local for x, z \
       - \"scattered\" formation repaired\
 2.7.10- semaphore groundwork \
 2.8.0 - new collectMissionIDs at start-up  \
       - new getUnitNameByID\
       - new getGroupNameByID\
       - bool2YesNo alsco can return NIL\
       - new getUnitStartPosByID\
 2.8.1 - arrayContainsString: type checking for theArray and warning\
       - processStringWildcards()\
       - new wildArrayContainsString() \
       - fix for stringStartsWith oddity with aircraft types \
 2.8.2 - better fixes for string.find() in stringStartsWith and containsString\
       - dcsCommon.isTroopCarrier(theUnit, carriers) new carriers optional param\
       - better guards for getUnitAlt and getUnitAGL\
       - new newPointAtDegreesRange()\
       - new newPointAtAngleRange()\
       - new isTroopCarrierType()\
       - stringStartsWith now supports case insensitive match \
       - isTroopCarrier() supports 'any' and 'all'\
       - made getEnemyCoalitionFor() more resilient \
       - fix to smallRandom for negative numbers\
       - isTroopCarrierType uses wildArrayContainsString\
 2.8.3 - small optimizations in bearingFromAtoB()\
       - new whichSideOfMine()\
 2.8.4 - new rotatePointAroundOriginRad()\
       - new rotatePointAroundPointDeg()\
       - new rotatePointAroundPointRad()\
       - getClosestAirbaseTo() now supports passing list of air bases\
 2.8.5 - better guard in getGroupUnit()\
 2.8.6 - phonetic helpers \
         new spellString()\
 2.8.7 - new flareColor2Num()\
       - new flareColor2Text()\
       - new iteratePlayers()\
 \
--]]--\
\
    -- dcsCommon is a library of common lua functions \
    -- for easy access and simple mission programming\
    -- (c) 2021 - 2023 by Chritian Franz and cf/x AG\
\
    dcsCommon.verbose = false -- set to true to see debug messages. Lots of them\
    dcsCommon.uuidStr = \"uuid-\"\
    dcsCommon.simpleUUID = 76543 -- a number to start. as good as any\
    \
    -- globals\
    dcsCommon.cbID = 0 -- callback id for simple callback scheduling\
    dcsCommon.troopCarriers = {\"Mi-8MT\", \"UH-1H\", \"Mi-24P\"} -- Ka-50, Apache and Gazelle can't carry troops\
    dcsCommon.coalitionSides = {0, 1, 2}\
    \
    -- lookup tables\
    dcsCommon.groupID2Name = {}\
    dcsCommon.unitID2Name = {}\
    dcsCommon.unitID2X = {}\
    dcsCommon.unitID2Y = {}\
\
    -- verify that a module is loaded. obviously not required\
    -- for dcsCommon, but all higher-order modules\
    function dcsCommon.libCheck(testingFor, requiredLibs)\
        local canRun = true \
        for idx, libName in pairs(requiredLibs) do \
            if not _G[libName] then \
                trigger.action.outText(\"*** \" .. testingFor .. \" requires \" .. libName, 30)\
                canRun = false \
            end\
        end\
        return canRun\
    end\
\
    -- read all groups and units from miz and build a reference table\
    function dcsCommon.collectMissionIDs()\
    -- create cross reference tables to be able to get a group or\
    -- unit's name by ID\
        for coa_name_miz, coa_data in pairs(env.mission.coalition) do -- iterate all coalitions\
            local coa_name = coa_name_miz\
            if string.lower(coa_name_miz) == 'neutrals' then -- remove 's' at neutralS\
                coa_name = 'neutral'\
            end\
            -- directly convert coalition into number for easier access later\
            local coaNum = 0\
            if coa_name == \"red\" then coaNum = 1 end \
            if coa_name == \"blue\" then coaNum = 2 end \
            \
            if type(coa_data) == 'table' then -- coalition = {bullseye, nav_points, name, county}, \
                                              -- with county being an array \
                if coa_data.country then -- make sure there a country table for this coalition\
                    for cntry_id, cntry_data in pairs(coa_data.country) do -- iterate all countries for this \
                        -- per country = {id, name, vehicle, helicopter, plane, ship, static}\
                        local countryName = string.lower(cntry_data.name)\
                        local countryID = cntry_data.id \
                        if type(cntry_data) == 'table' then    -- filter strings .id and .name \
                            for obj_type_name, obj_type_data in pairs(cntry_data) do\
                                -- only look at helos, ships, planes and vehicles\
                                if obj_type_name == \"helicopter\" or \
                                   obj_type_name == \"ship\" or \
                                   obj_type_name == \"plane\" or \
                                   obj_type_name == \"vehicle\" or \
                                   obj_type_name == \"static\" -- what about \"cargo\"?\
                                then -- (so it's not id or name)\
                                    local category = obj_type_name\
                                    if ((type(obj_type_data) == 'table') and obj_type_data.group and (type(obj_type_data.group) == 'table') and (#obj_type_data.group > 0)) then    --there's at least one group!\
                                        for group_num, group_data in pairs(obj_type_data.group) do\
                                            \
                                            local aName = group_data.name \
                                            local aID = group_data.groupId\
                                            -- store this reference \
                                            dcsCommon.groupID2Name[aID] = aName \
                                            \
                                            -- now iterate all units in this group \
                                            -- for player into \
                                            for unit_num, unit_data in pairs(group_data.units) do\
                                                if unit_data.name and unit_data.unitId then \
                                                    -- store this reference \
                                                    dcsCommon.unitID2Name[unit_data.unitId] = unit_data.name\
                                                    dcsCommon.unitID2X[unit_data.unitId] = unit_data.x\
                                                    dcsCommon.unitID2Y[unit_data.unitId] = unit_data.y\
                                                end\
                                            end -- for all units\
                                        end -- for all groups \
                                    end --if has category data \
                                end --if plane, helo etc... category\
                            end --for all objects in country \
                        end --if has country data \
                    end --for all countries in coalition\
                end --if coalition has country table \
            end -- if there is coalition data  \
        end --for all coalitions in mission \
    end\
\
    function dcsCommon.getUnitNameByID(theID)\
        -- accessor function for later expansion\
        return dcsCommon.unitID2Name[theID]\
    end\
    \
    function dcsCommon.getGroupNameByID(theID)\
        -- accessor function for later expansion \
        return dcsCommon.groupID2Name[theID]\
    end\
\
    function dcsCommon.getUnitStartPosByID(theID)\
        local x = dcsCommon.unitID2X[theID]\
        local y = dcsCommon.unitID2Y[theID]\
        return x, y\
    end\
    \
    -- returns only positive values, lo must be >0 and <= hi \
    function dcsCommon.randomBetween(loBound, hiBound)\
        if not loBound then loBound = 1 end \
        if not hiBound then hiBound = 1 end \
        if loBound == hiBound then return loBound end \
\
        local delayMin = loBound\
        local delayMax = hiBound \
        local delay = delayMax \
    \
        if delayMin ~= delayMax then \
            -- pick random in range , say 3-7 --> 5 s!\
            local delayDiff = (delayMax - delayMin) + 1 -- 7-3 + 1\
            delay = dcsCommon.smallRandom(delayDiff) - 1 --> 0-4\
            delay = delay + delayMin \
            if delay > delayMax then delay = delayMax end \
            if delay < 1 then delay = 1 end \
        \
            if dcsCommon.verbose then \
                trigger.action.outText(\"+++dcsC: delay range \" .. delayMin .. \"-\" .. delayMax .. \": selected \" .. delay, 30)\
            end\
        end\
        \
        return delay\
    end\
    \
\
    -- taken inspiration from mist, as dcs lua has issues with\
    -- random numbers smaller than 50. Given a range of x numbers 1..x, it is \
    -- repeated a number of times until it fills an array of at least \
    -- 50 items (usually some more), and only then one itemis picked from \
    -- that array with a random number that is from a greater range (0..50+)\
    function dcsCommon.smallRandom(theNum) -- adapted from mist, only support ints\
        theNum = math.floor(theNum)\
        if theNum >= 50 then return math.random(theNum) end\
        if theNum < 1 then\
            trigger.action.outText(\"smallRandom: invoke with argument < 1 (\" .. theNum .. \"), using 1\", 30)\
            theNum = 1 \
        end \
        -- for small randoms (<50) \
        local lowNum, highNum\
        highNum = theNum\
        lowNum = 1\
        local total = 1\
        if math.abs(highNum - lowNum + 1) < 50 then -- if total values is less than 50\
            total = math.modf(50/math.abs(highNum - lowNum + 1)) -- number of times to repeat whole range to get above 50. e.g. 11 would be 5 times 1 .. 11, giving us 55 items total \
        end\
        local choices = {}\
        for i = 1, total do -- iterate required number of times\
            for x = lowNum, highNum do -- iterate between the range\
                choices[#choices +1] = x -- add each entry to a table\
            end\
        end\
        local rtnVal; -- = math.random(#choices) -- will now do a math.random of at least 50 choices\
        for i = 1, 15 do\
            rtnVal = math.random(#choices) -- iterate 15 times for randomization\
        end\
        return choices[rtnVal] -- return indexed\
    end\
    \
\
    function dcsCommon.getSizeOfTable(theTable)\
        local count = 0\
        for _ in pairs(theTable) do count = count + 1 end\
        return count\
    end\
\
    function dcsCommon.findAndRemoveFromTable(theTable, theElement) -- assumes array \
        if not theElement then return false end \
        if not theTable then return false end \
        for i=1, #theTable do \
            if theTable[i] == theElement then \
                -- this element found. remove from table \
                table.remove(theTable, i)\
                return true \
            end\
        end\
    end\
\
    function dcsCommon.pickRandom(theTable)\
        if not theTable then \
            trigger.action.outText(\"*** warning: nil table in pick random\", 30)\
        end\
        \
        if #theTable < 1 then \
            trigger.action.outText(\"*** warning: zero choice in pick random\", 30)\
            --local k = i.ll \
            return nil\
        end\
        if #theTable == 1 then return theTable[1] end\
        r = dcsCommon.smallRandom(#theTable) --r = math.random(#theTable)\
        return theTable[r]\
    end\
\
    -- enumerateTable - make an array out of a table for indexed access\
    function dcsCommon.enumerateTable(theTable)\
        if not theTable then theTable = {} end\
        local array = {}\
        for key, value in pairs(theTable) do \
            table.insert(array, value)\
        end\
        return array\
    end\
\
    -- combine table. creates new \
    function dcsCommon.combineTables(inOne, inTwo)\
        local outTable = {}\
        for idx, element in pairs(inOne) do \
            table.insert(outTable, element)\
        end\
        for idx, element in pairs(inTwo) do \
            table.insert(outTable, element)\
        end\
        return outTable\
    end\
-- \
-- A I R F I E L D S  A N D  F A R P S  \
--\
\
    -- airfield management \
    function dcsCommon.getAirbaseCat(aBase)\
        if not aBase then return nil end \
        \
        local airDesc = aBase:getDesc()\
        if not airDesc then return nil end \
        \
        local airCat = airDesc.category\
        return airCat \
    end\
\
    -- get free parking slot. optional parkingType can be used to \
    -- filter for a scpecific type, e.g. 104 = open field\
    function dcsCommon.getFirstFreeParkingSlot(aerodrome, parkingType) \
        if not aerodrome then return nil end \
        local freeSlots = aerodrome:getParking(true)\
        \
        for idx, theSlot in pairs(freeSlots) do \
            if not parkingType then \
                -- simply return the first we come across\
                return theSlot\
            end        \
            \
            if theSlot.Term_Type == parkingType then \
                return theSlot \
            end\
        end\
        \
        return nil \
    end\
\
    -- getAirbasesInRangeOfPoint: get airbases that are in range of point \
    function dcsCommon.getAirbasesInRangeOfPoint(center, range, filterCat, filterCoalition)\
        if not center then return {} end \
        if not range then range = 500 end -- 500m default \
        local basesInRange = {}\
        \
        local allAB = dcsCommon.getAirbasesWhoseNameContains(\"*\", filterCat, filterCoalition)\
        for idx, aBase in pairs(allAB) do             \
            local delta = dcsCommon.dist(center, aBase:getPoint())\
            if delta <= range then \
                table.insert(basesInRange, aBase)\
            end\
        end\
        return basesInRange\
    end\
\
    -- getAirbasesInRangeOfAirbase returns all airbases that \
    -- are in range of the given airbase \
    function dcsCommon.getAirbasesInRangeOfAirbase(airbase, includeCenter, range, filterCat, filterCoalition)\
        if not airbase then return {} end\
        if not range then range = 150000 end \
        local center = airbase:getPoint() \
        local centerName = airbase:getName() \
        \
        local ABinRange = {}\
        local allAB = dcsCommon.getAirbasesWhoseNameContains(\"*\", filterCat, filterCoalition)\
        \
        for idx, aBase in pairs(allAB) do \
            if aBase:getName() ~= centerName then \
                local delta = dcsCommon.dist(center, aBase:getPoint())\
                if delta <= range then \
                    table.insert(ABinRange, aBase)\
                end\
            end        \
        end\
        \
        if includeCenter then \
            table.insert(ABinRange, airbase)\
        end\
        \
        return ABinRange\
    end\
\
    function dcsCommon.getAirbasesInRangeOfAirbaseList(theCenterList, includeList, range, filterCat, filterCoalition)\
        local collectorDict = {}\
        for idx, aCenter in pairs(theCenterList) do \
            -- get all surrounding airbases. returns list of airfields \
            local surroundingAB = dcsCommon.getAirbasesInRangeOfAirbase(airbase, includeList, range, filterCat, filterCoalition)\
            \
            for idx2, theAirField in pairs (surroundingAB) do \
                collectorDict[airField] = theAirField \
            end\
        end\
        \
        -- make result an array\
        local theABList = dcsCommon.enumerateTable(collectorDict)\
        return theABList\
    end\
\
    -- getAirbasesWhoseNameContains - get all airbases containing \
    -- a name. filterCat is optional and can be aerodrome (0), farp (1), ship (2)\
    -- filterCoalition is optional and can be 0 (neutral), 1 (red), 2 (blue) \
    -- if no name given or aName = \"*\", then all bases are returned prior to filtering \
    function dcsCommon.getAirbasesWhoseNameContains(aName, filterCat, filterCoalition)\
        --trigger.action.outText(\"getAB(name): enter with \" .. aName, 30)\
        if not aName then aName = \"*\" end \
        local allYourBase = world.getAirbases() -- get em all \
        local areBelongToUs = {}\
        -- now iterate all bases\
        for idx, aBase in pairs(allYourBase) do\
            local airBaseName = aBase:getName() -- get display name\
            if aName == \"*\" or dcsCommon.containsString(airBaseName, aName) then \
                -- containsString is case insesitive unless told otherwise\
                --if aName ~= \"*\" then \
                --    trigger.action.outText(\"getAB(name): matched \" .. airBaseName, 30)\
                --end \
                local doAdd = true \
                if filterCat then \
                    -- make sure the airbase is of that category \
                    local airCat = dcsCommon.getAirbaseCat(aBase)\
                    doAdd = doAdd and airCat == filterCat \
                end\
                \
                if filterCoalition then \
                    doAdd = doAdd and filterCoalition == aBase:getCoalition()\
                end\
                \
                if doAdd then \
                    -- all good, add to table\
                    table.insert(areBelongToUs, aBase)\
                end            \
            end\
        end\
        return areBelongToUs\
    end\
\
    function dcsCommon.getFirstAirbaseWhoseNameContains(aName, filterCat, filterCoalition)\
        local allBases = dcsCommon.getAirbasesWhoseNameContains(aName, filterCat, filterCoalition)\
        for idx, aBase in pairs (allBases) do \
            -- simply return first \
            return aBase\
        end\
        return nil \
    end    \
\
    function dcsCommon.getClosestAirbaseTo(thePoint, filterCat, filterCoalition, allYourBase)\
        local delta = math.huge\
        if not allYourBase then \
            allYourBase = dcsCommon.getAirbasesWhoseNameContains(\"*\", filterCat, filterCoalition) -- get em all and filter\
        end \
        \
        local closestBase = nil \
        for idx, aBase in pairs(allYourBase) do\
            -- iterate them all \
            local abPoint = aBase:getPoint()\
            newDelta = dcsCommon.dist(thePoint, {x=abPoint.x, y = 0, z=abPoint.z})\
            if newDelta < delta then \
                delta = newDelta\
                closestBase = aBase\
            end\
        end\
        return closestBase, delta \
    end\
\
    function dcsCommon.getClosestFreeSlotForCatInAirbaseTo(cat, x, y, theAirbase, ignore)\
        if not theAirbase then return nil end \
        if not ignore then ignore = {} end \
        if not cat then return nil end \
        if (not cat == \"helicopter\") and (not cat == \"plane\") then \
            trigger.action.outText(\"+++common-getslotforcat: wrong cat <\" .. cat .. \">\", 30)\
            return nil \
        end\
        local allFree = theAirbase:getParking(true) --  only free slots\
        local filterFreeByType = {}\
        for idx, aSlot in pairs(allFree) do \
            local termT = aSlot.Term_Type\
            if termT == 104 or \
            (termT == 72 and cat == \"plane\") or \
            (termT == 68 and cat == \"plane\") or \
            (termT == 40 and cat == \"helicopter\") then \
                table.insert(filterFreeByType, aSlot)\
            else \
                -- we skip this slot, not good for type \
            end\
        end\
        \
        if #filterFreeByType == 0 then \
            return nil\
        end \
        \
        local reallyFree = {}\
        for idx, aSlot in pairs(filterFreeByType) do \
            local slotNum = aSlot.Term_Index\
            isTaken = false \
            for idy, taken in pairs(ignore) do \
                if taken == slotNum then isTaken = true end \
            end\
            if not isTaken then \
                table.insert(reallyFree, aSlot)\
            end\
        end\
        \
        if #reallyFree < 1 then \
            reallyFree = filterFreeByType\
        end\
        \
        local closestDist = math.huge \
        local closestSlot = nil \
        local p = {x = x, y = 0, z = y} -- !!\
        for idx, aSlot in pairs(reallyFree) do \
            local sp = {x = aSlot.vTerminalPos.x, y = 0, z = aSlot.vTerminalPos.z}\
            local currDist = dcsCommon.distFlat(p, sp)\
            --trigger.action.outText(\"slot <\" .. aSlot.Term_Index .. \"> has dist \" .. math.floor(currDist) .. \" and _0 of <\" .. aSlot.Term_Index_0 .. \">\", 30)\
            if currDist < closestDist then \
                closestSlot = aSlot \
                closestDist = currDist \
            end\
        end\
        --trigger.action.outText(\"slot <\" .. closestSlot.Term_Index .. \"> has closest dist <\" .. math.floor(closestDist) .. \">\", 30)\
        return closestSlot\
    end\
\
-- \
-- U N I T S   M A N A G E M E N T \
--\
\
    -- number of living units in group\
    function dcsCommon.livingUnitsInGroup(group)\
        local living = 0\
        local allUnits = group:getUnits()\
        for key, aUnit in pairs(allUnits) do \
            if aUnit:isExist() and aUnit:getLife() >= 1 then \
                living = living + 1\
            end\
        end\
        return living\
    end\
\
    -- closest living unit in group to a point\
    function dcsCommon.getClosestLivingUnitToPoint(group, p)\
        if not p then return nil end\
        if not group then return nil end\
        local closestUnit = nil\
        local closestDist = math.huge\
        local allUnits = group:getUnits()\
        for key, aUnit in pairs(allUnits) do \
            if aUnit:isExist() and aUnit:getLife() >= 1 then \
                local thisDist = dcsCommon.dist(p, aUnit:getPoint())\
                if thisDist < closestDist then \
                    closestDist = thisDist\
                    closestUnit = aUnit \
                end\
            end\
        end\
        return closestUnit, closestDist\
    end\
    \
    -- closest living group to a point - cat can be nil or one of Group.Category = { AIRPLANE = 0, HELICOPTER = 1, GROUND = 2, SHIP = 3, TRAIN = 4}\
    function dcsCommon.getClosestLivingGroupToPoint(p, coal, cat) \
        if not cat then cat = 2 end -- ground is default \
        local closestGroup = nil;\
        local closestGroupDist = math.huge\
        local allGroups =  coalition.getGroups(coal, cat) -- get all groups from this coalition, perhaps filtered by cat \
        for key, grp in pairs(allGroups) do\
            local closestUnit, dist = dcsCommon.getClosestLivingUnitToPoint(grp, p)\
            if closestUnit then \
                if dist < closestGroupDist then \
                    closestGroup = grp\
                    closestGroupDist = dist\
                end\
            end            \
        end\
        return closestGroup, closestGroupDist\
    end\
\
    function dcsCommon.getLivingGroupsAndDistInRangeToPoint(p, range, coal, cat) \
        if not cat then cat = 2 end -- ground is default \
        local groupsInRange = {};\
        local allGroups = coalition.getGroups(coal, cat) -- get all groups from this coalition, perhaps filtered by cat \
        for key, grp in pairs(allGroups) do\
            local closestUnit, dist = dcsCommon.getClosestLivingUnitToPoint(grp, p)\
            if closestUnit then \
                if dist < range then \
                    table.insert(groupsInRange, {group = grp, dist = dist}) -- array\
                end\
            end            \
        end\
        -- sort the groups by distance\
        table.sort(groupsInRange, function (left, right) return left.dist < right.dist end )\
        return groupsInRange\
    end\
\
    -- distFlat ignores y, input must be xyz points, NOT xy points  \
    function dcsCommon.distFlat(p1, p2) \
        local point1 = {x = p1.x, y = 0, z=p1.z}\
        local point2 = {x = p2.x, y = 0, z=p2.z}\
        return dcsCommon.dist(point1, point2)\
    end\
    \
    \
    -- distance between points\
    function dcsCommon.dist(point1, point2)     -- returns distance between two points\
      -- supports xyz and xy notations\
      if not point1 then \
        trigger.action.outText(\"+++ warning: nil point1 in common:dist\", 30)\
        point1 = {x=0, y=0, z=0}\
      end\
\
      if not point2 then \
        trigger.action.outText(\"+++ warning: nil point2 in common:dist\", 30)\
        point2 = {x=0, y=0, z=0}\
        stop.here.now = 1\
      end\
      \
      local p1 = {x = point1.x, y = point1.y}\
      if not point1.z then \
        p1.z = p1.y\
        p1.y = 0\
      else \
        p1.z = point1.z\
      end\
      \
      local p2 = {x = point2.x, y = point2.y}\
      if not point2.z then \
        p2.z = p2.y\
        p2.y = 0\
      else \
        p2.z = point2.z\
      end\
      \
      local x = p1.x - p2.x\
      local y = p1.y - p2.y \
      local z = p1.z - p2.z\
      \
      return (x*x + y*y + z*z)^0.5\
    end\
\
    function dcsCommon.delta(name1, name2) -- returns distance (in meters) of two named objects\
      local n1Pos = Unit.getByName(name1):getPosition().p\
      local n2Pos = Unit.getByName(name2):getPosition().p\
      return dcsCommon.dist(n1Pos, n2Pos)\
    end\
\
    -- lerp between a and b, x being 0..1 (percentage), clipped to [0..1]\
    function dcsCommon.lerp(a, b, x) \
        if not a then return 0 end\
        if not b then return 0 end\
        if not x then return a end\
        if x < 0 then x = 0 end \
        if x > 1 then x = 1 end \
        return a + (b - a ) * x\
    end\
\
    function dcsCommon.bearingFromAtoB(A, B) -- coords in x, z \
        if not A then \
            trigger.action.outText(\"WARNING: no 'A' in bearingFromAtoB\", 30)\
            return 0\
        end\
        if not B then\
            trigger.action.outText(\"WARNING: no 'A' in bearingFromAtoB\", 30)\
            return 0\
        end\
        if not A.x then \
            trigger.action.outText(\"WARNING: no 'A.x' (type A =<\" .. type(A) .. \">)in bearingFromAtoB\", 30)\
            return 0\
        end\
        if not A.y then \
            trigger.action.outText(\"WARNING: no 'A.x' (type A =<\" .. type(A) .. \">)in bearingFromAtoB\", 30)\
            return 0\
        end\
        if not B.x then \
            trigger.action.outText(\"WARNING: no 'B.x' (type B =<\" .. type(B) .. \">)in bearingFromAtoB\", 30)\
            return 0\
        end\
        if not B.y then \
            trigger.action.outText(\"WARNING: no 'B.y' (type B =<\" .. type(B) .. \">)in bearingFromAtoB\", 30)\
            return 0\
        end\
        \
        local dx = B.x - A.x\
        local dz = B.z - A.z\
        local bearing = math.atan2(dz, dx) -- in radiants\
        return bearing\
    end\
\
    function dcsCommon.bearingInDegreesFromAtoB(A, B)\
        local bearing = dcsCommon.bearingFromAtoB(A, B) -- in rads \
        bearing = math.floor(bearing / math.pi * 180)\
        if bearing < 0 then bearing = bearing + 360 end\
        if bearing > 360 then bearing = bearing - 360 end\
        return bearing\
    end\
    \
    function dcsCommon.compassPositionOfARelativeToB(A, B)\
        -- warning: is REVERSE in order for bearing, returns a string like 'Sorth', 'Southwest'\
        if not A then return \"***error:A***\" end\
        if not B then return \"***error:B***\" end\
        local bearing = dcsCommon.bearingInDegreesFromAtoB(B, A) -- returns 0..360\
        if bearing < 23 then return \"North\" end \
        if bearing < 68 then return \"NE\" end\
        if bearing < 112 then return \"East\" end \
        if bearing < 158 then return \"SE\" end \
        if bearing < 202 then return \"South\" end \
        if bearing < 248 then return \"SW\" end \
        if bearing < 292 then return \"West\" end\
        if bearing < 338 then return \"NW\" end \
        return \"North\"\
    end\
    \
    function dcsCommon.bearing2compass(inrad)\
        local bearing = math.floor(inrad / math.pi * 180)\
        if bearing < 0 then bearing = bearing + 360 end\
        if bearing > 360 then bearing = bearing - 360 end\
        return dcsCommon.bearingdegrees2compass(bearing)\
    end\
    \
    function dcsCommon.bearingdegrees2compass(bearing)\
        if bearing < 23 then return \"North\" end \
        if bearing < 68 then return \"NE\" end\
        if bearing < 112 then return \"East\" end \
        if bearing < 158 then return \"SE\" end \
        if bearing < 202 then return \"South\" end \
        if bearing < 248 then return \"SW\" end \
        if bearing < 292 then return \"West\" end\
        if bearing < 338 then return \"NW\" end \
        return \"North\"\
    end\
    \
    function dcsCommon.clockPositionOfARelativeToB(A, B, headingOfBInDegrees)\
        -- o'clock notation \
        if not A then return \"***error:A***\" end\
        if not B then return \"***error:B***\" end\
        if not headingOfBInDegrees then headingOfBInDegrees = 0 end \
        \
        local bearing = dcsCommon.bearingInDegreesFromAtoB(B, A) -- returns 0..360\
--        trigger.action.outText(\"+++comm: oclock - bearing = \" .. bearing .. \" and inHeading = \" .. headingOfBInDegrees, 30) \
        bearing = bearing - headingOfBInDegrees\
        return dcsCommon.getClockDirection(bearing)\
        \
    end \
    \
    -- given a heading, return clock with 0 being 12, 180 being 6 etc.\
    function dcsCommon.getClockDirection(direction) -- inspired by cws, improvements my own\
        if not direction then return 0 end\
        direction = math.fmod (direction, 360)\
        while direction < 0 do \
            direction = direction + 360\
        end\
        while direction >= 360 do \
            direction = direction - 360\
        end\
        if direction < 15 then -- special case 12 o'clock past 12 o'clock\
            return 12\
        end\
    \
        direction = direction + 15 -- add offset so we get all other times correct\
        return math.floor(direction/30)\
    \
    end\
\
    function dcsCommon.getGeneralDirection(direction) -- inspired by cws, improvements my own\
        if not direction then return \"unkown\" end\
        direction = math.fmod (direction, 360)\
        while direction < 0 do \
            direction = direction + 360\
        end\
        while direction >= 360 do \
            direction = direction - 360\
        end\
        if direction < 45 then return \"ahead\" end    \
        if direction < 135 then return \"right\" end\
        if direction < 225 then return \"behind\" end\
        if direction < 315 then return \"left\" end \
        return \"ahead\"\
    end\
    \
    function dcsCommon.getNauticalDirection(direction) -- inspired by cws, improvements my own\
        if not direction then return \"unkown\" end\
        direction = math.fmod (direction, 360)\
        while direction < 0 do \
            direction = direction + 360\
        end\
        while direction >= 360 do \
            direction = direction - 360\
        end\
        if direction < 45 then return \"ahead\" end    \
        if direction < 135 then return \"starboard\" end\
        if direction < 225 then return \"aft\" end\
        if direction < 315 then return \"port\" end \
        return \"ahead\"\
    end\
\
    function dcsCommon.aspectByDirection(direction) -- inspired by cws, improvements my own\
        if not direction then return \"unkown\" end\
        direction = math.fmod (direction, 360)\
        while direction < 0 do \
            direction = direction + 360\
        end\
        while direction >= 360 do \
            direction = direction - 360\
        end\
        \
        if direction < 45 then return \"hot\" end    \
        if direction < 135 then return \"beam\" end\
        if direction < 225 then return \"drag\" end\
        if direction < 315 then return \"beam\" end \
        return \"hot\"\
    end\
    \
    function dcsCommon.whichSideOfMine(theUnit, target) -- returs two values: -1/1 = left/right and \"left\"/\"right\" \
        if not theUnit then return nil end \
        if not target then return nil end \
        local uDOF = theUnit:getPosition() -- returns p, x, y, z Vec3\
        -- with x, y, z being the normalised vectors for right, up, forward \
        local heading = math.atan2(uDOF.x.z, uDOF.x.x) -- returns rads\
        if heading < 0 then\
            heading = heading + 2 * math.pi    -- put heading in range of 0 to 2*pi\
        end\
        -- heading now runs from 0 through 2Pi\
        local A = uDOF.p\
        local B = target:getPoint() \
         \
        -- now get bearing from theUnit to target  \
        local dx = B.x - A.x\
        local dz = B.z - A.z\
        local bearing = math.atan2(dz, dx) -- in rads\
        if bearing < 0 then\
            bearing = bearing + 2 * math.pi    -- make bearing 0 to 2*pi\
        end\
\
        -- we now have bearing to B, and own heading. \
        -- subtract own heading from bearing to see at what \
        -- bearing target would be if we 'turned the world' so\
        -- that theUnit is heading 0\
        local dBearing = bearing - heading\
        -- if result < 0 or > Pi (=180°), target is left from us\
        if dBearing < 0 or dBearing > math.pi then return -1, \"left\" end\
        return 1, \"right\"\
        -- note: no separate case for straight in front or behind\
    end\
    \
    function dcsCommon.randomDegrees()\
        local degrees = math.random(360) * 3.14152 / 180\
        return degrees\
    end\
\
    function dcsCommon.randomPercent()\
        local percent = math.random(100)/100\
        return percent\
    end\
\
    function dcsCommon.randomPointOnPerimeter(sourceRadius, x, z) \
        return dcsCommon.randomPointInCircle(sourceRadius, sourceRadius-1, x, z)\
    end\
\
    function dcsCommon.randomPointInCircle(sourceRadius, innerRadius, x, z)\
        if not x then x = 0 end\
        if not z then z = 0 end \
        \
        --local y = 0\
        if not innerRadius then innerRadius = 0 end        \
        if innerRadius < 0 then innerRadius = 0 end\
        \
        local percent = dcsCommon.randomPercent() -- 1 / math.random(100)\
        -- now lets get a random degree\
        local degrees = dcsCommon.randomDegrees() -- math.random(360) * 3.14152 / 180 -- ok, it's actually radiants. \
        local r = (sourceRadius-innerRadius) * percent \
        x = x + (innerRadius + r) * math.cos(degrees)\
        z = z + (innerRadius + r) * math.sin(degrees)\
    \
        local thePoint = {}\
        thePoint.x = x\
        thePoint.y = 0\
        thePoint.z = z \
        \
        return thePoint, degrees\
    end\
\
    function dcsCommon.newPointAtDegreesRange(p1, degrees, radius)\
        local rads = degrees * 3.14152 / 180\
        local p2 = dcsCommon.newPointAtAngleRange(p1, rads, radius)\
        return p2 \
    end\
    \
    function dcsCommon.newPointAtAngleRange(p1, angle, radius)\
        local p2 = {}\
        p2.x = p1.x + radius * math.cos(angle)\
        p2.y = p1.y \
        p2.z = p1.z + radius * math.sin(angle)\
        return p2 \
    end\
\
    -- get group location: get the group's location by \
    -- accessing the fist existing, alive member of the group that it finds\
    function dcsCommon.getGroupLocation(group)\
        -- nifty trick from mist: make this work with group and group name\
        if type(group) == 'string' then -- group name\
            group = Group.getByName(group)\
        end\
        \
        -- get all units\
        local allUnits = group:getUnits()\
\
        -- iterate through all members of group until one is alive and exists\
        for index, theUnit in pairs(allUnits) do \
            if (theUnit:isExist() and theUnit:getLife() > 0) then \
                return theUnit:getPosition().p \
            end;\
        end\
\
        -- if we get here, there was no live unit \
        --trigger.action.outText(\"+++cmn: A group has no live units. returning nil\", 10)\
        return nil \
        \
    end\
\
    -- get the group's first Unit that exists and is \
    -- alive \
    function dcsCommon.getGroupUnit(group)\
        if not group then return nil  end\
        \
        -- nifty trick from mist: make this work with group and group name\
        if type(group) == 'string' then -- group name\
            group = Group.getByName(group)\
        end\
        \
        if not group:isExist() then return nil end \
        \
        -- get all units\
        local allUnits = group:getUnits()\
\
        -- iterate through all members of group until one is alive and exists\
        for index, theUnit in pairs(allUnits) do \
            if Unit.isExist(theUnit) and theUnit:getLife() > 0 then \
                return theUnit\
            end;\
        end\
\
        -- if we get here, there was no live unit \
        --trigger.action.outText(\"+++cmn A group has no live units. returning nil\", 10)\
        return nil \
        \
    end\
\
    -- and here the alias\
    function dcsCommon.getFirstLivingUnit(group)\
        return dcsCommon.getGroupUnit(group)\
    end\
    \
    -- isGroupAlive returns true if there is at least one unit in the group that isn't dead\
    function dcsCommon.isGroupAlive(group)\
        return (dcsCommon.getGroupUnit(group) ~= nil) \
    end\
\
    function dcsCommon.getLiveGroupUnits(group)\
        -- nifty trick from mist: make this work with group and group name\
        if type(group) == 'string' then -- group name\
            group = Group.getByName(group)\
        end\
        \
        local liveUnits = {}\
        -- get all units\
        local allUnits = group:getUnits()\
\
        -- iterate through all members of group until one is alive and exists\
        for index, theUnit in pairs(allUnits) do \
            if (theUnit:isExist() and theUnit:getLife() > 0) then \
                table.insert(liveUnits, theUnit) \
            end;\
        end\
\
        -- if we get here, there was no live unit \
        return liveUnits\
    end\
\
    function dcsCommon.getGroupTypeString(group) -- convert into comma separated types \
        if not group then \
            trigger.action.outText(\"+++cmn getGroupTypeString: nil group\", 30)\
            return \"\" \
        end\
        if not dcsCommon.isGroupAlive(group) then \
            trigger.action.outText(\"+++cmn getGroupTypeString: dead group\", 30)\
            return \"\" \
        end \
        local theTypes = \"\"\
        local liveUnits = dcsCommon.getLiveGroupUnits(group)\
        for i=1, #liveUnits do \
            if i > 1 then theTypes = theTypes .. \",\" end\
            theTypes = theTypes .. liveUnits[i]:getTypeName()\
        end\
        return theTypes\
    end\
\
    function dcsCommon.getGroupTypes(group) \
        if not group then \
            trigger.action.outText(\"+++cmn getGroupTypes: nil group\", 30)\
            return {}\
        end\
        if not dcsCommon.isGroupAlive(group) then \
            trigger.action.outText(\"+++cmn getGroupTypes: dead group\", 30)\
            return {}\
        end \
        local liveUnits = dcsCommon.getLiveGroupUnits(group)\
        local unitTypes = {}\
        for i=1, #liveUnits do \
            table.insert(unitTypes, liveUnits[i]:getTypeName())\
        end\
        return unitTypes\
    end\
\
    function dcsCommon.getEnemyCoalitionFor(aCoalition)\
        if type(aCoalition) == \"string\" then \
            aCoalition = aCoalition:lower()\
            if aCoalition == \"red\" then return 2 end\
            if aCoalition == \"blue\" then return 1 end\
            return nil \
        end\
        if aCoalition == 1 then return 2 end\
        if aCoalition == 2 then return 1 end\
        return nil\
    end\
\
    function dcsCommon.getACountryForCoalition(aCoalition)\
        -- scan the table of countries and get the first country that is part of aCoalition\
        -- this is useful if you want to create troops for a coalition but don't know the\
        -- coalition's countries \
        -- we start with id=0 (Russia), go to id=85 (Slovenia), but skip id = 14\
        local i = 0\
        while i < 86 do \
            if i ~= 14 then \
                if (coalition.getCountryCoalition(i) == aCoalition) then return i end\
            end\
            i = i + 1\
        end\
        \
        return nil\
    end\
--\
--\
-- C A L L B A C K   H A N D L E R \
--\
--\
\
    -- installing callbacks\
    -- based on mist, with optional additional hooks for pre- and post-\
    -- processing of the event\
    -- when filtering occurs in pre, an alternative 'rejected' handler can be called \
    function dcsCommon.addEventHandler(f, pre, post, rejected) -- returns ID \
        local handler = {} -- build a wrapper and connect the onEvent\
        --dcsCommon.cbID = dcsCommon.cbID + 1 -- increment unique count\
        handler.id = dcsCommon.uuid(\"eventHandler\")\
        handler.f = f -- the callback itself\
        if (rejected) then handler.rejected = rejected end\
        -- now set up pre- and post-processors. defaults are set in place\
        -- so pre and post are optional. If pre returns false, the callback will\
        -- not be invoked\
        if (pre) then handler.pre = pre else handler.pre = dcsCommon.preCall end\
        if (post) then handler.post = post else handler.post = dcsCommon.postCall end\
        function handler:onEvent(event)\
            if not self.pre(event) then \
                if dcsCommon.verbose then\
--                    trigger.action.outText(\"event \" .. event.id .. \" discarded by pre-processor\", 10)\
                end\
                if (self.rejected) then self.rejected(event) end \
                return\
            end\
            self.f(event) -- call the handler\
            self.post(event) -- do post-processing\
        end\
        world.addEventHandler(handler)\
        return handler.id\
    end\
\
    function dcsCommon.preCall(e)\
        -- we can filter here\
        -- if we return false, the call is abortet\
        if dcsCommon.verbose then\
            trigger.action.outText(\"event \" .. e.id .. \" received: PRE-PROCESSING\", 10)\
        end\
        return true;\
    end;\
\
    function dcsCommon.postCall(e)\
        -- we do pos proccing here \
        if dcsCommon.verbose then\
            trigger.action.outText(\"event \" .. e.id .. \" received: post proc\", 10)\
        end\
    end\
    \
    -- highly specific eventhandler for one event only\
    -- based on above, with direct filtering built in; skips pre\
    -- but does post\
    function dcsCommon.addEventHandlerForEventTypes(f, evTypes, post, rejected) -- returns ID \
        local handler = {} -- build a wrapper and connect the onEvent\
        dcsCommon.cbID = dcsCommon.cbID + 1 -- increment unique count\
        handler.id = dcsCommon.cbID\
        handler.what = evTypes\
        if (rejected) then handler.rejected = rejected end \
        \
        handler.f = f -- set the callback itself\
        -- now set up post-processor. pre is hard-coded to match evType\
        -- post is optional. If event.id is not in evTypes, the callback will\
        -- not be invoked\
        if (post) then handler.post = post else handler.post = dcsCommon.postCall end\
        function handler:onEvent(event)\
            hasMatch = false;\
            for key, evType in pairs(self.what) do\
                if evType == event.id then\
                    hasMatch = true;\
                    break;\
                end;\
            end;\
            if not hasMatch then \
                if dcsCommon.verbose then\
                    trigger.action.outText(\"event \" .. e.id .. \" discarded - not in whitelist evTypes\", 10)\
                end\
                if (self.rejected) then self.rejected(event) end \
                return;\
            end;\
            \
            self.f(event) -- call the actual handler as passed to us\
            self.post(event) -- do post-processing \
        end\
        world.addEventHandler(handler) -- add to event handlers\
        return handler.id\
    end\
    \
    \
    \
    -- remove event handler / callback, identical to Mist \
    -- note we don't call world.removeEventHandler, but rather directly \
    -- access world.eventHandlers directly and remove kvp directly.\
    function dcsCommon.removeEventHandler(id)\
        for key, handler in pairs(world.eventHandlers) do\
            if handler.id and handler.id == id then\
                world.eventHandlers[key] = nil\
                return true\
            end\
        end\
        return false\
    end\
\
--\
--\
-- C L O N I N G \
--\
--\
    -- topClone is a shallow clone of orig, only top level is iterated,\
    -- all values are ref-copied\
    function dcsCommon.topClone(orig)\
        if not orig then return nil end \
        local orig_type = type(orig)\
        local copy\
        if orig_type == 'table' then\
            copy = {}\
            for orig_key, orig_value in pairs(orig) do\
                copy[orig_key] = orig_value\
            end\
        else -- number, string, boolean, etc\
            copy = orig\
        end\
        return copy\
    end\
\
    -- clone is a recursive clone which will also clone\
    -- deeper levels, as used in units \
    function dcsCommon.clone(orig, stripMeta)\
        if not orig then return nil end \
        local orig_type = type(orig)\
        local copy\
        if orig_type == 'table' then\
            copy = {}\
            for orig_key, orig_value in next, orig, nil do\
                copy[dcsCommon.clone(orig_key)] = dcsCommon.clone(orig_value)\
            end\
            if not stripMeta then \
                -- also connect meta data\
                setmetatable(copy, dcsCommon.clone(getmetatable(orig)))\
            else \
                -- strip all except string, and for strings use a fresh string \
                if type(copy) == \"string\" then \
                    local tmp = \"\"\
                    tmp = tmp .. copy -- will get rid of any foreign metas for string \
                    copy = tmp \
                end\
            end\
        else -- number, string, boolean, etc\
            copy = orig\
        end\
        return copy\
    end\
\
    function dcsCommon.copyArray(inArray)\
        if not inArray then return nil end \
        \
        -- warning: this is a ref copy!\
        local theCopy = {}\
        for idx, element in pairs(inArray) do \
            table.insert(theCopy, element)\
        end\
        return theCopy \
    end\
--\
-- \
-- S P A W N I N G \
-- \
-- \
\
    function dcsCommon.createEmptyGroundGroupData (name)\
        local theGroup = {} -- empty group\
        theGroup.visible = false\
        theGroup.taskSelected = true\
        -- theGroup.route = {}\
        -- theGroup.groupId = id\
        theGroup.tasks = {}\
        -- theGroup.hidden = false -- hidden on f10?\
\
        theGroup.units = { } -- insert units here! -- use addUnitToGroupData\
\
        theGroup.x = 0\
        theGroup.y = 0\
        theGroup.name = name\
        -- theGroup.start_time = 0\
        theGroup.task = \"Ground Nothing\"\
        \
        return theGroup\
    end;\
\
    function dcsCommon.createEmptyAircraftGroupData (name)\
        local theGroup = dcsCommon.createEmptyGroundGroupData(name)--{} -- empty group\
\
        theGroup.task = \"Nothing\" -- can be others, like Transport, CAS, etc\
        -- returns with empty route\
        theGroup.route = dcsCommon.createEmptyAircraftRouteData() -- we can add points here \
        return theGroup\
    end;\
\
    function dcsCommon.createAircraftRoutePointData(x, z, altitudeInFeet, knots, altType, action)\
        local rp = {}\
        rp.x = x\
        rp.y = z\
        rp.action = \"Turning Point\"\
        rp.type = \"Turning Point\"\
        if action then rp.action = action; rp.type = action end -- warning: may not be correct, need to verify later\
        rp.alt = altitudeInFeet * 0.3048\
        rp.speed = knots * 0.514444 -- we use \
        rp.alt_type = \"BARO\"\
        if (altType) then rp.alt_type = altType end \
        return rp\
    end\
\
    function dcsCommon.addRoutePointDataToRouteData(inRoute, x, z, altitudeInFeet, knots, altType, action)\
        local p = dcsCommon.createAircraftRoutePointData(x, z, altitudeInFeet, knots, altType, action)\
        local thePoints = inRoute.points \
        table.insert(thePoints, p)\
    end\
    \
    function dcsCommon.addRoutePointDataToGroupData(group, x, z, altitudeInFeet, knots, altType, action)\
        if not group.route then group.route = dcsCommon.createEmptyAircraftRouteData() end\
        local theRoute = group.route \
        dcsCommon.addRoutePointDataToRouteData(theRoute, x, z, altitudeInFeet, knots, altType, action)\
    end\
\
    function dcsCommon.addRoutePointForGroupData(theGroup, theRP)\
        if not theGroup then return end \
        if not theGroup.route then theGroup.route = dcsCommon.createEmptyAircraftRouteData() end\
        \
        local theRoute = theGroup.route \
        local thePoints = theRoute.points \
        table.insert(thePoints, theRP)\
    end\
    \
    function dcsCommon.createEmptyAircraftRouteData()\
        local route = {}\
        route.points = {}\
        return route\
    end\
\
    function dcsCommon.createTakeOffFromParkingRoutePointData(aerodrome)\
        if not aerodrome then return nil end \
            \
        local rp = {}    \
        local freeParkingSlot = dcsCommon.getFirstFreeParkingSlot(aerodrome, 104) -- get big slot first \
        if not freeParkingSlot then \
            freeParkingSlot = dcsCommon.getFirstFreeParkingSlot(aerodrome) -- try any size\
        end\
            \
        if not freeParkingSlot then \
            trigger.action.outText(\"civA: no free parking at \" .. aerodrome:getName(), 30)\
            return nil \
        end\
            \
        local p = freeParkingSlot.vTerminalPos\
            \
        rp.airdromeId = aerodrome:getID() \
        rp.x = p.x\
        rp.y = p.z\
        rp.alt = p.y \
        rp.action = \"From Parking Area\"\
        rp.type = \"TakeOffParking\"\
            \
        rp.speed = 100; -- in m/s? If so, that's 360 km/h \
        rp.alt_type = \"BARO\"\
        return rp\
    end\
\
    function dcsCommon.createOverheadAirdromeRoutPintData(aerodrome)\
        if not aerodrome then return nil end \
        local rp = {}            \
        local p = aerodrome:getPoint()\
        rp.x = p.x\
        rp.y = p.z\
        rp.alt = p.y + 2000 -- 6000 ft overhead\
        rp.action = \"Turning Point\"\
        rp.type = \"Turning Point\"\
            \
        rp.speed = 133; -- in m/s? If so, that's 360 km/h \
        rp.alt_type = \"BARO\"\
        return rp\
    end\
    \
\
    function dcsCommon.createLandAtAerodromeRoutePointData(aerodrome)\
        if not aerodrome then return nil end \
            \
        local rp = {}            \
        local p = aerodrome:getPoint()\
        rp.airdromeId = aerodrome:getID() \
        rp.x = p.x\
        rp.y = p.z\
        rp.alt = p.y \
        rp.action = \"Landing\"\
        rp.type = \"Land\"\
            \
        rp.speed = 100; -- in m/s? If so, that's 360 km/h \
        rp.alt_type = \"BARO\"\
        return rp\
    end\
\
    \
    function dcsCommon.createRPFormationData(findex) -- must be added as \"task\" to an RP. use 4 for Echelon right\
        local task = {}\
        task.id = \"ComboTask\"\
        local params = {}\
        task.params = params\
        local tasks = {}\
        params.tasks = tasks\
        local t1 = {}\
        tasks[1] = t1\
        t1.number = 1\
        t1.auto = false \
        t1.id = \"WrappedAction\"\
        t1.enabled = true\
        local t1p = {}\
        t1.params = t1p\
        local action = {}\
        t1p.action = action \
        action.id = \"Option\"\
        local ap = {}\
        action.params = ap\
        ap.variantIndex = 3\
        ap.name = 5 -- AI.Option.Air.ID 5 = Formation \
        ap.formationIndex = findex -- 4 is echelon_right\
        ap.value = 262147\
        \
        return task \
    end\
\
    function dcsCommon.addTaskDataToRP(theTask, theGroup, rpIndex)\
        local theRoute = theGroup.route\
        local thePoints = theRoute.points\
        local rp = thePoints[rpIndex]\
        rp.task = theTask\
    end\
    \
    -- create a minimal payload table that is compatible with creating \
    -- a unit. you may need to alter this before adding the unit to\
    -- the mission. all params optional \
    function dcsCommon.createPayload(fuel, flare, chaff, gun) \
        local payload = {}\
        payload.pylons = {}\
        if not fuel then fuel = 1000 end -- in kg. check against fuelMassMax in type desc\
        if not flare then flare = 0 end\
        if not chaff then chaff = 0 end\
        if not gun then gun = 0 end\
        return payload \
        \
    end\
\
    function dcsCommon.createCallsign(cs) \
        local callsign = {}\
        callsign[1] = 1\
        callsign[2] = 1\
        callsign[3] = 1\
        if not cs then cs = \"Enfield11\" end\
        callsign.name = cs\
        return callsign\
    end\
    \
\
    -- create the data table required to spawn a unit.\
    -- unit types are defined in https://github.com/mrSkortch/DCS-miscScripts/tree/master/ObjectDB\
    function dcsCommon.createGroundUnitData(name, unitType, transportable)\
        local theUnit = {}\
        unitType = dcsCommon.trim(unitType)\
        theUnit.type = unitType -- e.g. \"LAV-25\",\
        if not transportable then transportable = false end -- elaborate, not requried code\
        theUnit.transportable = {[\"randomTransportable\"] = transportable} \
        -- theUnit.unitId = id \
        theUnit.skill = \"Average\" -- always average \
        theUnit.x = 0 -- make it zero, zero!\
        theUnit.y = 0\
        theUnit.name = name\
        theUnit.playerCanDrive = false\
        theUnit.heading = 0\
        return theUnit\
    end \
\
    function dcsCommon.createAircraftUnitData(name, unitType, transportable, altitude, speed, heading)\
        local theAirUnit = dcsCommon.createGroundUnitData(name, unitType, transportable)\
        theAirUnit.alt = 100 -- make it 100m\
        if altitude then theAirUnit.alt = altitude end \
        theAirUnit.alt_type = \"RADIO\" -- AGL\
        theAirUnit.speed = 77 -- m/s --> 150 knots\
        if speed then theAirUnit.speed = speed end \
        if heading then theAirUnit.heading = heading end \
        theAirUnit.payload = dcsCommon.createPayload()\
        theAirUnit.callsign = dcsCommon.createCallsign()\
        return theAirUnit\
    end\
    \
\
    function dcsCommon.addUnitToGroupData(theUnit, theGroup, dx, dy, heading)\
        -- add a unit to a group, and place it at dx, dy of group's position,\
        -- taking into account unit's own current location\
        if not dx then dx = 0 end\
        if not dy then dy = 0 end\
        if not heading then heading = 0 end\
        theUnit.x = theUnit.x + dx + theGroup.x\
        theUnit.y = theUnit.y + dy + theGroup.y \
        theUnit.heading = heading\
        table.insert(theGroup.units, theUnit)\
    end;\
\
    function dcsCommon.createSingleUnitGroup(name, theUnitType, x, z, heading) \
        -- create the container \
        local theNewGroup = dcsCommon.createEmptyGroundGroupData(name)\
        local aUnit = {}\
        aUnit = dcsCommon.createGroundUnitData(name .. \"-1\", theUnitType, false)\
--        trigger.action.outText(\"dcsCommon - unit name retval \" .. aUnit.name, 30)\
        dcsCommon.addUnitToGroupData(aUnit, theNewGroup, x, z, heading)\
        return theNewGroup\
    end\
    \
\
    function dcsCommon.arrangeGroupDataIntoFormation(theNewGroup, radius, minDist, formation, innerRadius)\
        -- formations:\
        --    (default) \"line\" (left to right along x) -- that is Y direction\
        --    \"line_v\" a line top to bottom -- that is X direction\
        --    \"chevron\" - left to right middle too top\
        --    \"scattered\", \"random\" -- random, innerRadius used to clear area in center\
        --       \"circle\", \"circle_forward\" -- circle, forward facing\
        --    \"circle_in\" -- circle, inwarf facing\
        --    \"circle_out\" -- circle, outward facing\
        --    \"grid\", \"square\", \"rect\" -- optimal rectangle\
        --    \"2cols\", \"2deep\" -- 2 columns, n deep \
        --    \"2wide\" -- 2 columns wide, 2 deep \
\
        local num = #theNewGroup.units \
        \
        -- now do the formation stuff\
        -- make sure that they keep minimum  distance \
--        trigger.action.outText(\"dcsCommon - processing formation \" .. formation .. \" with radius = \" .. radius, 30)\
        if formation == \"LINE_V\" then \
            -- top to bottom in zone (heding 0). -- will run through x-coordinate \
            -- use entire radius top to bottom \
            local currX = -radius\
            local increment = radius * 2/(num - 1) -- MUST NOT TRY WITH 1 UNIT!\
            for i=1, num do\
            \
                local u = theNewGroup.units[i]\
--                trigger.action.outText(\"formation unit \" .. u.name .. \" currX = \" .. currX, 30)\
                u.x = currX\
                currX = currX + increment\
            end\
        \
        elseif formation == \"LINE\" then \
            -- left to right in zone. runs through Y\
            -- left and right are y because at heading 0, forward is x (not y as expected)\
            -- if only one, place in middle of circle and be done \
            if num == 1 then \
                -- nothing. just stay in the middle \
            else \
                local currY = -radius\
                local increment = radius * 2/(num - 1) -- MUST NOT TRY WITH 1 UNIT!\
                for i=1, num do\
                    local u = theNewGroup.units[i]\
--                    trigger.action.outText(\"formation unit \" .. u.name .. \" currX = \" .. currY, 30)\
                    u.y = currY\
                    currY = currY + increment\
                end    \
            end \
            \
        elseif formation == \"CHEVRON\" then \
            -- left to right in zone. runs through Y\
            -- left and right are y because at heading 0, forward is x (not y as expected)\
            local currY = -radius\
            local currX = 0\
            local incrementY = radius * 2/(num - 1) -- MUST NOT TRY WITH 1 UNIT!\
            local incrementX = radius * 2/(num - 1) -- MUST NOT TRY WITH 1 UNIT!\
            for i=1, num do\
                local u = theNewGroup.units[i]\
--                trigger.action.outText(\"formation unit \" .. u.name .. \" currX = \" .. currX .. \" currY = \" .. currY, 30)\
                u.x = currX\
                u.y = currY\
                -- calc coords for NEXT iteration\
                currY = currY + incrementY -- march left to right\
                if i < num / 2 then -- march up\
                    currX = currX + incrementX \
                elseif i == num / 2 then -- even number, keep height\
                    currX = currX + 0 \
                else \
                    currX = currX - incrementX -- march down \
                end \
                -- note: when unit number even, the wedge is sloped. may need an odd/even test for better looks\
            end    \
\
        elseif formation == \"SCATTERED\" or formation == \"RANDOM\" then \
            -- use randomPointInCircle and tehn iterate over all vehicles for mindelta\
            processedUnits = {}\
            for i=1, num do\
                local emergencyBreak = 1 -- prevent endless loop\
                local lowDist = 10000\
                local uPoint = {}\
                local thePoint = {}\
                repeat     -- get random point until mindistance to all is kept or emergencybreak\
                    thePoint = dcsCommon.randomPointInCircle(radius, innerRadius) -- returns x, 0, z\
                    -- check if too close to others\
                    for idx, rUnit in pairs(processedUnits) do -- get min dist to all positioned units\
                        --trigger.action.outText(\"rPnt: thePoint =  \" .. dcsCommon.point2text(thePoint), 30)\
                        uPoint.x = rUnit.x\
                        uPoint.y = 0\
                        uPoint.z = rUnit.y \
                        --trigger.action.outText(\"rPnt: uPoint =  \" .. dcsCommon.point2text(uPoint), 30)\
                        local dist = dcsCommon.dist(thePoint, uPoint) -- measure distance to unit\
                        if (dist < lowDist) then lowDist = dist end\
                    end\
                    emergencyBreak = emergencyBreak + 1\
                until (emergencyBreak > 20) or (lowDist > minDist)\
                -- we have random x, y \
                local u = theNewGroup.units[i] -- get unit to position\
                u.x = thePoint.x\
                u.y = thePoint.z -- z --> y mapping! \
                -- now add the unit to the 'processed' set \
                table.insert(processedUnits, u)\
            end    \
\
        elseif dcsCommon.stringStartsWith(formation, \"CIRCLE\") then\
            -- units are arranged on perimeter of circle defined by radius \
--            trigger.action.outText(\"formation circle detected\", 30)\
            local currAngle = 0\
            local angleInc = 2 * 3.14157 / num -- increase per spoke \
            for i=1, num do\
                local u = theNewGroup.units[i] -- get unit \
                u.x = radius * math.cos(currAngle)\
                u.y = radius * math.sin(currAngle)\
                \
                -- now baldower out heading \
                -- circle, circle_forward no modifier of heading\
                if dcsCommon.stringStartsWith(formation, \"CIRCLE_IN\") then \
                    -- make the heading inward faceing - that's angle + pi\
                    u.heading = u.heading + currAngle + 3.14157\
                elseif dcsCommon.stringStartsWith(formation, \"CIRCLE_OUT\") then \
                    u.heading = u.heading + currAngle + 0\
                end\
\
                currAngle = currAngle + angleInc\
            end\
        elseif formation == \"GRID\" or formation == \"SQUARE\" or formation == \"RECT\" then \
            if num < 2 then return end \
            -- arrange units in an w x h grid\
            -- e-g- 12 units = 4 x 3. \
            -- calculate w \
            local w = math.floor(num^(0.5) + 0.5)\
            dcsCommon.arrangeGroupInNColumns(theNewGroup, w, radius)\
            --[[--\
            local h = math.floor(num / w)\
            --trigger.action.outText(\"AdcsC: num=\" .. num .. \" w=\" .. w .. \"h=\" .. h .. \" -- num%w=\" .. num%w, 30)\
            if (num % w) > 0 then \
                h = h + 1\
            end\
            \
            --trigger.action.outText(\"BdcsC: num=\" .. num .. \" w=\" .. w .. \"h=\" .. h, 30)\
            \
            -- now w * h always >= num and num items fir in that grid\
            -- w is width, h is height, of course :) \
            -- now calculat xInc and yInc\
            local i = 1\
            local xInc = 0 \
            if w > 1 then xInc = 2 * radius / (w-1) end\
            local yInc = 0\
            if h > 1 then yInc = 2 * radius / (h-1) end \
            local currY = radius \
            if h < 2 then currY = 0 end -- special:_ place in Y middle if only one row)\
            while h > 0 do \
                local currX = radius \
                local wCnt = w \
                while wCnt > 0 and (i <= num) do \
                    local u = theNewGroup.units[i] -- get unit \
                    u.x = currX\
                    u.y = currY\
                    currX = currX - xInc\
                    wCnt = wCnt - 1\
                    i = i + 1\
                end\
                currY = currY - yInc \
                h = h - 1\
            end\
            --]]--\
        elseif formation == \"2DEEP\" or formation == \"2COLS\" then\
            if num < 2 then return end \
            -- arrange units in an 2 x h grid\
            local w = 2\
            dcsCommon.arrangeGroupInNColumnsDeep(theNewGroup, w, radius)\
\
        elseif formation == \"2WIDE\" then\
            if num < 2 then return end \
            -- arrange units in an 2 x h grid\
            local w = 2\
            dcsCommon.arrangeGroupInNColumns(theNewGroup, w, radius)\
        else \
            trigger.action.outText(\"dcsCommon - unknown formation: \" .. formation, 30)\
        end\
    \
    end\
    \
    function dcsCommon.arrangeGroupInNColumns(theNewGroup, w, radius)\
        local num = #theNewGroup.units\
        local h = math.floor(num / w)\
        if (num % w) > 0 then \
            h = h + 1\
        end\
        local i = 1\
        local xInc = 0 \
        if w > 1 then xInc = 2 * radius / (w-1) end\
        local yInc = 0\
        if h > 1 then yInc = 2 * radius / (h-1) end \
        local currY = radius \
        if h < 2 then currY = 0 end -- special:_ place in Y middle if only one row)\
        while h > 0 do \
            local currX = radius \
            local wCnt = w \
            while wCnt > 0 and (i <= num) do \
                local u = theNewGroup.units[i] -- get unit \
                u.x = currX\
                u.y = currY\
                currX = currX - xInc\
                wCnt = wCnt - 1\
                i = i + 1\
            end\
            currY = currY - yInc \
            h = h - 1\
        end\
    end\
    \
    function dcsCommon.arrangeGroupInNColumnsDeep(theNewGroup, w, radius)\
        local num = #theNewGroup.units\
        local h = math.floor(num / w)\
        if (num % w) > 0 then \
            h = h + 1\
        end\
        local i = 1\
        local yInc = 0 \
        if w > 1 then yInc = 2 * radius / (w-1) end\
        local xInc = 0\
        if h > 1 then xInc = 2 * radius / (h-1) end \
        local currX = radius \
        if h < 2 then currX = 0 end -- special:_ place in Y middle if only one row)\
        while h > 0 do \
            local currY = radius \
            local wCnt = w \
            while wCnt > 0 and (i <= num) do \
                local u = theNewGroup.units[i] -- get unit \
                u.x = currX\
                u.y = currY\
                currY = currY - yInc\
                wCnt = wCnt - 1\
                i = i + 1\
            end\
            currX = currX - xInc \
            h = h - 1\
        end\
    end\
    \
    \
    function dcsCommon.createGroundGroupWithUnits(name, theUnitTypes, radius, minDist, formation, innerRadius)\
        if not minDist then minDist = 4 end -- meters\
        if not formation then formation = \"line\" end \
        if not radius then radius = 30 end -- meters \
        if not innerRadius then innerRadius = 0 end\
        formation = formation:upper()\
        -- theUnitTypes can be either a single string or a table of strings\
        -- see here for TypeName https://github.com/mrSkortch/DCS-miscScripts/tree/master/ObjectDB\
        -- formation defines how the units are going to be arranged in the\
        -- formation specified. \
        -- formations:\
        --    (default) \"line\" (left to right along x) -- that is Y direction\
        --    \"line_V\" a line top to bottom -- that is X direction\
        --    \"chevron\" - left to right middle too top\
        --    \"scattered\", \"random\" -- random, innerRadius used to clear area in center\
        --       \"circle\", \"circle_forward\" -- circle, forward facing\
        --    \"circle_in\" -- circle, inwarf facing\
        --    \"circle_out\" -- circle, outward facing\
\
        -- first, we create a group\
        local theNewGroup = dcsCommon.createEmptyGroundGroupData(name)\
        \
        -- now add a single unit or multiple units\
        if type(theUnitTypes) ~= \"table\" then \
--            trigger.action.outText(\"dcsCommon - i am here\", 30)\
--            trigger.action.outText(\"dcsCommon - name \" .. name, 30)\
--            trigger.action.outText(\"dcsCommon - unit type \" .. theUnitTypes, 30)\
            \
            local aUnit = {}\
            aUnit = dcsCommon.createGroundUnitData(name .. \"-1\", theUnitTypes, false)\
--            trigger.action.outText(\"dcsCommon - unit name retval \" .. aUnit.name, 30)\
            dcsCommon.addUnitToGroupData(aUnit, theNewGroup, 0, 0) -- create with data at location (0,0)\
            return theNewGroup\
        end \
\
        -- if we get here, theUnitTypes is a table\
        -- now loop and create a unit for each table\
        local num = 1\
        for key, theType in pairs(theUnitTypes) do \
            -- trigger.action.outText(\"+++dcsC: creating unit \" .. name .. \"-\" .. num .. \": \" .. theType, 30)\
            local aUnit = dcsCommon.createGroundUnitData(name .. \"-\"..num, theType, false)\
            dcsCommon.addUnitToGroupData(aUnit, theNewGroup, 0, 0)\
            num = num + 1\
        end\
        \
        dcsCommon.arrangeGroupDataIntoFormation(theNewGroup, radius, minDist, formation, innerRadius)\
        return theNewGroup\
\
    \
    end\
\
-- create a new group, based on group in mission. Groups coords are 0,0 for group and all\
-- x,y and heading\
    function dcsCommon.createGroupDataFromLiveGroup(name, newName) \
        if not newName then newName = dcsCommon.uuid(\"uniqName\") end\
        -- get access to the group\
        local liveGroup = Group.getByName(name)\
        if not liveGroup then return nil end\
        -- get the categorty\
        local cat = liveGroup:getCategory()\
        local theNewGroup = {}\
        \
        -- create a new empty group at (0,0) \
        if cat == Group.Category.AIRPLANE or cat == Group.Category.HELICOPTER then \
            theNewGroup = dcsCommon.createEmptyAircraftGroupData(newName)\
        elseif cat == Group.Category.GROUND then\
            theNewGroup = dcsCommon.createEmptyGroudGroupData(newName)\
        else \
            trigger.action.outText(\"dcsCommon - unknown category: \" .. cat, 30)\
            return nil\
        end\
        \
\
        -- now get all units from live group and create data units\
        -- note that unit data for group has x=0, y=0\
        liveUnits = liveGroup:getUnits()\
        \
        for index, theUnit in pairs(liveUnits) do \
            -- for each unit we get the desc \
            local desc = theUnit:getDesc() -- of interest is only typename \
            local newUnit = dcsCommon.createGroundUnitData(dcsCommon.uuid(newName),\
                                                           desc.typeName,\
                                                           false)\
            -- we now basically have a ground unit at (0,0) \
            -- add mandatory fields by type\
            if cat == Group.Category.AIRPLANE or cat == Group.Category.HELICOPTER then \
                newUnit.alt = 100 -- make it 100m\
                newUnit.alt_type = \"RADIO\" -- AGL\
                newUnit.speed = 77 -- m/s --> 150 knots\
                newUnit.payload = dcsCommon.createPayload() -- empty payload\
                newUnit.callsign = dcsCommon.createCallsign() -- 'enfield11'\
                \
            elseif cat == Group.Category.GROUND then\
                -- we got all we need\
            else \
                -- trigger.action.outText(\"dcsCommon - unknown category: \" .. cat, 30)\
                -- return nil\
                -- we also got all we need\
            end            \
            \
        end\
    \
    end;\
    \
    function dcsCommon.rotatePointAroundOriginRad(inX, inY, angle) -- angle in degrees\
        local c = math.cos(angle)\
        local s = math.sin(angle)\
        local px\
        local py \
        px = inX * c - inY * s\
        py = inX * s + inY * c\
        return px, py        \
    end\
    \
    function dcsCommon.rotatePointAroundOrigin(inX, inY, angle) -- angle in degrees\
        local rads =  3.14152 / 180 -- convert to radiants. \
        angle = angle * rads -- turns into rads\
        local px, py = dcsCommon.rotatePointAroundOriginRad(inX, inY, angle)\
        return px, py        \
    end\
    \
    function dcsCommon.rotatePointAroundPointRad(x, y, px, py, angle)\
        x = x - px \
        y = y - py\
        x, y = dcsCommon.rotatePointAroundOriginRad(x, y, angle)\
        x = x + px \
        y = y + py \
        return x, y\
    end\
\
    function dcsCommon.rotatePointAroundPointDeg(x, y, px, py, degrees)\
        x, y = dcsCommon.rotatePointAroundPointRad(x, y, px, py, degrees * 3.14152 / 180)\
        return x, y\
    end\
\
    -- rotates a Vec3-base inPoly on XZ pane around inPoint on XZ pane\
     function dcsCommon.rotatePoly3AroundVec3Rad(inPoly, inPoint, rads)\
        local outPoly = {}\
        for idx, aVertex in pairs(inPoly) do \
            local x, z = dcsCommon.rotatePointAroundPointRad(aVertex.x, aVertex.z, inPoint.x, inPoint.z, rads)        \
            local v3 = {x = x, y = aVertex.y, z = z}\
            outPoly[idx] = v3\
        end \
        return outPoly \
    end\
\
    function dcsCommon.rotateUnitData(theUnit, degrees, cx, cz)\
        if not cx then cx = 0 end\
        if not cz then cz = 0 end\
        local cy = cz \
        --trigger.action.outText(\"+++dcsC:rotGrp cy,cy = \"..cx .. \",\" .. cy, 30)\
        \
        local rads = degrees *  3.14152 / 180\
        do\
            theUnit.x = theUnit.x - cx -- MOVE TO ORIGIN OF ROTATION\
            theUnit.y = theUnit.y - cy                 \
            theUnit.x, theUnit.y = dcsCommon.rotatePointAroundOrigin(theUnit.x, theUnit.y, degrees)\
            theUnit.x = theUnit.x + cx -- MOVE BACK \
            theUnit.y = theUnit.y + cy                 \
\
            -- may also want to increase heading by degrees\
            theUnit.heading = theUnit.heading + rads \
        end\
    end\
    \
\
    function dcsCommon.rotateGroupData(theGroup, degrees, cx, cz)\
        if not cx then cx = 0 end\
        if not cz then cz = 0 end\
        local cy = cz \
        --trigger.action.outText(\"+++dcsC:rotGrp cy,cy = \"..cx .. \",\" .. cy, 30)\
        \
        local rads = degrees *  3.14152 / 180\
        -- turns all units in group around the group's center by degrees.\
        -- may also need to turn individual units by same amount\
        for i, theUnit in pairs (theGroup.units) do\
            theUnit.x = theUnit.x - cx -- MOVE TO ORIGIN OF ROTATION\
            theUnit.y = theUnit.y - cy                 \
            theUnit.x, theUnit.y = dcsCommon.rotatePointAroundOrigin(theUnit.x, theUnit.y, degrees)\
            theUnit.x = theUnit.x + cx -- MOVE BACK \
            theUnit.y = theUnit.y + cy                 \
\
            -- may also want to increase heading by degrees\
            theUnit.heading = theUnit.heading + rads \
            -- now kill psi if it existed before \
            -- theUnit.psi = nil\
            -- better code: psi is always -heading. Nobody knows what psi is, though\
            if theUnit.psi then \
                theUnit.psi = -theUnit.heading \
            end\
        end\
    end\
\
    function dcsCommon.offsetGroupData(theGroup, dx, dy)\
        -- add dx and dy to group's and all unit's coords\
        for i, theUnit in pairs (theGroup.units) do \
            theUnit.x = theUnit.x + dx\
            theUnit.y = theUnit.y + dy\
        end\
        \
        theGroup.x = theGroup.x + dx\
        theGroup.y = theGroup.y + dy \
    end\
    \
    function dcsCommon.moveGroupDataTo(theGroup, xAbs, yAbs)\
        local dx = xAbs-theGroup.x\
        local dy = yAbs-theGroup.y\
        dcsCommon.offsetGroupData(theGroup, dx, dy)\
    end\
    \
    -- static objectr shapes and types are defined here\
    -- https://github.com/mrSkortch/DCS-miscScripts/tree/master/ObjectDB/Statics\
    \
    function dcsCommon.createStaticObjectData(name, objType, heading, dead, cargo, mass)\
        local staticObj = {}\
        if not heading then heading = 0 end \
        if not dead then dead = false end \
        if not cargo then cargo = false end \
        objType = dcsCommon.trim(objType) \
        \
        staticObj.heading = heading\
        -- staticObj.groupId = 0\
        -- staticObj.shape_name = shape -- e.g. H-Windsock_RW\
        staticObj.type = objType  -- e.g. Windsock\
        -- [\"unitId\"] = 3,\
        staticObj.rate = 1 -- score when killed\
        staticObj.name = name\
        -- staticObj.category = \"Fortifications\",\
        staticObj.y = 0\
        staticObj.x = 0\
        staticObj.dead = dead\
        staticObj.canCargo = cargo -- to cargo\
        if cargo then \
            if not mass then mass = 1234 end \
            staticObj.mass = mass -- to cargo\
        end\
        return staticObj\
    end\
    \
    function dcsCommon.createStaticObjectDataAt(loc, name, objType, heading, dead)\
        local theData = dcsCommon.createStaticObjectData(name, objType, heading, dead)\
        theData.x = loc.x\
        theData.y = loc.z \
        return theData\
    end\
    \
    function dcsCommon.createStaticObjectForCoalitionAtLocation(theCoalition, loc, name, objType, heading, dead) \
        if not heading then heading = math.random(360) * 3.1415 / 180 end\
        local theData = dcsCommon.createStaticObjectDataAt(loc, name, objType, heading, dead)\
        local theStatic = coalition.addStaticObject(theCoalition, theData)\
        return theStatic\
    end\
    \
    function dcsCommon.createStaticObjectForCoalitionInRandomRing(theCoalition, objType, x, z, innerRadius, outerRadius, heading, alive) \
        if not outerRadius then outerRadius = innerRadius end\
        if not heading then heading = math.random(360) * 3.1415 / 180 end\
        local dead = not alive\
        local p = dcsCommon.randomPointInCircle(outerRadius, innerRadius, x, z)\
        local theData = dcsCommon.createStaticObjectData(dcsCommon.uuid(\"static\"), objType, heading, dead)\
        theData.x = p.x\
        theData.y = p.z \
        \
        local theStatic = coalition.addStaticObject(theCoalition, theData)\
        return theStatic\
    end\
    \
    \
    \
    function dcsCommon.linkStaticDataToUnit(theStatic, theUnit, dx, dy, heading)\
        if not theStatic then \
            trigger.action.OutText(\"+++dcsC: NIL theStatic on linkStatic!\", 30)\
            return \
        end\
        -- NOTE: we may get current heading and subtract/add \
        -- to original heading \
        local rotX, rotY = dcsCommon.rotatePointAroundOrigin(dx, dy, -heading)\
        \
        if not theUnit then return end\
        if not theUnit:isExist() then return end \
        theStatic.linkOffset = true \
        theStatic.linkUnit = theUnit:getID()\
        local unitPos = theUnit:getPoint()\
        local offsets = {}\
        offsets.x = rotX  \
        offsets.y = rotY \
        offsets.angle = 0\
        theStatic.offsets = offsets\
    end\
    \
    function dcsCommon.offsetStaticData(theStatic, dx, dy)\
        theStatic.x = theStatic.x + dx\
        theStatic.y = theStatic.y + dy\
        -- now check if thre is a route (for linked objects)\
        if theStatic.route then \
            -- access points[1] x and y and copy from main\
            theStatic.route.points[1].x = theStatic.x\
            theStatic.route.points[1].y = theStatic.y\
        end\
    end\
    \
    function dcsCommon.moveStaticDataTo(theStatic, x, y)\
        theStatic.x = x\
        theStatic.y = y\
        -- now check if thre is a route (for linked objects)\
        if theStatic.route then \
            -- access points[1] x and y and copy from main\
            theStatic.route.points[1].x = theStatic.x\
            theStatic.route.points[1].y = theStatic.y\
        end\
\
    end\
\
function dcsCommon.synchGroupData(inGroupData) -- update group data block by \
-- comparing it to spawned group and update units by x, y, heding and isExist \
-- modifies inGroupData!\
    if not inGroupData then return end \
    -- groupdata from game, NOT MX DATA!\
    -- we synch the units and their coords \
    local livingUnits = {}\
    for idx, unitData in pairs(inGroupData.units) do \
        local theUnit = Unit.getByName(unitData.name)\
        if theUnit and theUnit:isExist() and theUnit:getLife()>1 then \
            -- update x and y and heading\
            local pos = theUnit:getPoint()\
            unitData.unitId = theUnit:getID()\
            unitData.x = pos.x \
            unitData.y = pos.z -- !!!!\
            unitData.heading = dcsCommon.getUnitHeading(gUnit)\
            table.insert(livingUnits, unitData)\
        end\
    end\
    inGroupData.units = livingUnits \
end\
\
--\
--\
-- M I S C   M E T H O D S \
--\
--\
\
-- as arrayContainsString, except it includes wildcard matches if EITHER \
-- ends on \"*\"\
    function dcsCommon.wildArrayContainsString(theArray, theString, caseSensitive) \
        if not theArray then return false end\
        if not theString then return false end\
        if not caseSensitive then caseSensitive = false end \
        if type(theArray) ~= \"table\" then \
            trigger.action.outText(\"***arrayContainsString: theArray is not type table but <\" .. type(theArray) .. \">\", 30)\
        end\
        if not caseSensitive then theString = string.upper(theString) end \
        \
        --trigger.action.outText(\"wildACS: theString = <\" .. theString .. \">, theArray contains <\" .. #theArray .. \"> elements\", 30)\
        local wildIn = dcsCommon.stringEndsWith(theString, \"*\")\
        if wildIn then dcsCommon.removeEnding(theString, \"*\") end \
        for idx, theElement in pairs(theArray) do -- i = 1, #theArray do \
            --local theElement = theArray[i]\
            --trigger.action.outText(\"test e <\" .. theElement .. \"> against s <\" .. theString .. \">\", 30)\
            if not caseSensitive then theElement = string.upper(theElement) end \
            local wildEle = dcsCommon.stringEndsWith(theElement, \"*\")\
            if wildEle then theElement = dcsCommon.removeEnding(theElement, \"*\") end \
            --trigger.action.outText(\"matching s=<\" .. theString .. \"> with e=<\" .. theElement .. \">\", 30)\
            if wildEle and wildIn then \
                -- both end on wildcards, partial match for both\
                if dcsCommon.stringStartsWith(theElement, theString) then return true end \
                if dcsCommon.stringStartsWith(theString, theElement) then return true end \
                --trigger.action.outText(\"match e* with s* failed.\", 30)\
            elseif wildEle then \
                -- Element is a wildcard, partial match \
                if dcsCommon.stringStartsWith(theString, theElement) then return true end\
                --trigger.action.outText(\"startswith - match e* <\" .. theElement .. \"> with s <\" .. theString .. \"> failed.\", 30)\
            elseif wildIn then\
                -- theString is a wildcard. partial match \
                if dcsCommon.stringStartsWith(theElement, theString) then return true end\
                --trigger.action.outText(\"match e with s* failed.\", 30)\
            else\
                -- standard: no wildcards, full match\
                if theElement == theString then return true end \
                --trigger.action.outText(\"match e with s (straight) failed.\", 30)\
            end\
            \
        end\
        return false \
    end\
\
\
    function dcsCommon.arrayContainsString(theArray, theString) \
        if not theArray then return false end\
        if not theString then return false end\
        if type(theArray) ~= \"table\" then \
            trigger.action.outText(\"***arrayContainsString: theArray is not type table but <\" .. type(theArray) .. \">\", 30)\
        end\
        for i = 1, #theArray do \
            if theArray[i] == theString then return true end \
        end\
        return false \
    end\
    \
    function dcsCommon.splitString(inputstr, sep) \
        if sep == nil then\
            sep = \"%s\"\
        end\
        if inputstr == nil then \
            inputstr = \"\"\
        end\
        \
        local t={}\
        for str in string.gmatch(inputstr, \"([^\"..sep..\"]+)\") do\
            table.insert(t, str)\
        end\
        return t\
    \
    end\
    \
    function dcsCommon.trimFront(inputstr) \
        if not inputstr then return nil end \
        local s = inputstr\
        while string.len(s) > 1 and string.sub(s, 1, 1) == \" \" do \
            local snew = string.sub(s, 2) -- all except first\
            s = snew\
        end\
        return s\
    end\
    \
    function dcsCommon.trimBack(inputstr)\
        if not inputstr then return nil end \
        local s = inputstr\
        while string.len(s) > 1 and string.sub(s, -1) == \" \" do \
            local snew = string.sub(s, 1, -2) -- all except last\
            s = snew\
        end\
        return s\
    end\
    \
    function dcsCommon.trim(inputstr) \
        local t1 = dcsCommon.trimFront(inputstr)\
        local t2 = dcsCommon.trimBack(t1)\
        return t2\
    end\
    \
    function dcsCommon.trimArray(theArray)\
        local trimmedArray = {}\
        for idx, element in pairs(theArray) do \
            local tel = dcsCommon.trim(element)\
            table.insert(trimmedArray, tel)\
        end\
        return trimmedArray\
    end\
    \
    function dcsCommon.string2Array(inString, deli, uCase)\
        if not inString then return {} end \
        if not deli then return {} end \
        if not uCase then uCase = false end\
        if uCase then inString = string.upper(inString) end\
        inString = dcsCommon.trim(inString)\
        if dcsCommon.containsString(inString, deli) then \
            local a = dcsCommon.splitString(inString, deli)\
            a = dcsCommon.trimArray(a)\
            return a \
        else \
            return {inString}\
        end\
    end\
    \
    function dcsCommon.array2string(inArray, deli)\
        if not deli then deli = \",\" end\
        if type(inArray) ~= \"table\" then return \"<err in array2string: not an array>\" end\
        local s = \"\"\
        local count = 0\
        for idx, ele in pairs(inArray) do\
            if count > 0 then s = s .. deli .. \" \" end\
            s = s .. ele\
        end\
        return s\
    end\
    \
    function dcsCommon.stripLF(theString)\
        return theString:gsub(\"[\\r\\n]\", \"\")\
    end\
    \
    function dcsCommon.removeBlanks(theString)\
        return theString:gsub(\"%s\", \"\")\
    end\
    \
    function dcsCommon.stringIsPositiveNumber(theString)\
        -- only full integer positive numbers supported \
        if not theString then return false end \
--        if theString == \"\" then return false end \
        for i = 1, #theString do \
            local c = theString:sub(i,i)\
            if c < \"0\" or c > \"9\" then return false end \
        end\
        return true \
    end\
    \
    function dcsCommon.stringStartsWithDigit(theString)\
        if #theString < 1 then return false end \
        local c = string.sub(theString, 1, 1) \
        return c >= \"0\" and c <= \"9\" \
    end\
    \
    function dcsCommon.stringStartsWithLetter(theString)\
        if #theString < 1 then return false end \
        local c = string.sub(theString, 1, 1)\
        if c >= \"a\" and c <= \"z\" then return true end  \
        if c >= \"A\" and c <= \"Z\" then return true end \
        return false \
    end\
    \
    function dcsCommon.stringStartsWith(theString, thePrefix, caseInsensitive)\
        if not theString then return false end \
        if not thePrefix then return false end \
        if not caseInsensitive then caseInsensitive = false end \
        \
        if caseInsensitive then \
            theString = string.upper(theString)\
            thePrefix = string.upper(theString)\
        end\
        -- new code because old 'string.find' had some really \
        -- strange results with aircraft types. Prefix \"A-10\" did not \
        -- match string \"A-10A\" etc. \
        \
        -- superseded: string.find (s, pattern [, init [, plain]]) solves the problem \
        \
        --[[\
        local pl = string.len(thePrefix)\
        if pl > string.len(theString) then return false end\
        if pl < 1 then return false end\
         for i=1, pl do \
        local left =  string.sub(theString, i, i)\
        local right = string.sub(thePrefix, i, i)\
            if left ~= right then \
                return false\
            end\
        end\
    \
        return true \
--]]--        trigger.action.outText(\"---- OK???\", 30)\
        -- strange stuff happening with some strings, let's investigate \
        \
        local i, j = string.find(theString, thePrefix, 1, true)\
        return (i == 1)\
--[[--\
        if res then\
            trigger.action.outText(\"startswith: <\" .. theString .. \"> pre <\" .. thePrefix .. \"> --> YES\", 30)\
        else \
            trigger.action.outText(\"startswith: <\" .. theString .. \"> nojoy pre <\" .. thePrefix .. \">\", 30)\
        end\
        return res \
--]]--\
    end\
    \
    function dcsCommon.removePrefix(theString, thePrefix)\
        if not dcsCommon.stringStartsWith(theString, thePrefix) then \
            return theString\
        end;\
        return theString:sub(1 + #thePrefix)\
    end\
    \
    function dcsCommon.stringEndsWith(theString, theEnding)\
        return theEnding == \"\" or theString:sub(-#theEnding) == theEnding\
    end\
    \
    function dcsCommon.removeEnding(theString, theEnding) \
        if not dcsCommon.stringEndsWith(theString, theEnding) then \
            return theString\
        end\
        return theString:sub(1, #theString - #theEnding)\
    end\
    \
    function dcsCommon.containsString(inString, what, caseSensitive)\
        if (not caseSensitive) then \
            inString = string.upper(inString)\
            what = string.upper(what)\
        end\
        if inString == what then return true end -- when entire match \
        return string.find(inString, what, 1, true) -- 1, true means start at 1, plaintext\
    end\
    \
    function dcsCommon.bool2Text(theBool) \
        if not theBool then theBool = false end \
        if theBool then return \"true\" end \
        return \"false\"\
    end\
    \
    function dcsCommon.bool2YesNo(theBool)\
        if not theBool then \
            theBool = false\
            return \"NIL\"\
        end \
        if theBool then return \"yes\" end \
        return \"no\"\
    end\
    \
    function dcsCommon.bool2Num(theBool)\
        if not theBool then theBool = false end \
        if theBool then return 1 end \
        return 0\
    end\
\
    function dcsCommon.point2text(p) \
        if not p then return \"<!NIL!>\" end \
        local t = \"[x=\"\
        if p.x then t = t .. p.x .. \", \" else t = t .. \"<nil>, \" end \
        if p.y then t = t .. \"y=\" .. p.y .. \", \" else t = t .. \"y=<nil>, \" end \
        if p.z then t = t .. \"z=\" .. p.z .. \"]\" else t = t .. \"z=<nil>]\" end \
        return t \
    end\
\
    function dcsCommon.string2GroupCat(inString)\
\
        if not inString then return 2 end -- default ground \
        inString = inString:lower()\
        inString = dcsCommon.trim(inString)\
\
        local catNum = tonumber(inString)\
        if catNum then \
            if catNum < 0 then catNum = 0 end \
            if catNum > 4 then catNum = 4 end \
            return catNum \
        end\
    \
        catNum = 2 -- ground default \
        if dcsCommon.stringStartsWith(inString, \"grou\") then catNum = 2 end \
        if dcsCommon.stringStartsWith(inString, \"air\") then catNum = 0 end\
        if dcsCommon.stringStartsWith(inString, \"hel\") then catNum = 1 end\
        if dcsCommon.stringStartsWith(inString, \"shi\") then catNum = 3 end\
        if dcsCommon.stringStartsWith(inString, \"trai\") then catNum = 4 end\
\
        return catNum\
    end\
\
    function dcsCommon.string2ObjectCat(inString)\
\
        if not inString then return 3 end -- default static \
        inString = inString:lower()\
        inString = dcsCommon.trim(inString)\
\
        local catNum = tonumber(inString)\
        if catNum then \
            if catNum < 0 then catNum = 0 end \
            if catNum > 6 then catNum = 6 end \
            return catNum \
        end\
    \
        catNum = 3 -- static default \
        if dcsCommon.stringStartsWith(inString, \"uni\") then catNum = 1 end \
        if dcsCommon.stringStartsWith(inString, \"wea\") then catNum = 2 end\
        if dcsCommon.stringStartsWith(inString, \"bas\") then catNum = 4 end\
        if dcsCommon.stringStartsWith(inString, \"sce\") then catNum = 5 end\
        if dcsCommon.stringStartsWith(inString, \"car\") then catNum = 6 end\
\
        return catNum\
    end\
\
    function dcsCommon.menu2text(inMenu)\
        if not inMenu then return \"<nil>\" end\
        local s = \"\"\
        for n, v in pairs(inMenu) do \
            if type(v) == \"string\" then \
                if s == \"\" then s = \"[\" .. v .. \"]\"  else \
                    s = s .. \" | [\" .. type(v) .. \"]\" end\
            else \
                if s == \"\" then s = \"[<\" .. type(v) .. \">]\"  else\
                    s = s .. \" | [<\" .. type(v) .. \">]\" end\
            end\
        end\
        return s\
    end\
\
    -- recursively show the contents of a variable\
    function dcsCommon.dumpVar(key, value, prefix, inrecursion)\
        if not inrecursion then \
            -- output a marker to find in the log / screen\
            env.info(\"*** dcsCommon vardump START\")\
        end\
        if not value then value = \"nil\" end\
        if not prefix then prefix = \"\" end\
        prefix = \" \" .. prefix\
        if type(value) == \"table\" then \
            env.info(prefix .. key .. \": [ \")\
            -- iterate through all kvp\
            for k,v in pairs (value) do\
                dcsCommon.dumpVar(k, v, prefix, true)\
            end\
            env.info(prefix .. \" ] - end \" .. key)\
            \
        elseif type(value) == \"boolean\" then \
            local b = \"false\"\
            if value then b = \"true\" end\
            env.info(prefix .. key .. \": \" .. b)\
            \
        else -- simple var, show contents, ends recursion\
            env.info(prefix .. key .. \": \" .. value)\
        end\
        \
        if not inrecursion then \
            -- output a marker to find in the log / screen\
            trigger.action.outText(\"=== dcsCommon vardump END\", 30)\
            env.info(\"=== dcsCommon vardump END\")\
        end\
    end\
    \
    function dcsCommon.dumpVar2Str(key, value, prefix, inrecursion)\
        if not inrecursion then \
            -- output a marker to find in the log / screen\
            trigger.action.outText(\"*** dcsCommon vardump START\",30)\
        end\
        if not value then value = \"nil\" end\
        if not prefix then prefix = \"\" end\
        prefix = \" \" .. prefix\
        if getmetatable(value) then \
            if type(value) == \"string\" then \
            else \
                trigger.action.outText(prefix .. key (\" .. type(value) .. \") .. \" HAS META\", 30)\
            end\
        end\
        if type(value) == \"table\" then \
            trigger.action.outText(prefix .. key .. \": [ \", 30)\
            -- iterate through all kvp\
            for k,v in pairs (value) do\
                dcsCommon.dumpVar2Str(k, v, prefix, true)\
            end\
            trigger.action.outText(prefix .. \" ] - end \" .. key, 30)\
            \
        elseif type(value) == \"boolean\" then \
            local b = \"false\"\
            if value then b = \"true\" end\
            trigger.action.outText(prefix .. key .. \": \" .. b, 30)\
            \
        else -- simple var, show contents, ends recursion\
            trigger.action.outText(prefix .. key .. \": \" .. value, 30)\
        end\
        \
        if not inrecursion then \
            -- output a marker to find in the log / screen\
            trigger.action.outText(\"=== dcsCommon vardump END\", 30)\
            --env.info(\"=== dcsCommon vardump END\")\
        end\
    end\
    \
\
    \
    function dcsCommon.numberUUID()\
        dcsCommon.simpleUUID = dcsCommon.simpleUUID + 1\
        return dcsCommon.simpleUUID\
    end\
\
    function dcsCommon.uuid(prefix)\
        --dcsCommon.uuIdent = dcsCommon.uuIdent + 1\
        if not prefix then prefix = dcsCommon.uuidStr end\
        return prefix .. \"-\" .. dcsCommon.numberUUID() -- dcsCommon.uuIdent\
    end\
    \
    function dcsCommon.event2text(id) \
        if not id then return \"error\" end\
        if id == 0 then return \"invalid\" end\
        -- translate the event id to text\
        local events = {\"shot\", \"hit\", \"takeoff\", \"land\",\
                        \"crash\", \"eject\", \"refuel\", \"dead\",\
                        \"pilot dead\", \"base captured\", \"mission start\", \"mission end\", -- 12\
                        \"took control\", \"refuel stop\", \"birth\", \"human failure\", \
                        \"det. failure\", \"engine start\", \"engine stop\", \"player enter unit\",\
                        \"player leave unit\", \"player comment\", \"start shoot\", \"end shoot\",\
                        \"mark add\", \"mark changed\", \"makr removed\", \"kill\", \
                        \"score\", \"unit lost\", \"land after eject\", \"Paratrooper land\", \
                        \"chair discard after eject\", \"weapon add\", \"trigger zone\", \"landing quality mark\",\
                        \"BDA\", \"max\"}\
        if id > #events then return \"Unknown (ID=\" .. id .. \")\" end\
        return events[id]\
    end\
\
    function dcsCommon.smokeColor2Text(smokeColor)\
        if (smokeColor == 0) then return \"Green\" end\
        if (smokeColor == 1) then return \"Red\" end\
        if (smokeColor == 2) then return \"White\" end\
        if (smokeColor == 3) then return \"Orange\" end\
        if (smokeColor == 4) then return \"Blue\" end\
        \
        return (\"unknown: \" .. smokeColor)\
    end\
    \
    function dcsCommon.flareColor2Text(flareColor)\
        if (flareColor == 0) then return \"Green\" end\
        if (flareColor == 1) then return \"Red\" end\
        if (flareColor == 2) then return \"White\" end\
        if (flareColor == 3) then return \"Yellow\" end\
        if (flareColor < 0) then return \"Random\" end \
        return (\"unknown: \" .. flareColor)\
    end\
    \
    function dcsCommon.smokeColor2Num(smokeColor)\
        if not smokeColor then smokeColor = \"green\" end \
        if type(smokeColor) ~= \"string\" then return 0 end \
        smokeColor = smokeColor:lower()\
        if (smokeColor == \"green\") then return 0 end \
        if (smokeColor == \"red\") then return 1 end \
        if (smokeColor == \"white\") then return 2 end \
        if (smokeColor == \"orange\") then return 3 end \
        if (smokeColor == \"blue\") then return 4 end \
        return 0\
    end\
\
    function dcsCommon.flareColor2Num(flareColor)\
        if not flareColor then flareColor = \"green\" end \
        if type(flareColor) ~= \"string\" then return 0 end \
        flareColor = flareColor:lower()\
        if (flareColor == \"green\") then return 0 end \
        if (flareColor == \"red\") then return 1 end \
        if (flareColor == \"white\") then return 2 end \
        if (flareColor == \"yellow\") then return 3 end \
        if (flareColor == \"random\") then return -1 end \
        if (flareColor == \"rnd\") then return -1 end \
        return 0\
    end\
\
    \
    function dcsCommon.markPointWithSmoke(p, smokeColor)\
        if not smokeColor then smokeColor = 0 end \
        local x = p.x \
        local z = p.z -- do NOT change the point directly\
        -- height-correct\
        local y = land.getHeight({x = x, y = z})\
        local newPoint= {x = x, y = y + 2, z = z}\
        trigger.action.smoke(newPoint, smokeColor)\
    end\
\
-- based on buzzer1977's idea, channel is number, eg in 74X, channel is 74, mode is \"X\"\
    function tacan2freq(channel, mode)    \
        if not mode then mode = \"X\" end \
        if not channel then channel = 1 end \
        if type(mode) ~= \"string\" then mode = \"X\" end \
        mode = mode:upper()\
        local offset = 1000000 * channel\
        if channel < 64 then \
            if mode == \"Y\" then\
                return 1087000000 + offset\
            end\
            return 961000000 + offset -- mode x\
        end\
    \
        if mode == \"Y\" then\
            return 961000000 + offset\
        end\
        return 1087000000 + offset -- mode x\
    end\
    \
    function dcsCommon.processHMS(msg, delta)\
        local rS = math.floor(delta)\
        local remainS = tostring(rS)\
        local rM = math.floor(delta/60)\
        local remainM = tostring(rM)\
        local rH = math.floor(delta/3600)\
        local remainH = tostring(rH)\
        local hmsH = remainH \
        if rH < 10 then hmsH = \"0\" .. hmsH end \
        \
        local hmsCount = delta - (rH * 3600) -- mins left \
        local mins = math.floor (hmsCount / 60)\
        local hmsM = tostring(mins)\
        if mins < 10 then hmsM = \"0\" .. hmsM end \
        \
        hmsCount = hmsCount - (mins * 60) \
        local secs = math.floor(hmsCount)\
        local hmsS = tostring(secs)\
        if secs < 10 then hmsS = \"0\" .. hmsS end \
        \
        msg = string.gsub(msg, \"<s>\", remainS)\
        msg = string.gsub(msg, \"<m>\", remainM)\
        msg = string.gsub(msg, \"<h>\", remainH)\
        \
        msg = string.gsub(msg, \"<:s>\", hmsS)\
        msg = string.gsub(msg, \"<:m>\", hmsM)\
        msg = string.gsub(msg, \"<:h>\", hmsH)\
        \
        return msg \
    end\
    \
    function dcsCommon.nowString()\
        local absSecs = timer.getAbsTime()-- + env.mission.start_time\
        while absSecs > 86400 do \
            absSecs = absSecs - 86400 -- subtract out all days \
        end\
        return dcsCommon.processHMS(\"<:h>:<:m>:<:s>\", absSecs)\
    end\
    \
    function dcsCommon.str2num(inVal, default) \
        if not default then default = 0 end\
        if not inVal then return default end\
        if type(inVal) == \"number\" then return inVal end                 \
        local num = nil\
        if type(inVal) == \"string\" then num = tonumber(inVal) end\
        if not num then return default end\
        return num\
    end\
    \
    function dcsCommon.stringRemainsStartingWith(theString, startingWith)\
        -- find the first position where startingWith starts \
        local pos = theString:find(startingWith)\
        if not pos then return theString end \
        -- now return the entire remainder of the string from pos \
        local nums = theString:len() - pos + 1\
        return theString:sub(-nums)\
    end\
\
--\
--\
-- V E C T O R   M A T H \
--\
--\
\
function dcsCommon.vAdd(a, b) \
    local r = {}\
    if not a then a = {x = 0, y = 0, z = 0} end\
    if not b then b = {x = 0, y = 0, z = 0} end\
    r.x = a.x + b.x \
    r.y = a.y + b.y \
    r.z = a.z + b.z \
    return r \
end\
\
function dcsCommon.vSub(a, b) \
    local r = {}\
    if not a then a = {x = 0, y = 0, z = 0} end\
    if not b then b = {x = 0, y = 0, z = 0} end\
    r.x = a.x - b.x \
    r.y = a.y - b.y \
    r.z = a.z - b.z \
    return r \
end\
\
function dcsCommon.vMultScalar(a, f) \
    local r = {}\
    if not a then a = {x = 0, y = 0, z = 0} end\
    if not f then f = 0 end\
    r.x = a.x * f \
    r.y = a.y * f \
    r.z = a.z * f \
    return r \
end\
\
function dcsCommon.vLerp (a, b, t)\
    if not a then a = {x = 0, y = 0, z = 0} end\
    if not b then b = {x = 0, y = 0, z = 0} end\
    \
    local d = dcsCommon.vSub(b, a)\
    local dt = dcsCommon.vMultScalar(d, t)\
    local r = dcsCommon.vAdd(a, dt)\
    return r\
end\
\
function dcsCommon.mag(x, y, z) \
    if not x then x = 0 end\
    if not y then y = 0 end \
    if not z then z = 0 end \
    \
    return (x * x + y * y + z * z)^0.5\
end\
\
function dcsCommon.vMag(a) \
    if not a then return 0 end \
    if not a.x then a.x = 0 end \
    if not a.y then a.y = 0 end \
    if not a.z then a.z = 0 end\
    return dcsCommon.mag(a.x, a.y, a.z) \
end\
\
function dcsCommon.magSquare(x, y, z) \
    if not x then x = 0 end\
    if not y then y = 0 end \
    if not z then z = 0 end \
    \
    return (x * x + y * y + z * z)\
end\
\
function dcsCommon.vNorm(a) \
    if not a then return {x = 0, y = 0, z = 0} end \
    m = dcsCommon.vMag(a)\
    if m <= 0 then return {x = 0, y = 0, z = 0} end \
    local r = {}\
    r.x = a.x / m \
    r.y = a.y / m \
    r.z = a.z / m\
    return r \
end\
\
function dcsCommon.dot (a, b) \
    if not a then a = {} end \
    if not a.x then a.x = 0 end \
    if not a.y then a.y = 0 end \
    if not a.z then a.z = 0 end\
    if not b then b = {} end \
    if not b.x then b.x = 0 end \
    if not b.y then b.y = 0 end \
    if not b.z then b.z = 0 end \
    \
    return a.x * b.x + a.y * b.y + a.z * b.z \
end\
--\
-- UNIT MISC\
-- \
function dcsCommon.isSceneryObject(theUnit)\
    if not theUnit then return false end\
    return theUnit.getCoalition == nil -- scenery objects do not return a coalition \
end\
\
function dcsCommon.isTroopCarrierType(theType, carriers)\
    if not theType then return false end \
    if not carriers then carriers = dcsCommon.troopCarriers \
    end \
    -- remember that arrayContainsString is case INsensitive by default \
    if dcsCommon.wildArrayContainsString(carriers, theType) then \
        -- may add additional tests before returning true\
        return true\
    end\
    \
    -- see if user wanted 'any' or 'all' supported\
    if dcsCommon.arrayContainsString(carriers, \"any\") then \
        return true \
    end \
    \
    if dcsCommon.arrayContainsString(carriers, \"all\") then \
        return true \
    end \
    \
    return false\
end\
\
function dcsCommon.isTroopCarrier(theUnit, carriers)\
    -- return true if conf can carry troups\
    if not theUnit then return false end \
    local uType = theUnit:getTypeName()\
    return dcsCommon.isTroopCarrierType(uType, carriers) \
end\
\
function dcsCommon.isPlayerUnit(theUnit)\
    -- new patch. simply check if getPlayerName returns something\
    if not theUnit then return false end \
    if not Unit.isExist(theUnit) then return end \
    if not theUnit.getPlayerName then return false end -- map/static object \
    local pName = theUnit:getPlayerName()\
    if pName then return true end \
    return false \
end\
\
function dcsCommon.getAllExistingPlayerUnitsRaw()\
    local apu = {}\
    for idx, theSide in pairs(dcsCommon.coalitionSides) do\
        local thePlayers = coalition.getPlayers(theSide) \
        for idy, theUnit in pairs (thePlayers) do \
            if theUnit and theUnit:isExist() then \
                table.insert(apu, theUnit)\
            end\
        end\
    end\
    return apu \
end\
\
function dcsCommon.getUnitAlt(theUnit)\
    if not theUnit then return 0 end\
    if not Unit.isExist(theUnit) then return 0 end -- safer \
    local p = theUnit:getPoint()\
    return p.y \
end\
\
function dcsCommon.getUnitAGL(theUnit)\
    if not theUnit then return 0 end\
    if not Unit.isExist(theUnit) then return 0 end -- safe fix\
    local p = theUnit:getPoint()\
    local alt = p.y \
    local loc = {x = p.x, y = p.z}\
    local landElev = land.getHeight(loc)\
    return alt - landElev\
end \
\
function dcsCommon.getUnitSpeed(theUnit)\
    if not theUnit then return 0 end\
    if not Unit.isExist(theUnit) then return 0 end \
    local v = theUnit:getVelocity()\
    return dcsCommon.mag(v.x, v.y, v.z)\
end\
\
-- closing velocity of u1 and u2, seen from u1\
function dcsCommon.getClosingVelocity(u1, u2)\
    if not u1 then return 0 end \
    if not u2 then return 0 end \
    if not u1:isExist() then return 0 end \
    if not u2:isExist() then return 0 end \
    local v1 = u1:getVelocity()\
    local v2 = u2:getVelocity()\
    local dV = dcsCommon.vSub(v1,v2)\
    local a = u1:getPoint()\
    local b = u2:getPoint() \
    local aMinusB = dcsCommon.vSub(a,b) -- vector from u2 to u1\
    local abMag = dcsCommon.vMag(aMinusB) -- distance u1 to u2 \
    if abMag < .0001 then return 0 end \
    -- project deltaV onto vector from u2 to u1 \
    local vClose = dcsCommon.dot(dV, aMinusB) / abMag \
    return vClose \
end\
\
function dcsCommon.getGroupAvgSpeed(theGroup)\
    if not theGroup then return 0 end \
    if not dcsCommon.isGroupAlive(theGroup) then return 0 end \
    local totalSpeed = 0\
    local cnt = 0 \
    local livingUnits = theGroup:getUnits()\
    for idx, theUnit in pairs(livingUnits) do \
        cnt = cnt + 1\
        totalSpeed = totalSpeed + dcsCommon.getUnitSpeed(theUnit)\
    end \
    if cnt == 0 then return 0 end \
    return totalSpeed / cnt \
end\
 \
function dcsCommon.getGroupMaxSpeed(theGroup)\
    if not theGroup then return 0 end \
    if not dcsCommon.isGroupAlive(theGroup) then return 0 end \
    local maxSpeed = 0\
    local livingUnits = theGroup:getUnits()\
    for idx, theUnit in pairs(livingUnits) do \
        currSpeed = dcsCommon.getUnitSpeed(theUnit)\
        if currSpeed > maxSpeed then maxSpeed = currSpeed end \
    end \
    return maxSpeed\
end \
\
function dcsCommon.getUnitHeading(theUnit)\
    if not theUnit then return 0 end \
    if not theUnit:isExist() then return 0 end \
    local pos = theUnit:getPosition() -- returns three vectors, p is location\
\
    local heading = math.atan2(pos.x.z, pos.x.x)\
    -- make sure positive only, add 360 degrees\
    if heading < 0 then\
        heading = heading + 2 * math.pi    -- put heading in range of 0 to 2*pi\
    end\
    return heading \
end\
\
function dcsCommon.getUnitHeadingDegrees(theUnit)\
    local heading = dcsCommon.getUnitHeading(theUnit)\
    return heading * 57.2958 -- 180 / math.pi \
end\
\
function dcsCommon.typeIsInfantry(theType)\
    local isInfantry =  \
                dcsCommon.containsString(theType, \"infantry\", false) or \
                dcsCommon.containsString(theType, \"paratrooper\", false) or\
                dcsCommon.containsString(theType, \"stinger\", false) or\
                dcsCommon.containsString(theType, \"manpad\", false) or\
                dcsCommon.containsString(theType, \"soldier\", false) or \
                dcsCommon.containsString(theType, \"SA-18 Igla\", false)\
    return isInfantry\
end\
\
function dcsCommon.unitIsInfantry(theUnit)\
    if not theUnit then return false end \
    if not theUnit:isExist() then return end\
    local theType = theUnit:getTypeName()\
--[[--\
    local isInfantry =  \
                dcsCommon.containsString(theType, \"infantry\", false) or \
                dcsCommon.containsString(theType, \"paratrooper\", false) or\
                dcsCommon.containsString(theType, \"stinger\", false) or\
                dcsCommon.containsString(theType, \"manpad\", false) or\
                dcsCommon.containsString(theType, \"soldier\", false) or \
                dcsCommon.containsString(theType, \"SA-18 Igla\", false)\
    return isInfantry\
--]]--\
    return dcsCommon.typeIsInfantry(theType)\
end\
\
function dcsCommon.coalition2county(inCoalition)\
    -- simply return UN troops for 0 neutral,\
    -- joint red for 1  red\
    -- joint blue for 2 blue \
    if inCoalition == 1 then return 81 end -- cjtf red\
    if inCoalition == 2 then return 80 end -- blue \
    if type(inCoalition) == \"string\" then \
            inCoalition = inCoalition:lower()\
            if inCoalition == \"red\" then return 81 end\
            if inCoalition == \"blue\" then return 80 end\
    end\
        \
    trigger.action.outText(\"+++dcsC: coalition2county in (\" .. inCoalition .. \") converts to UN (82)!\", 30)\
    return 82 -- UN \
    \
end\
\
function dcsCommon.latLon2Text(lat, lon)\
    -- inspired by mist, thanks Grimes!\
    -- returns two strings: lat and lon \
    \
    -- determine hemispheres by sign\
    local latHemi, lonHemi\
    if lat > 0 then latHemi = 'N' else latHemi = 'S' end\
    if lon > 0 then lonHemi = 'E' else lonHemi = 'W' end\
\
    -- remove sign since we have hemi\
    lat = math.abs(lat)\
    lon = math.abs(lon)\
\
    -- calc deg / mins \
    local latDeg = math.floor(lat)\
    local latMin = (lat - latDeg) * 60\
    local lonDeg = math.floor(lon)\
    local lonMin = (lon - lonDeg) * 60\
\
    -- calc seconds \
    local rawLatMin = latMin\
    latMin = math.floor(latMin)\
    local latSec = (rawLatMin - latMin) * 60\
    local rawLonMin = lonMin\
    lonMin = math.floor(lonMin)\
    local lonSec = (rawLonMin - lonMin) * 60\
\
    -- correct for rounding errors \
    if latSec >= 60 then\
        latSec = latSec - 60\
        latMin = latMin + 1\
    end\
    if lonSec >= 60 then\
        lonSec = lonSec - 60\
        lonMin = lonMin + 1\
    end\
\
    -- prepare string output \
    local secFrmtStr = '%06.3f'\
    local lat = string.format('%02d', latDeg) .. '°' .. string.format('%02d', latMin) .. \"'\" .. string.format(secFrmtStr, latSec) .. '\"' .. latHemi\
    local lon = string.format('%02d', lonDeg) .. '°' .. string.format('%02d', lonMin) .. \"'\" .. string.format(secFrmtStr, lonSec) .. '\"' .. lonHemi\
    return lat, lon  \
end\
\
-- get mission name. If mission file name without \".miz\"\
function dcsCommon.getMissionName()\
    local mn = net.dostring_in(\"gui\", \"return DCS.getMissionName()\")\
    return mn\
end\
\
function dcsCommon.flagArrayFromString(inString, verbose)\
    if not verbose then verbose = false end \
    \
    if verbose then \
        trigger.action.outText(\"+++flagArray: processing <\" .. inString .. \">\", 30)\
    end \
\
    if string.len(inString) < 1 then \
        trigger.action.outText(\"+++flagArray: empty flags\", 30)\
        return {} \
    end\
    \
    \
    local flags = {}\
    local rawElements = dcsCommon.splitString(inString, \",\")\
    -- go over all elements \
    for idx, anElement in pairs(rawElements) do \
        anElement = dcsCommon.trim(anElement)\
        if dcsCommon.stringStartsWithDigit(anElement) and  dcsCommon.containsString(anElement, \"-\") then \
            -- interpret this as a range\
            local theRange = dcsCommon.splitString(anElement, \"-\")\
            local lowerBound = theRange[1]\
            lowerBound = tonumber(lowerBound)\
            local upperBound = theRange[2]\
            upperBound = tonumber(upperBound)\
            if lowerBound and upperBound then\
                -- swap if wrong order\
                if lowerBound > upperBound then \
                    local temp = upperBound\
                    upperBound = lowerBound\
                    lowerBound = temp \
                end\
                -- now add add numbers to flags\
                for f=lowerBound, upperBound do \
                    table.insert(flags, f)\
\
                end\
            else\
                -- bounds illegal\
                trigger.action.outText(\"+++flagArray: ignored range <\" .. anElement .. \"> (range)\", 30)\
            end\
        else\
            -- single number\
            local f = dcsCommon.trim(anElement) -- DML flag upgrade: accept strings tonumber(anElement)\
            if f then \
                table.insert(flags, f)\
\
            else \
                trigger.action.outText(\"+++flagArray: ignored element <\" .. anElement .. \"> (single)\", 30)\
            end\
        end\
    end\
    if verbose then \
        trigger.action.outText(\"+++flagArray: <\" .. #flags .. \"> flags total\", 30)\
    end \
    return flags\
end\
\
function dcsCommon.rangeArrayFromString(inString, verbose)\
    if not verbose then verbose = false end \
    \
    if verbose then \
        trigger.action.outText(\"+++rangeArray: processing <\" .. inString .. \">\", 30)\
    end \
\
    if string.len(inString) < 1 then \
        trigger.action.outText(\"+++rangeArray: empty ranges\", 30)\
        return {} \
    end\
    \
    local ranges = {}\
    local rawElements = dcsCommon.splitString(inString, \",\")\
    -- go over all elements \
    for idx, anElement in pairs(rawElements) do \
        anElement = dcsCommon.trim(anElement)\
        local outRange = {}\
        if dcsCommon.stringStartsWithDigit(anElement) and  dcsCommon.containsString(anElement, \"-\") then \
            -- interpret this as a range\
            local theRange = dcsCommon.splitString(anElement, \"-\")\
            local lowerBound = theRange[1]\
            lowerBound = tonumber(lowerBound)\
            local upperBound = theRange[2]\
            upperBound = tonumber(upperBound)\
            if lowerBound and upperBound then\
                -- swap if wrong order\
                if lowerBound > upperBound then \
                    local temp = upperBound\
                    upperBound = lowerBound\
                    lowerBound = temp \
                end\
                -- now add to ranges\
                outRange[1] = lowerBound\
                outRange[2] = upperBound\
                table.insert(ranges, outRange)\
                if verbose then \
                    trigger.action.outText(\"+++rangeArray: new range <\" .. lowerBound .. \"> to <\" .. upperBound .. \">\", 30)\
                end\
            else\
                -- bounds illegal\
                trigger.action.outText(\"+++rangeArray: ignored range <\" .. anElement .. \"> (range)\", 30)\
            end\
        else\
            -- single number\
            local f = dcsCommon.trim(anElement) \
            f = tonumber(f)\
            if f then \
                outRange[1] = f\
                outRange[2] = f\
                table.insert(ranges, outRange)\
                if verbose then \
                    trigger.action.outText(\"+++rangeArray: new (single-val) range <\" .. f .. \"> to <\" .. f .. \">\", 30)\
                end\
            else \
                trigger.action.outText(\"+++rangeArray: ignored element <\" .. anElement .. \"> (single)\", 30)\
            end\
        end\
    end\
    if verbose then \
        trigger.action.outText(\"+++rangeArray: <\" .. #ranges .. \"> ranges total\", 30)\
    end \
    return ranges\
end\
\
function dcsCommon.incFlag(flagName)\
    local v = trigger.misc.getUserFlag(flagName)\
    trigger.action.setUserFlag(flagName, v + 1)\
end\
\
function dcsCommon.decFlag(flagName)\
    local v = trigger.misc.getUserFlag(flagName)\
    trigger.action.setUserFlag(flagName, v - 1)\
end\
\
function dcsCommon.objectHandler(theObject, theCollector)\
    table.insert(theCollector, theObject)\
    return true \
end\
\
function dcsCommon.getObjectsForCatAtPointWithRadius(aCat, thePoint, theRadius)\
    if not aCat then aCat = Object.Category.UNIT end \
    local p = {x=thePoint.x, y=thePoint.y, z=thePoint.z}\
    local collector = {}\
    \
    -- now build the search argument \
    local args = {\
            id = world.VolumeType.SPHERE,\
            params = {\
                point = p,\
                radius = theRadius\
            }\
        }\
    \
    -- now call search\
    world.searchObjects(aCat, args, dcsCommon.objectHandler, collector)\
    return collector\
end\
\
function dcsCommon.getSceneryObjectsInZone(theZone) -- DCS ZONE!!! \
    local aCat = 5 -- scenery\
    -- WARNING: WE ARE USING DCS ZONES, NOT CFX!!!\
    local p = {x=theZone.x, y=0, z=theZone.y}\
    local lp = {x = p.x, y = p.z}\
    p.y = land.getHeight(lp)\
    local collector = {}\
    \
    -- now build the search argument \
    local args = {\
            id = world.VolumeType.SPHERE,\
            params = {\
                point = p,\
                radius = theZone.radius\
            }\
        }\
    \
    -- now call search\
    world.searchObjects(aCat, args, dcsCommon.objectHandler, collector)\
    return collector\
end\
\
function dcsCommon.getSceneryObjectInZoneByName(theName, theZone) -- DCS ZONE!!!\
    local allObs = dcsCommon.getSceneryObjectsInZone(theZone)\
    for idx, anObject in pairs(allObs) do \
        if tostring(anObject:getName()) == theName then return anObject end \
    end\
    return nil \
end\
\
--\
-- bitwise operators\
--\
function dcsCommon.bitAND32(a, b)\
    if not a then a = 0 end \
    if not b then b = 0 end \
    local z = 0\
    local e = 1\
    for i = 0, 31 do \
        local a1 = a % 2 -- 0 or 1\
        local b1 = b % 2 -- 0 or 1\
        if a1 == 1 and b1 == 1 then \
            a = a - 1 -- remove bit \
            b = b - 1 \
            z = z + e\
        else\
            if a1 == 1 then a = a - 1 end -- remove bit \
            if b1 == 1 then b = b - 1 end \
        end\
        a = a / 2 -- shift right\
        b = b / 2        \
        e = e * 2 -- raise e by 1 \
    end\
    return z\
end\
\
function dcsCommon.num2bin(a)\
    if not a then a = 0 end \
    local z = \"\"\
    for i = 0, 31 do \
        local a1 = a % 2 -- 0 or 1\
        if a1 == 1 then \
            a = a - 1 -- remove bit \
            z = \"1\"..z\
        else\
            z = \"0\"..z\
        end\
        a = a / 2 -- shift right\
    end\
    return z\
end\
\
function dcsCommon.LSR(a, num)\
    if not a then a = 0 end \
    if not num then num = 16 end \
    for i = 1, num do \
        local a1 = a % 2 -- 0 or 1\
        if a1 == 1 then \
            a = a - 1 -- remove bit \
        end\
        a = a / 2 -- shift right\
    end\
    return a\
end\
\
--\
-- string wildcards \
--\
function dcsCommon.processStringWildcards(inMsg)\
    -- Replace STATIC bits of message like CR and zone name \
    if not inMsg then return \"<nil inMsg>\" end\
    local formerType = type(inMsg)\
    if formerType ~= \"string\" then inMsg = tostring(inMsg) end  \
    if not inMsg then inMsg = \"<inMsg is incompatible type \" .. formerType .. \">\" end \
    local outMsg = \"\"\
    -- replace line feeds \
    outMsg = inMsg:gsub(\"<n>\", \"\\n\")\
\
    return outMsg \
end\
\
--\
-- phonetic alphabet \
--\
dcsCommon.alphabet = {\
    a = \"alpha\",\
    b = \"bravo\",\
    c = \"charlie\",\
    d = \"delta\",\
    e = \"echo\",\
    f = \"foxtrot\",\
    g = \"golf\",\
    h = \"hotel\",\
    i = \"india\",\
    j = \"juliet\",\
    k = \"kilo\",\
    l = \"lima\",\
    m = \"mike\",\
    n = \"november\",\
    o = \"oscar\",\
    p = \"papa\",\
    q = \"quebec\",\
    r = \"romeo\",\
    s = \"sierra\",\
    t = \"tango\",\
    u = \"uniform\",\
    v = \"victor\",\
    w = \"whiskey\",\
    x = \"x-ray\",\
    y = \"yankee\",\
    z = \"zulu\",\
[\"0\"] = \"zero\",\
[\"1\"] = \"wun\",\
[\"2\"] = \"too\",\
[\"3\"] = \"tree\",\
[\"4\"] = \"fower\",\
[\"5\"] = \"fife\" ,\
[\"6\"] = \"six\",\
[\"7\"] = \"seven\",\
[\"8\"] = \"att\",\
[\"9\"] = \"niner\",\
[\" \"] = \"break\",\
}\
\
function dcsCommon.letter(inChar)\
    local theChar = \"\"\
    if type(inChar == \"string\") then \
        if #inChar < 1 then return \"#ERROR0#\" end\
        inChar = string.lower(inChar)\
        theChar = string.sub(inChar, 1, 1)\
    elseif type(inChar == \"number\") then \
        if inChar > 255 then return \"#ERROR>#\" end \
        if inChar < 0 then return \"#ERROR<#\" end \
        theChar = char(inChar)\
    else \
        return \"#ERRORT#\"\
    end\
--    trigger.action.outText(\"doing <\" .. theChar .. \">\", 30)\
    local a = dcsCommon.alphabet[theChar]\
    if a == nil then a = \"#ERROR?#\" end \
    return a \
end\
\
function dcsCommon.spellString(inString)\
    local res = \"\"\
    local first = true \
    for i = 1, #inString do\
        local c = inString:sub(i,i)\
        if first then \
            res = dcsCommon.letter(c)\
            first = false \
        else \
            res = res .. \" \" .. dcsCommon.letter(c)\
        end\
    end\
    return res \
end\
\
--\
-- iterators\
--\
-- iteratePlayers - call callback for all player units\
-- callback is of signature callback(playerUnit)\
--\
\
function dcsCommon.iteratePlayers(callBack)\
    local factions = {0, 1, 2}\
    for idx, theFaction in pairs(factions) do \
        local players = coalition.getPlayers(theFaction)\
        for idy, theUnit in pairs(players) do \
            callBack(theUnit)\
        end\
    end\
end\
\
--\
-- SEMAPHORES\
--\
dcsCommon.semaphores = {}\
\
-- replacement for trigger.misc.getUserFlag\
function dcsCommon.getUserFlag(flagName)\
    if dcsCommon.semaphores[flagName] then \
        return dcsCommon.semaphores[flagName]\
    end\
    \
    return trigger.misc.getUserFlag(flagName)\
end\
\
-- replacement for trigger.action.setUserFlag \
function dcsCommon.setUserFlag(flagName, theValue)\
    -- not yet connected: semaphores\
    \
    -- forget semaphore content if new value is old-school \
    if type(theValue) == \"number\" then \
        dcsCommon.semaphores[theValue] = nil --return to old-school \
    end\
    trigger.action.setUserFlag(flagName, theValue)\
end\
\
--\
--\
-- INIT\
--\
--\
    -- init any variables, tables etc that the lib requires internally\
    function dcsCommon.init()\
        cbID = 0\
        -- create ID tables\
        dcsCommon.collectMissionIDs()\
        \
        --dcsCommon.uuIdent = 0\
        if (dcsCommon.verbose) or true then\
          trigger.action.outText(\"dcsCommon v\" .. dcsCommon.version .. \" loaded\", 10)\
        end\
    end\
\
    \
-- do init. \
dcsCommon.init()\
\
",
                    ["predicate"] = "a_do_script",
                }, -- end of [1]
                [2] = 
                {
                    ["text"] = "cfxZones = {}\
cfxZones.version = \"3.0.9\"\
\
-- cf/x zone management module\
-- reads dcs zones and makes them accessible and mutable \
-- by scripting.\
--\
-- Copyright (c) 2021, 2022 by Christian Franz and cf/x AG\
--\
\
--[[-- VERSION HISTORY\
 - 2.2.4 - getCoalitionFromZoneProperty\
         - getStringFromZoneProperty\
 - 2.2.5 - createGroundUnitsInZoneForCoalition corrected coalition --> country \
 - 2.2.6 - getVectorFromZoneProperty(theZone, theProperty, defaultVal)\
 - 2.2.7 - allow 'yes' as 'true' for boolean attribute \
 - 2.2.8 - getBoolFromZoneProperty supports default \
         - cfxZones.hasProperty\
 - 2.3.0 - property names are case insensitive \
 - 2.3.1 - getCoalitionFromZoneProperty allows 0, 1, 2 also\
 - 2.4.0 - all zones look for owner attribute, and set it to 0 (neutral) if not present \
 - 2.4.1 - getBoolFromZoneProperty upgraded by expected bool \
         - markZoneWithSmoke raised by 3 meters\
 - 2.4.2 - getClosestZone also returns delta \
 - 2.4.3 - getCoalitionFromZoneProperty() accepts 'all' as neutral \
           createUniqueZoneName()\
           getStringFromZoneProperty returns default if property value = \"\"\
           corrected bug in addZoneToManagedZones\
 - 2.4.4 - getPoint(aZone) returns uip-to-date pos for linked and normal zones\
         - linkUnit can use \"useOffset\" property to keep relative position\
 - 2.4.5 - updated various methods to support getPoint when referencing \
           zone.point  \
 - 2.4.6 - corrected spelling in markZoneWithSmoke\
 - 2.4.7 - copy reference to dcs zone into cfx zone \
 - 2.4.8 - getAllZoneProperties\
 - 2.4.9 - createSimpleZone no longer requires location \
         - parse dcs adds empty .properties = {} if none tehre \
         - createCircleZone adds empty properties \
         - createPolyZone adds empty properties \
 - 2.4.10 - pickRandomZoneFrom now defaults to all cfxZones.zones\
          - getBoolFromZoneProperty also recognizes 0, 1\
          - removed autostart\
 - 2.4.11 - removed typo in get closest zone \
 - 2.4.12 - getStringFromZoneProperty\
 - 2.5.0  - harden getZoneProperty and all getPropertyXXXX\
 - 2.5.1  - markZoneWithSmoke supports alt attribute \
 - 2.5.2  - getPoint also writes through to zone itself for optimization\
          - new method getPositiveRangeFromZoneProperty(theZone, theProperty, default)\
 - 2.5.3  - new getAllGroupsInZone()\
 - 2.5.4  - cleaned up getZoneProperty break on no properties \
          - extractPropertyFromDCS trims key and property \
 - 2.5.5  - pollFlag() centralized for banging \
          - allStaticsInZone\
 - 2.5.6  - flag accessor setFlagValue(), getFlagValue()  \
          - pollFlag supports theZone as final parameter\
          - randomDelayFromPositiveRange\
          - isMEFlag\
 - 2.5.7  - pollFlag supports dml flags\
 - 2.5.8  - flagArrayFromString\
          - getFlagNumber invokes tonumber() before returning result \
 - 2.5.9  - removed pass-back flag in getPoint() \
 - 2.6.0  - testZoneFlag() method based flag testing\
 - 2.6.1  - Watchflag parsing of zone condition for number-named flags\
          - case insensitive\
          - verbose for zone-local accepted (but not acted upon)\
          - hasProperty now offers active information when looking for '*?' and '*!'\
 - 2.7.0  - doPollFlag - fully support multiple flags per bang!\
 - 2.7.1  - setFlagValueMult()\
 - 2.7.2  - '261 repair'\
 - 2.7.3  - testZoneFlag returns mathodResult, lastVal\
          - evalFlagMethodImmediate()\
 - 2.7.4  - doPollFlag supports immediate number setting \
 - 2.7.5  - more QoL checks when mixing up ? and ! for attributes\
 - 2.7.6  - trim for getBoolFromZoneProperty and getStringFromZoneProperty\
 - 2.7.7  - randomInRange()\
          - show number of zones \
 - 2.7.8  - inc method now triggers if curr value > last value \
          - dec method noew triggers when curr value < last value \
          - testFlagByMethodForZone supports lohi, hilo transitions \
          - doPollFlag supports 'pulse'\
          - pulseFlag\
          - unpulse \
- 2.7.9   - getFlagValue QoL for <none>\
          - setFlagValue QoL for <none>\
- 2.8.0      - new allGroupNamesInZone()\
- 2.8.1   - new zonesLinkedToUnit()  \
- 2.8.2   - flagArrayFromString trims elements before range check \
- 2.8.3   - new verifyMethod()\
          - changed extractPropertyFromDCS() to also match attributes with blanks like \"the Attr\" to \"theAttr\"\
          - new expandFlagName()\
- 2.8.4   - fixed bug in setFlagValue()\
- 2.8.5   - createGroundUnitsInZoneForCoalition() now always passes back a copy of the group data \
          - data also contains cty = country and cat = category for easy spawn\
          - getFlagValue additional zone name guards \
- 2.8.6   - fix in getFlagValue for missing delay \
- 2.8.7   - update isPointInsideZone(thePoint, theZone, radiusIncrease) - new radiusIncrease\
          - isPointInsideZone() returns delta as well\
- 2.9.0   - linked zones can useOffset and useHeading \
          - getPoint update \
          - pointInZone understands useOrig\
          - allStaticsInZone supports useOrig \
          - dPhi for zones with useHeading \
          - uHdg for zones with useHading, contains linked unit's original heading\
          - Late-linking implemented:\
          - linkUnit works for late-activating units \
          - linkUnit now also works for player / clients, dynamic (re-)linking \
          - linkUnit uses zone's origin for all calculations \
- 2.9.1   - new evalRemainder()\
          - pollFlag supports +/- for immediate numbers, flags, number flags in parantheses\
          - stronger guards in hasProperty \
- 2.9.2   - new createRandomPointInPolyZone()\
          - createRandomZoneInZone uses createRandomPointInPolyZone\
          - new createRandomPointInZone()\
          - new randomPointInZone()\
- 3.0.0   - support for DCS 2.8 linkUnit attribute, integration with \
            linedUnit and warning.\
          - initZoneVerbosity()\
- 3.0.1   - updateMovingZones() better tracks linked units by name\
- 3.0.2   - maxRadius for all zones, only differs from radius in polyZones \
          - re-factoring zone-base string processing from messenger module\
          - new processStringWildcards() that does almost all that messenger can \
- 3.0.3   - new getLinkedUnit()\
- 3.0.4   - new createRandomPointOnZoneBoundary()\
- 3.0.5   - getPositiveRangeFromZoneProperty() now also supports upper bound (optional)\
- 3.0.6   - new createSimplePolyZone()\
          - new createSimpleQuadZone()\
- 3.0.7   - getPoint() can also get land y when passing true as second param\
- 3.0.8   - new cfxZones.pointInOneOfZones(thePoint, zoneArray, useOrig) \
- 3.0.9   - new getFlareColorStringFromZoneProperty()\
\
--]]--\
cfxZones.verbose = false\
cfxZones.caseSensitiveProperties = false -- set to true to make property names case sensitive \
cfxZones.ups = 1 -- updates per second. updates moving zones\
\
cfxZones.zones = {} -- these are the zone as retrieved from the mission.\
                    -- ALWAYS USE THESE, NEVER DCS's ZONES!!!!\
\
-- a zone has the following attributes\
-- x, z -- coordinate of center. note they have correct x, 0, z coordinates so no y-->z mapping\
-- radius (zero if quad zone)\
-- isCircle (true if quad zone)\
-- poly the quad coords are in the poly attribute and are a \
-- 1..n, wound counter-clockwise as (currently) in DCS:\
-- lower left, lower right upper left, upper right, all coords are x, 0, z \
-- bounds - contain the AABB coords for the zone: ul (upper left), ur, ll (lower left), lr \
--          for both circle and poly, all (x, 0, z)\
\
-- zones can carry information in their names that can get processed into attributes\
-- use \
-- zones can also carry information in their 'properties' tag that ME allows to \
-- edit. cfxZones provides an easy method to access these properties \
--  - getZoneProperty (returns as string)\
--  - getMinMaxFromZoneProperty\
--  - getBoolFromZoneProperty\
--  - getNumberFromZoneProperty\
\
\
-- SUPPORTED PROPERTIES\
-- - \"linkedUnit\" - zone moves with unit of that name. must be exact match\
--   can be combined with other attributes that extend (e.g. scar manager and\
--   limited pilots/airframes \
--\
\
--\
-- readZonesFromDCS is executed exactly once at the beginning\
-- from then on, use only the cfxZones.zones table \
-- WARNING: cfxZones is NOT case-sensitive. All zone names are \
-- indexed by upper case. If you have two zones with same name but \
-- different case, one will be replaced\
--\
\
function cfxZones.readFromDCS(clearfirst)\
    if (clearfirst) then\
        cfxZones.zones = {}\
    end\
    -- not all missions have triggers or zones\
    if not env.mission.triggers then \
        if cfxZones.verbose then \
            trigger.action.outText(\"cf/x zones: no env.triggers defined\", 10)\
        end\
        return\
    end\
    \
    if not env.mission.triggers.zones then \
        if cfxZones.verbose then \
            trigger.action.outText(\"cf/x zones: no zones defined\", 10)\
        end\
        return;\
    end\
\
    -- we only retrieve the data we need. At this point it is name, location and radius\
    -- and put this in our own little  structure. we also convert to all upper case name for index\
    -- and assume that the name may also carry meaning, e.g. 'LZ:' defines a landing zone\
    -- so we can quickly create other sets from this\
    -- zone object. DCS 2.7 introduced quads, so this is supported as well\
    --   name - name in upper case\
    --   isCircle - true if circular zone \
    --   isPoly - true if zone is defined by convex polygon, e.g. quad \
    --   point - vec3 (x 0 z) - zone's in-world center, used to place the coordinate\
    --   radius - number, zero when quad\
    --   bounds - aabb with attributes ul, ur, ll, lr (upper left .. lower right) as (x, 0, z)\
    --   poly - array 1..n of poly points, wound counter-clockwise \
    \
    for i, dcsZone in pairs(env.mission.triggers.zones) do\
        if type(dcsZone) == 'table' then -- hint taken from MIST: verify type when reading from dcs\
                                         -- dcs data is like a box of chocolates...\
            local newZone = {}\
            -- name, converted to upper is used only for indexing\
            -- the original name remains untouched\
            newZone.dcsZone = dcsZone\
            newZone.name = dcsZone.name\
            newZone.isCircle = false\
            newZone.isPoly = false\
            newZone.radius = 0\
            newZone.poly = {}\
            newZone.bounds = {}\
            newZone.properties = {} -- dcs has this too, copy if present\
            if dcsZone.properties then \
                newZone.properties = dcsZone.properties \
            else\
                newZone.properties = {}\
            end -- WARNING: REF COPY. May need to clone \
            \
            local upperName = newZone.name:upper()\
            \
            -- location as 'point'\
            -- WARNING: zones locs are 2D (x,y) pairs, while y in DCS is altitude.\
            --          so we need to change (x,y) into (x, 0, z). Since Zones have no\
            --          altitude (they are an infinite cylinder) this works. Remember to \
            --          drop y from zone calculations to see if inside. \
            -- WARNING: ME linked zones have a relative x any y \
            --          to the linked unit \
            if dcsZone.linkUnit then \
                -- calculate the zone's real position by accessing the unit's MX data \
                -- as precached by dcsCommon\
                local ux, uy = dcsCommon.getUnitStartPosByID(dcsZone.linkUnit)\
                newZone.point = cfxZones.createPoint(ux + dcsZone.x, 0, uy + dcsZone.y)\
                newZone.dcsOrigin = cfxZones.createPoint(ux + dcsZone.x, 0, uy + dcsZone.y)\
            else \
                newZone.point = cfxZones.createPoint(dcsZone.x, 0, dcsZone.y)\
                newZone.dcsOrigin = cfxZones.createPoint(dcsZone.x, 0, dcsZone.y)\
            end\
\
            -- start type processing. if zone.type exists, we have a mission \
            -- created with 2.7 or above, else earlier \
            local zoneType = 0\
            if (dcsZone.type) then \
                zoneType = dcsZone.type \
            end\
            \
            if zoneType == 0 then \
                -- circular zone \
                newZone.isCircle = true \
                newZone.radius = dcsZone.radius\
                newZone.maxRadius = newZone.radius -- same for circular\
    \
            elseif zoneType == 2 then\
                -- polyZone\
                newZone.isPoly = true \
                newZone.radius = dcsZone.radius -- radius is still written in DCS, may change later. The radius has no meaning and is the last radius written before zone changed to poly.\
                -- note that newZone.point is only inside the tone for \
                -- convex polys, and DML only correctly works with convex polys\
                -- now transfer all point in the poly\
                -- note: DCS in 2.7 misspells vertices as 'verticies'\
                -- correct for this \
                newZone.maxRadius = 0\
                local verts = {}\
                if dcsZone.verticies then verts = dcsZone.verticies \
                else \
                    -- in later versions, this was corrected\
                    verts = dcsZone.vertices -- see if this is ever called\
                end\
                \
                for v=1, #verts do\
                    local dcsPoint = verts[v]\
                    local polyPoint = cfxZones.createPointFromDCSPoint(dcsPoint) -- (x, y) --> (x, 0, y-->z)\
                    newZone.poly[v] = polyPoint\
                    -- measure distance from zone's point, and store maxRadius \
                    -- dcs always saves a point with the poly zone \
                    local dist = dcsCommon.dist(newZone.point, polyPoint)\
                    if dist > newZone.maxRadius then newZone.maxRadius = dist end \
                end\
            else \
                \
                trigger.action.outText(\"cf/x zones: malformed zone #\" .. i .. \" unknown type \" .. zoneType, 10)\
            end\
            \
\
            -- calculate bounds\
            cfxZones.calculateZoneBounds(newZone) \
\
            -- add to my table\
            cfxZones.zones[upperName] = newZone -- WARNING: UPPER ZONE!!!\
            --trigger.action.outText(\"znd: procced \" .. newZone.name .. \" with radius \" .. newZone.radius, 30)\
        else\
            if cfxZones.verbose then \
                trigger.action.outText(\"cf/x zones: malformed zone #\" .. i .. \" dropped\", 10)\
            end\
        end -- else var not a table\
        \
    end -- for all zones kvp\
end -- readFromDCS\
\
function cfxZones.calculateZoneBounds(theZone)\
    if not (theZone) then return \
    end\
    \
    local bounds = theZone.bounds -- copy ref!\
    \
    if theZone.isCircle then \
        -- aabb are easy: center +/- radius \
        local center = theZone.point\
        local radius = theZone.radius \
        -- dcs uses z+ is down on map\
        -- upper left is center - radius \
        bounds.ul = cfxZones.createPoint(center.x - radius, 0, center.z - radius)\
        bounds.ur = cfxZones.createPoint(center.x + radius, 0, center.z - radius)\
        bounds.ll = cfxZones.createPoint(center.x - radius, 0, center.z + radius)\
        bounds.lr = cfxZones.createPoint(center.x + radius, 0, center.z + radius)\
        \
    elseif theZone.isPoly then\
        local poly = theZone.poly -- ref copy!\
        -- create the four points\
        local ll = cfxZones.createPointFromPoint(poly[1])\
        local lr = cfxZones.createPointFromPoint(poly[1])\
        local ul = cfxZones.createPointFromPoint(poly[1])\
        local ur = cfxZones.createPointFromPoint(poly[1])\
        \
        local pRad = dcsCommon.dist(theZone.point, poly[1]) -- rRad is radius for polygon from theZone.point \
        \
        -- now iterate through all points and adjust bounds accordingly \
        for v=2, #poly do \
            local vertex = poly[v]\
            if (vertex.x < ll.x) then ll.x = vertex.x; ul.x = vertex.x end \
            if (vertex.x > lr.x) then lr.x = vertex.x; ur.x = vertex.x end \
            if (vertex.z < ul.z) then ul.z = vertex.z; ur.z = vertex.z end\
            if (vertex.z > ll.z) then ll.z = vertex.z; lr.z = vertex.z end \
            local dp = dcsCommon.dist(theZone.point, vertex)\
            if dp > pRad then pRad = dp end -- find largst distance to vertex\
        end\
        \
        -- now keep the new point references\
        -- and store them in the zone's bounds\
        bounds.ll = ll\
        bounds.lr = lr\
        bounds.ul = ul\
        bounds.ur = ur \
        -- store pRad \
        theZone.pRad = pRad -- not sure we'll ever need that, but at least we have it\
--        trigger.action.outText(\"+++Zones: poly zone <\" .. theZone.name .. \"> has pRad = \" .. pRad, 30) -- remember to remove me \
    else \
        -- huston, we have a problem\
        if cfxZones.verbose then \
            trigger.action.outText(\"cf/x zones: calc bounds: zone \" .. theZone.name .. \" has unknown type\", 30)\
        end\
    end\
    \
end\
\
function cfxZones.createPoint(x, y, z)\
    local newPoint = {}\
    newPoint.x = x\
    newPoint.y = y\
    newPoint.z = z \
    return newPoint\
end\
\
function cfxZones.copyPoint(inPoint) \
    local newPoint = {}\
    newPoint.x = inPoint.x\
    newPoint.y = inPoint.y\
    -- handle xz only \
    if inPoint.z then \
        newPoint.z = inPoint.z \
    else \
        newPoint.z = inPoint.y \
    end\
    return newPoint    \
end\
\
function cfxZones.createHeightCorrectedPoint(inPoint) -- this should be in dcsCommon\
    local cP = cfxZones.createPoint(inPoint.x, land.getHeight({x=inPoint.x, y=inPoint.z}),inPoint.z)\
    return cP\
end\
\
function cfxZones.getHeightCorrectedZonePoint(theZone)\
    return cfxZones.createHeightCorrectedPoint(theZone.point)\
end\
\
function cfxZones.createPointFromPoint(inPoint)\
    return cfxZones.copyPoint(inPoint)\
end\
\
function cfxZones.createPointFromDCSPoint(inPoint) \
    return cfxZones.createPoint(inPoint.x, 0, inPoint.y)\
end\
\
\
function cfxZones.createRandomPointInsideBounds(bounds)\
    -- warning: bounds do not move woth zone! may have to be updated\
    local x = math.random(bounds.ll.x, ur.x)\
    local z = math.random(bounds.ll.z, ur.z)\
    return cfxZones.createPoint(x, 0, z)\
end\
\
function cfxZones.createRandomPointOnZoneBoundary(theZone)\
    if not theZone then return nil end \
    if theZone.isPoly then \
        local loc, dx, dy = cfxZones.createRandomPointInPolyZone(theZone, true)\
        return loc, dx, dy \
    else \
        local loc, dx, dy = cfxZones.createRandomPointInCircleZone(theZone, true)\
        return loc, dx, dy \
    end\
end\
\
function cfxZones.createRandomPointInZone(theZone)\
    if not theZone then return nil end \
    if theZone.isPoly then \
        local loc, dx, dy = cfxZones.createRandomPointInPolyZone(theZone)\
        return loc, dx, dy \
    else \
        local loc, dx, dy = cfxZones.createRandomPointInCircleZone(theZone)\
        return loc, dx, dy \
    end\
end\
\
function cfxZones.randomPointInZone(theZone)\
    local loc, dx, dy =  cfxZones.createRandomPointInZone(theZone)\
    return loc, dx, dy \
end\
\
function cfxZones.createRandomPointInCircleZone(theZone, onEdge)\
    if not theZone.isCircle then \
        trigger.action.outText(\"+++Zones: warning - createRandomPointInCircleZone called for non-circle zone <\" .. theZone.name .. \">\", 30)\
        return {x=theZone.point.x, y=0, z=theZone.point.z}\
    end\
    \
    -- ok, let's first create a random percentage value for the new radius\
    -- now lets get a random degree\
    local degrees = math.random() * 2 * 3.14152 -- radiants. \
    local r = theZone.radius \
    if not onEdge then \
        r = r * math.random()\
    end \
    local p = cfxZones.getPoint(theZone) -- force update of zone if linked\
    local dx = r * math.cos(degrees)\
    local dz = r * math.sin(degrees)\
    local px = p.x + dx -- r * math.cos(degrees)\
    local pz = p.z + dz -- r * math.sin(degrees)\
    return {x=px, y=0, z = pz}, dx, dz -- returns loc and offsets to theZone.point\
end\
\
function cfxZones.createRandomPointInPolyZone(theZone, onEdge)\
    if not theZone.isPoly then \
        trigger.action.outText(\"+++Zones: warning - createRandomPointInPolyZone called for non-poly zone <\" .. theZone.name .. \">\", 30)\
        return cfxZones.createPoint(theZone.point.x, 0, theZone.point.z)\
    end\
    -- force update of all points \
    local p = cfxZones.getPoint(theZone)\
    \
    -- point in convex poly: choose two different lines from that polygon \
    local lineIdxA = dcsCommon.smallRandom(#theZone.poly)\
    repeat lineIdxB = dcsCommon.smallRandom(#theZone.poly) until (lineIdxA ~= lineIdxB)\
    \
    -- we now have two different lines. pick a random point on each. \
    -- we use lerp to pick any point between a and b \
    local a = theZone.poly[lineIdxA]\
    lineIdxA = lineIdxA + 1 -- get next point in poly and wrap around\
    if lineIdxA > #theZone.poly then lineIdxA = 1 end \
    local b = theZone.poly[lineIdxA] \
    local randompercent = math.random()\
    local sourceA = dcsCommon.vLerp (a, b, randompercent)\
    -- if all we want is a point on an edge, we are done \
    if onEdge then \
        local polyPoint = sourceA\
        return polyPoint, polyPoint.x - p.x, polyPoint.z - p.z -- return loc, dx, dz \
    end \
    \
    -- now get point on second line \
    a = theZone.poly[lineIdxB]\
    lineIdxB = lineIdxB + 1 -- get next point in poly and wrap around\
    if lineIdxB > #theZone.poly then lineIdxB = 1 end \
    b = theZone.poly[lineIdxB] \
    randompercent = math.random()\
    local sourceB = dcsCommon.vLerp (a, b, randompercent)\
    \
    -- now take a random point on that line that entirely \
    -- runs through the poly \
    randompercent = math.random()\
    local polyPoint = dcsCommon.vLerp (sourceA, sourceB, randompercent)\
    return polyPoint, polyPoint.x - p.x, polyPoint.z - p.z -- return loc, dx, dz \
end\
\
function cfxZones.addZoneToManagedZones(theZone)\
    local upperName = string.upper(theZone.name) -- newZone.name:upper()\
    cfxZones.zones[upperName] = theZone\
end\
\
function cfxZones.createUniqueZoneName(inName, searchSet)\
    if not inName then return nil end \
    if not searchSet then searchSet = cfxZones.zones end \
    inName = inName:upper()\
    while searchSet[inName] ~= nil do \
        inName = inName .. \"X\"\
    end\
    return inName\
end\
\
function cfxZones.createSimpleZone(name, location, radius, addToManaged)\
    if not radius then radius = 10 end\
    if not addToManaged then addToManaged = false end \
    if not location then \
        location = {}\
    end\
    if not location.x then location.x = 0 end \
    if not location.z then location.z = 0 end \
    \
    local newZone = cfxZones.createCircleZone(name, location.x, location.z, radius)\
    \
    if addToManaged then \
        cfxZones.addZoneToManagedZones(newZone)\
    end\
    return newZone\
end\
\
function cfxZones.createCircleZone(name, x, z, radius) \
    local newZone = {}\
    newZone.isCircle = true\
    newZone.isPoly = false\
    newZone.poly = {}\
    newZone.bounds = {}\
            \
    newZone.name = name\
    newZone.radius = radius\
    newZone.point = cfxZones.createPoint(x, 0, z)\
 \
    -- props \
    newZone.properties = {}\
    \
    -- calculate my bounds\
    cfxZones.calculateZoneBounds(newZone)\
    \
    return newZone\
end\
\
function cfxZones.createSimplePolyZone(name, location, points, addToManaged)\
    if not addToManaged then addToManaged = false end \
    if not location then \
        location = {}\
    end\
    if not location.x then location.x = 0 end \
    if not location.z then location.z = 0 end \
\
    local newZone = cfxZones.createPolyZone(name, points)\
    \
    if addToManaged then \
        cfxZones.addZoneToManagedZones(newZone)\
    end\
    return newZone\
end\
\
function cfxZones.createSimpleQuadZone(name, location, points, addToManaged)\
    if not location then \
        location = {}\
    end\
    if not location.x then location.x = 0 end \
    if not location.z then location.z = 0 end \
        \
    -- synthesize 4 points if they don't exist\
    -- remember: in DCS positive x is up, positive z is right \
    if not points then \
        points = {} \
    end\
    if not points[1] then \
        -- upper left \
        points[1] = {x = location.x-1, y = 0, z = location.z-1}\
    end\
    if not points[2] then \
        -- upper right \
        points[2] = {x = location.x-1, y = 0, z = location.z+1}\
    end\
    if not points[3] then \
        -- lower right \
        points[3] = {x = location.x+1, y = 0, z = location.z+1}\
    end\
    if not points[4] then \
        -- lower left \
        points[4] = {x = location.x+1, y = 0, z = location.z-1}\
    end\
    \
    return cfxZones.createSimplePolyZone(name, location, points, addToManaged)\
end\
\
function cfxZones.createPolyZone(name, poly) -- poly must be array of point type\
local newZone = {}\
    newZone.isCircle = false\
    newZone.isPoly = true\
    newZone.poly = {}\
    newZone.bounds = {}\
            \
    newZone.name = name\
    newZone.radius = 0\
    -- copy poly\
    for v=1, #poly do \
        local theVertex = poly[v] \
        newZone.poly[v] = cfxZones.createPointFromPoint(theVertex) \
    end\
    \
    -- properties \
    newZone.properties = {}\
    \
    cfxZones.calculateZoneBounds(newZone)\
end\
\
\
\
function cfxZones.createRandomZoneInZone(name, inZone, targetRadius, entirelyInside)\
    -- create a new circular zone with center placed inside inZone\
    -- if entirelyInside is false, only the zone's center is guaranteed to be inside\
    -- inZone.\
    -- entirelyInside is not guaranteed for polyzones\
    \
--    trigger.action.outText(\"Zones: creating rZiZ with tr = \" .. targetRadius .. \" for \" .. inZone.name .. \" that as r = \" .. inZone.radius, 10)\
    \
    if inZone.isCircle then \
        local sourceRadius = inZone.radius\
        if entirelyInside and targetRadius > sourceRadius then targetRadius = sourceRadius end\
        if entirelyInside then sourceRadius = sourceRadius - targetRadius end\
    \
        -- ok, let's first create a random percentage value for the new radius\
        local percent = 1 / math.random(100)\
        -- now lets get a random degree\
        local degrees = math.random(360) * 3.14152 / 180 -- ok, it's actually radiants. \
        local r = sourceRadius * percent \
        local x = inZone.point.x + r * math.cos(degrees)\
        local z = inZone.point.z + r * math.sin(degrees)\
        -- construct new zone\
        local newZone = cfxZones.createCircleZone(name, x, z, targetRadius)\
        return newZone\
    \
    elseif inZone.isPoly then \
        -- we have a poly zone. the way we do this is simple:\
        -- generate random x, z with ranges of the bounding box \
        -- until the point falls within the polygon.\
        --[[ replaced by new code \
        \
        local newPoint = {}\
        local emergencyBrake = 0\
        repeat\
            newPoint = cfxZones.createRandomPointInsideBounds(inZone.bounds)\
            emergencyBrake = emergencyBrake + 1\
            if (emergencyBrake > 100) then \
                newPoint = cfxZones.copyPoint(inZone.Point)\
                trigger.action.outText(\"CreateZoneInZone: emergency brake for inZone\" .. inZone.name,  10)\
                break\
            end\
        until cfxZones.isPointInsidePoly(newPoint, inZone.poly)\
        --]]--\
        local newPoint = cfxZones.createRandomPointInPolyZone(inZone)\
        -- construct new zone\
        local newZone = cfxZones.createCircleZone(name, newPoint.x, newPoint.z, targetRadius)\
        return newZone\
        \
    else \
        -- zone type unknown\
        trigger.action.outText(\"CreateZoneInZone: unknown zone type for inZone =\" .. inZone.name ,  10)\
        return nil \
    end\
end\
\
-- polygon inside zone calculations\
\
\
-- isleft returns true if point P is to the left of line AB \
-- by determining the sign (up or down) of the normal vector of \
-- the two vectors PA and PB in the y coordinate. We arbitrarily define\
-- left as being > 0, so right is <= 0. As long as we always use the \
-- same comparison, it does not matter what up or down mean.\
-- this is important because we don't know if dcs always winds quads\
-- the same way, we must simply assume that they are wound as a polygon \
function cfxZones.isLeftXZ(A, B, P)\
    return ((B.x - A.x)*(P.z - A.z) - (B.z - A.z)*(P.x - A.x)) > 0\
end\
\
-- returns true/false for inside\
function cfxZones.isPointInsideQuad(thePoint, A, B, C, D) \
    -- Inside test (only convex polygons): \
    -- point lies on the same side of each quad's vertex AB, BC, CD, DA\
    -- how do we find out which side a point lies on? via the cross product\
    -- see isLeft below\
    \
    -- so all we need to do is make sure all results of isLeft for all\
    -- four sides are the same\
    mustMatch = isLeftXZ(A, B, thePoint) -- all test results must be the same and we are ok\
                                       -- they just must be the same side.\
    if (cfxZones.isLeftXZ(B, C, thePoint ~= mustMatch)) then return false end -- on other side than all before\
    if (cfxZones.isLeftXZ(C, D, thePoint ~= mustMatch)) then return false end \
    if (cfxZones.isLeftXZ(D, A, thePoint ~= mustMatch)) then return false end\
    return true\
end\
\
-- generalized version of insideQuad, assumes winding of poly, poly convex, poly closed\
function cfxZones.isPointInsidePoly(thePoint, poly)\
    local mustMatch = cfxZones.isLeftXZ(poly[1], poly[2], thePoint)\
    for v=2, #poly-1 do \
        if cfxZones.isLeftXZ(poly[v], poly[v+1], thePoint) ~= mustMatch then return false end\
    end\
    -- final test\
    if cfxZones.isLeftXZ(poly[#poly], poly[1], thePoint) ~= mustMatch then return false end\
    \
    return true\
end;\
\
function cfxZones.isPointInsideZone(thePoint, theZone, radiusIncrease)\
    -- radiusIncrease only works for circle zones \
    if not radiusIncrease then radiusIncrease = 0 end \
    local p = {x=thePoint.x, y = 0, z = thePoint.z} -- zones have no altitude\
    if (theZone.isCircle) then \
        local zp = cfxZones.getPoint(theZone)\
        local d = dcsCommon.dist(p, theZone.point)\
        return d < theZone.radius + radiusIncrease, d \
    end \
    \
    if (theZone.isPoly) then \
        --trigger.action.outText(\"zne: isPointInside: \" .. theZone.name .. \" is Polyzone!\", 30)\
        return (cfxZones.isPointInsidePoly(p, theZone.poly)), 0 -- always returns delta 0\
    end\
\
    trigger.action.outText(\"isPointInsideZone: Unknown zone type for \" .. outerZone.name, 10)\
end\
\
-- isZoneInZone returns true if center of innerZone is inside  outerZone\
function cfxZones.isZoneInsideZone(innerZone, outerZone) \
    return cfxZones.isPointInsideZone(innerZone.point, outerZone)\
\
    \
end\
\
function cfxZones.getZonesContainingPoint(thePoint, testZones) -- return array \
    if not testZones then \
        testZones = cfxZones.zones \
    end \
    \
    local containerZones = {}\
    for tName, tData in pairs(testZones) do \
        if cfxZones.isPointInsideZone(thePoint, tData) then \
            table.insert(containerZones, tData)\
        end\
    end\
\
    return containerZones\
end\
\
function cfxZones.getFirstZoneContainingPoint(thePoint, testZones)\
    if not testZones then \
        testZones = cfxZones.zones \
    end \
    \
    for tName, tData in pairs(testZones) do \
        if cfxZones.isPointInsideZone(thePoint, tData) then \
            return tData\
        end\
    end\
\
    return nil\
end\
\
function cfxZones.getAllZonesInsideZone(superZone, testZones) -- returnes array!\
    if not testZones then \
        testZones = cfxZones.zones \
    end \
    \
    local containedZones = {}\
    for zName, zData in pairs(testZones) do\
        if cfxZones.isZoneInsideZone(zData, superZone) then \
            if zData ~= superZone then \
                -- we filter superzone because superzone usually resides \
                -- inside itself \
                table.insert(containedZones, zData)\
            end\
        end\
    end\
    return containedZones \
end\
\
function cfxZones.getZonesWithAttributeNamed(attributeName, testZones)\
    if not testZones then testZones = cfxZones.zones end \
\
    local attributZones = {}\
    for aName,aZone in pairs(testZones) do\
        local attr = cfxZones.getZoneProperty(aZone, attributeName)\
        if attr then \
            -- this zone has the requested attribute\
            table.insert(attributZones, aZone)\
        end\
    end\
    return attributZones\
end\
\
--\
-- units / groups in zone\
--\
function cfxZones.allGroupsInZone(theZone, categ) -- categ is optional, must be code \
    -- warning: does not check for exiting!\
    --trigger.action.outText(\"Zone \" .. theZone.name .. \" radius \" .. theZone.radius, 30)\
    local inZones = {}\
    local coals = {0, 1, 2} -- all coalitions\
    for idx, coa in pairs(coals) do \
        local allGroups = coalition.getGroups(coa, categ)\
        for key, group in pairs(allGroups) do -- iterate all groups\
            if cfxZones.isGroupPartiallyInZone(group, theZone) then\
                table.insert(inZones, group)\
            end\
        end\
    end\
    return inZones\
end\
\
function cfxZones.allGroupNamesInZone(theZone, categ) -- categ is optional, must be code \
    -- warning: does not check for exiting!\
    --trigger.action.outText(\"Zone \" .. theZone.name .. \" radius \" .. theZone.radius, 30)\
    local inZones = {}\
    local coals = {0, 1, 2} -- all coalitions\
    for idx, coa in pairs(coals) do \
        local allGroups = coalition.getGroups(coa, categ)\
        for key, group in pairs(allGroups) do -- iterate all groups\
            if cfxZones.isGroupPartiallyInZone(group, theZone) then\
                table.insert(inZones, group:getName())\
            end\
        end\
    end\
    return inZones\
end\
\
function cfxZones.allStaticsInZone(theZone, useOrigin) -- categ is optional, must be code \
    -- warning: does not check for exiting!\
    local inZones = {}\
    local coals = {0, 1, 2} -- all coalitions\
    for idx, coa in pairs(coals) do \
        local allStats = coalition.getStaticObjects(coa)\
        for key, statO in pairs(allStats) do -- iterate all groups\
            local oP = statO:getPoint()\
            if useOrigin then \
                if cfxZones.pointInZone(oP, theZone, true) then \
                    -- use DCS original coords\
                    table.insert(inZones, statO)\
                end\
            elseif cfxZones.pointInZone(oP, theZone) then\
                table.insert(inZones, statO)\
            end\
        end\
    end\
    return inZones\
end\
\
function cfxZones.groupsOfCoalitionPartiallyInZone(coal, theZone, categ) -- categ is optional\
    local groupsInZone = {}\
    local allGroups = coalition.getGroups(coal, categ)\
    for key, group in pairs(allGroups) do -- iterate all groups\
        if group:isExist() then\
            if cfxZones.isGroupPartiallyInZone(group, theZone) then\
                table.insert(groupsInZone, group)            \
            end\
        end\
    end\
    return groupsInZone\
end\
\
function cfxZones.isGroupPartiallyInZone(aGroup, aZone)\
    if not aGroup then return false end \
    if not aZone then return false end \
        \
    if not aGroup:isExist() then return false end \
    local allUnits = aGroup:getUnits()\
    for uk, aUnit in pairs (allUnits) do \
        if aUnit:isExist() and aUnit:getLife() > 1 then         \
            local p = aUnit:getPoint()\
            local inzone, percent, dist = cfxZones.pointInZone(p, aZone)\
            if inzone then -- cfxZones.isPointInsideZone(p, aZone) then             \
                --trigger.action.outText(\"zne: YAY <\" .. aUnit:getName() .. \"> IS IN \" .. aZone.name, 30) \
                return true\
            end \
            --trigger.action.outText(\"zne: <\" .. aUnit:getName() .. \"> not in \" .. aZone.name .. \", dist = \" .. dist .. \", rad = \", aZone.radius, 30) \
        end\
    end\
    return false\
end\
\
function cfxZones.isEntireGroupInZone(aGroup, aZone)\
    if not aGroup then return false end \
    if not aZone then return false end \
    if not aGroup:isExist() then return false end \
    local allUnits = aGroup:getUnits()\
    for uk, aUnit in pairs (allUnits) do \
        if aUnit:isExist() and aUnit:getLife() > 1 then \
            local p = aUnit:getPoint()\
            if not cfxZones.isPointInsideZone(p, aZone) then \
                return false\
            end\
        end\
    end\
    return true\
end\
\
\
--\
-- Zone Manipulation\
--\
\
function cfxZones.offsetZone(theZone, dx, dz)\
    -- first, update center \
    theZone.point.x = theZone.point.x + dx\
    theZone.point.z = theZone.point.z + dz \
    \
    -- now process all polygon points - it's empty for circular, so don't worry\
    for v=1, #theZone.poly do \
        theZone.poly[v].x = theZone.poly[v].x + dx\
        theZone.poly[v].z = theZone.poly[v].z + dz \
    end\
end\
\
function cfxZones.moveZoneTo(theZone, x, z)\
    local dx = x - theZone.point.x\
    local dz = z - theZone.point.z \
    cfxZones.offsetZone(theZone, dx, dz)\
end;\
\
function cfxZones.centerZoneOnUnit(theZone, theUnit) \
    local thePoint = theUnit:getPoint()\
    cfxZones.moveZoneTo(theZone, thePoint.x, thePoint.z)\
end\
\
\
--[[\
-- no longer makes sense with poly zones\
function cfxZones.isZoneEntirelyInsideZone(innerZone, outerZone)\
    if (innerZone.radius > outerZone.radius) then return false end -- cant fit inside\
    local d = dcsCommon.dist(innerZone.point, outerZone.point)\
    local reducedR = outerZone.radius - innerZone.radius\
    return d < reducedR\
end;\
--]]\
\
function cfxZones.dumpZones(zoneTable)\
    if not zoneTable then zoneTable = cfxZones.zones end \
    \
    trigger.action.outText(\"Zones START\", 10)\
    for i, zone in pairs(zoneTable) do \
        local myType = \"unknown\"\
        if zone.isCircle then myType = \"Circle\" end\
        if zone.isPoly then myType = \"Poly\" end \
        \
        trigger.action.outText(\"#\".. i .. \": \" .. zone.name .. \" of type \" .. myType, 10)\
    end\
    trigger.action.outText(\"Zones END\", 10)\
end\
\
function cfxZones.stringStartsWith(theString, thePrefix)\
    return theString:find(thePrefix) == 1\
end\
\
function cfxZones.keysForTable(theTable)\
    local keyset={}\
    local n=0\
\
    for k,v in pairs(tab) do\
        n=n+1\
        keyset[n]=k\
    end\
    return keyset\
end\
\
\
--\
-- return all zones that have a specific named property\
--\
function cfxZones.zonesWithProperty(propertyName, searchSet)\
    if not searchSet then searchSet = cfxZones.zones end \
    local theZones = {}\
    for k, aZone in pairs(searchSet) do \
        if not aZone then \
            trigger.action.outText(\"+++zone: nil aZone for \" .. k, 30)\
        else \
            local lU = cfxZones.getZoneProperty(aZone, propertyName)\
            if lU then \
                table.insert(theZones, aZone)\
            end\
        end\
    end    \
    return theZones\
end\
\
--\
-- return all zones from the zone table that begin with string prefix\
--\
function cfxZones.zonesStartingWithName(prefix, searchSet)\
    \
    if not searchSet then searchSet = cfxZones.zones end \
    \
--    trigger.action.outText(\"Enter: zonesStartingWithName for \" .. prefix , 30)\
    local prefixZones = {}\
    prefix = prefix:upper() -- all zones have UPPERCASE NAMES! THEY SCREAM AT YOU\
    for name, zone in pairs(searchSet) do\
--        trigger.action.outText(\"testing \" .. name:upper() .. \" starts with \" .. prefix , 30)\
        if cfxZones.stringStartsWith(name:upper(), prefix) then\
            prefixZones[name] = zone -- note: ref copy!\
            --trigger.action.outText(\"zone with prefix <\" .. prefix .. \"> found: \" .. name, 10)\
        end\
    end\
    \
    return prefixZones\
end\
\
--\
-- return all zones from the zone table that begin with the string or set of strings passed in prefix \
-- if you pass 'true' as second (optional) parameter, it will first look for all zones that begin\
-- with '+' and return only those. Use during debugging to force finding a specific zone\
--\
function cfxZones.zonesStartingWith(prefix, searchSet, debugging)\
    -- you can force zones by having their name start with \"+\"\
    -- which will force them to return immediately if debugging is true for this call\
\
    if (debugging) then \
        local debugZones = cfxZones.zonesStartingWithName(\"+\", searchSet)\
        if not (next(debugZones) == nil) then -- # operator only works on array elements \
            --trigger.action.outText(\"returning zones with prefix <\" .. prefix .. \">\", 10)\
            return debugZones \
        end \
    end\
    \
    --trigger.action.outText(\"#debugZones is  <\" .. #debugZones .. \">\", 10)\
\
    if (type(prefix) == \"string\") then \
        return cfxZones.zonesStartingWithName(prefix, searchSet)\
    end\
    \
    local allZones = {}\
    for i=1, #prefix do \
        -- iterate through all names in prefix set\
        local theName = prefix[i]\
        local newZones = cfxZones.zonesStartingWithName(theName, searchSet)\
        -- add them all to current table\
        for zName, zInfo in pairs(newZones) do \
            allZones[zName] = zInfo -- will also replace doublets\
        end\
    end\
    \
    return allZones\
end\
\
function cfxZones.getZoneByName(aName, searchSet) \
    if not searchSet then searchSet = cfxZones.zones end \
    aName = aName:upper()\
    return searchSet[aName] -- the joys of key value pairs\
end\
\
function cfxZones.getZonesContainingString(aString, searchSet) \
    if not searchSet then searchSet = cfxZones.zones end\
    aString = string.upper(aString)\
    resultSet = {}\
    for zName, zData in pairs(searchSet) do \
        if aString == string.upper(zData.name) then \
            resultSet[zName] = zData\
        end\
    end\
    \
end;\
\
-- filter zones by range to a point. returns indexed set\
function cfxZones.getZonesInRange(point, range, theZones)\
    if not theZones then theZones = cfxZones.zones end\
    \
    local inRangeSet = {}\
    for zName, zData in pairs (theZones) do \
        if dcsCommon.dist(point, zData.point) < range then \
            table.insert(inRangeSet, zData)\
        end\
    end\
    return inRangeSet \
end\
\
-- get closest zone returns the zone that is closest to point \
function cfxZones.getClosestZone(point, theZones)\
    if not theZones then theZones = cfxZones.zones end\
    local lPoint = {x=point.x, y=0, z=point.z}\
    local currDelta = math.huge \
    local closestZone = nil\
    for zName, zData in pairs(theZones) do \
        local zPoint = cfxZones.getPoint(zData)\
        local delta = dcsCommon.dist(lPoint, zPoint) -- emulate flag compare \
        if (delta < currDelta) then \
            currDelta = delta\
            closestZone = zData\
        end\
    end\
    return closestZone, currDelta \
end\
\
-- return a random zone from the table passed in zones\
function cfxZones.pickRandomZoneFrom(zones)\
    if not zones then zones = cfxZones.zones end\
    local indexedZones = dcsCommon.enumerateTable(zones)\
    local r = math.random(#indexedZones)\
    return indexedZones[r]\
end\
\
-- return an zone element by index \
function cfxZones.getZoneByIndex(theZones, theIndex) \
    local enumeratedZones = dcsCommon.enumerateTable(theZones)\
    if (theIndex > #enumeratedZones) then\
        trigger.action.outText(\"WARNING: zone index \" .. theIndex .. \" out of bounds - max = \" .. #enumeratedZones, 30)\
        return nil end\
    if (theIndex < 1) then return nil end\
    \
    return enumeratedZones[theIndex]\
end\
\
-- place a smoke marker in center of zone, offset by dx, dy \
function cfxZones.markZoneWithSmoke(theZone, dx, dz, smokeColor, alt)\
    if not alt then alt = 5 end \
    local point = cfxZones.getPoint(theZone) --{} -- theZone.point\
    point.x = point.x + dx -- getpoint updates and returns copy \
    point.z = point.z + dz \
    -- get height at point \
    point.y = land.getHeight({x = point.x, y = point.z}) + alt\
    -- height-correct\
    --local newPoint= {x = point.x, y = land.getHeight({x = point.x, y = point.z}) + 3, z= point.z}\
    trigger.action.smoke(point, smokeColor)\
end\
\
-- place a smoke marker in center of zone, offset by radius and degrees \
function cfxZones.markZoneWithSmokePolar(theZone, radius, degrees, smokeColor, alt)\
    local rads = degrees * math.pi / 180\
    local dx = radius * math.sin(rads)\
    local dz = radius * math.cos(rads)\
    cfxZones.markZoneWithSmoke(theZone, dx, dz, smokeColor, alt)\
end\
\
-- place a smoke marker in center of zone, offset by radius and randomized degrees \
function cfxZones.markZoneWithSmokePolarRandom(theZone, radius, smokeColor)\
    local degrees = math.random(360)\
    cfxZones.markZoneWithSmokePolar(theZone, radius, degrees, smokeColor)\
end\
\
function cfxZones.pointInOneOfZones(thePoint, zoneArray, useOrig) \
    if not zoneArray then zoneArray = cfxZones.zones end \
    for idx, theZone in pairs(zoneArray) do \
        local isIn, percent, dist = cfxZones.pointInZone(thePoint, theZone, useOrig)\
        if isIn then return isIn, percent, dist, theZone end \
    end\
    return false, 0, 0, nil \
end\
\
\
-- unitInZone returns true if theUnit is inside the zone \
-- the second value returned is the percentage of distance\
-- from center to rim, with 100% being entirely in center, 0 = outside\
-- the third value returned is the distance to center\
function cfxZones.pointInZone(thePoint, theZone, useOrig)\
\
    if not (theZone) then return false, 0, 0 end\
        \
    local pflat = {x = thePoint.x, y = 0, z = thePoint.z}\
    \
    local zpoint \
    if useOrig then\
        zpoint = cfxZones.getDCSOrigin(theZone)\
    else \
        zpoint = cfxZones.getPoint(theZone) -- updates zone if linked \
    end\
    local ppoint = thePoint -- xyz\
    local pflat = {x = ppoint.x, y = 0, z = ppoint.z}\
    local dist = dcsCommon.dist(zpoint, pflat)\
    \
    if theZone.isCircle then \
        if theZone.radius <= 0 then \
            return false, 0, 0\
        end\
\
        local success = dist < theZone.radius\
        local percentage = 0\
        if (success) then \
            percentage = 1 - dist / theZone.radius \
        end\
        return success, percentage, dist \
    \
    elseif theZone.isPoly then\
        local success = cfxZones.isPointInsidePoly(pflat, theZone.poly)\
        return success, 0, dist\
    else \
        trigger.action.outText(\"pointInZone: Unknown zone type for \" .. theZone.name, 10)\
    end\
\
    return false\
end\
\
function cfxZones.unitInZone(theUnit, theZone)\
    if not (theUnit) then return false, 0, 0 end\
    if not (theUnit:isExist()) then return false, 0, 0 end\
    -- force zone update if it is linked to another zone \
    -- pointInZone does update\
    local thePoint = theUnit:getPoint()\
    return cfxZones.pointInZone(thePoint, theZone)\
    \
end\
\
-- returns all units of the input set that are inside the zone \
function cfxZones.unitsInZone(theUnits, theZone)\
    if not theUnits then return {} end\
    if not theZone then return {} end\
    \
    local zoneUnits = {}\
    for index, aUnit in pairs(theUnits) do \
        if cfxZones.unitInZone(aUnit, theZone) then \
            table.insert( zoneUnits, aUnit)\
        end\
    end\
    return zoneUnits\
end\
\
function cfxZones.closestUnitToZoneCenter(theUnits, theZone)\
    -- does not care if they really are in zone. call unitsInZone first\
    -- if you need to have them filtered\
    -- theUnits MUST BE ARRAY\
    if not theUnits then return nil end\
    if #theUnits == 0 then return nil end\
    local closestUnit = theUnits[1]\
    for i=2, #theUnits do\
        local aUnit = theUnits[i]\
        if dcsCommon.dist(theZone.point, closestUnit:getPoint()) > dcsCommon.dist(theZone.point, aUnit:getPoint()) then \
            closestUnit = aUnit\
        end\
    end\
    return closestUnit\
end\
\
function cfxZones.anyPlayerInZone(theZone) -- returns first player it finds\
    for pname, pinfo in pairs(cfxPlayer.playerDB) do\
        local playerUnit = pinfo.unit\
        if (cfxZones.unitInZone(playerUnit, theZone)) then \
            return true, playerUnit\
        end\
    end -- for all players \
    return false, nil\
end\
\
\
-- grow zone\
function cfxZones.growZone()\
    -- circular zones simply increase radius\
    -- poly zones: not defined \
    \
end\
\
\
-- creating units in a zone\
function cfxZones.createGroundUnitsInZoneForCoalition (theCoalition, groupName, theZone, theUnits, formation, heading) \
    -- theUnits can be string or table of string \
    if not groupName then groupName = \"G_\"..theZone.name end \
    -- group name will be taken from zone name and prependend with \"G_\"\
    local theGroup = dcsCommon.createGroundGroupWithUnits(groupName, theUnits, theZone.radius, nil, formation)\
    \
    -- turn the entire formation to heading\
    if (not heading) then heading = 0 end\
    dcsCommon.rotateGroupData(theGroup, heading) -- currently, group is still at origin, no cx, cy\
    \
    \
    -- now move the group to center of theZone\
    dcsCommon.moveGroupDataTo(theGroup, \
                          theZone.point.x, \
                          theZone.point.z) -- watchit: Z!!!\
\
\
    -- create the group in the world and return it\
    -- first we need to translate the coalition to a legal \
    -- country. we use UN for neutral, cjtf for red and blue \
    local theSideCJTF = dcsCommon.coalition2county(theCoalition)\
    -- store cty and cat for later access. DCS doesn't need it, but we may \
    \
    theGroup.cty = theSideCJTF\
    theGroup.cat = Group.Category.GROUND\
    \
    -- create a copy of the group data for \
    -- later reference \
    local groupDataCopy = dcsCommon.clone(theGroup)\
\
    local newGroup = coalition.addGroup(theSideCJTF, Group.Category.GROUND, theGroup)\
    return newGroup, groupDataCopy\
end\
\
--\
-- ===============\
-- FLAG PROCESSING \
-- ===============\
--\
\
--\
-- Flag Pulling \
--\
function cfxZones.pulseFlag(theFlag, method, theZone)\
    local args = {}\
    args.theFlag = theFlag\
    args.method = method\
    args.theZone = theZone \
    local delay = 3\
    if dcsCommon.containsString(method, \",\") then \
        local parts = dcsCommon.splitString(method, \",\")\
        delay = parts[2]\
        if delay then delay = tonumber(delay) end  \
    end\
    if not delay then delay = 3 end \
    if theZone.verbose then \
        trigger.action.outText(\"+++zne: RAISING pulse t=\"..delay..\" for flag <\" .. theFlag .. \"> in zone <\" .. theZone.name ..\">\", 30)\
    end \
    local newVal = 1\
    cfxZones.setFlagValue(theFlag, newVal, theZone)\
    \
    -- schedule second half of pulse \
    timer.scheduleFunction(cfxZones.unPulseFlag, args, timer.getTime() + delay)\
end\
\
function cfxZones.unPulseFlag(args)\
    local theZone = args.theZone\
    local method = args.method \
    local theFlag = args.theFlag \
    local newVal = 0\
    -- we may later use method to determine pulse direction / newVal\
    -- for now, we always go low \
    if theZone.verbose then \
        trigger.action.outText(\"+++zne: DOWNPULSE pulse for flag <\" .. theFlag .. \"> in zone <\" .. theZone.name ..\">\", 30)\
    end\
    cfxZones.setFlagValue(theFlag, newVal, theZone)\
end\
\
function cfxZones.evalRemainder(remainder)\
    local rNum = tonumber(remainder)\
    if not rNum then \
        -- we use remainder as name for flag \
        -- PROCESS ESCAPE SEQUENCES\
        local esc = string.sub(remainder, 1, 1)\
        local last = string.sub(remainder, -1)\
        if esc == \"@\" then \
            remainder = string.sub(remainder, 2)\
            remainder = dcsCommon.trim(remainder)\
        end\
        \
        if esc == \"(\" and last == \")\" and string.len(remainder) > 2 then \
            -- note: iisues with startswith(\"(\") ???\
            remainder = string.sub(remainder, 2, -2)\
            remainder = dcsCommon.trim(remainder)        \
        end\
        if esc == \"\\\"\" and last == \"\\\"\" and string.len(remainder) > 2 then \
            remainder = string.sub(remainder, 2, -2)\
            remainder = dcsCommon.trim(remainder)        \
        end\
        if cfxZones.verbose then \
            trigger.action.outText(\"+++zne: accessing flag <\" .. remainder .. \">\", 30)\
        end \
        rNum = cfxZones.getFlagValue(remainder, theZone)\
    end \
    return rNum\
end\
\
function cfxZones.doPollFlag(theFlag, method, theZone)\
    if cfxZones.verbose then \
        trigger.action.outText(\"+++zones: polling flag \" .. theFlag .. \" with \" .. method, 30)\
    end \
    \
    if not theZone then \
        trigger.action.outText(\"+++zones: nil theZone on pollFlag\", 30)\
    end\
    \
    method = method:lower()\
    method = dcsCommon.trim(method)\
    val = tonumber(method)\
    if dcsCommon.stringStartsWith(method, \"+\") or dcsCommon.stringStartsWith(method, \"-\")\
    then \
        -- skip this processing, a legal Lua val can start with \"+\" or \"-\"\
        -- but we interpret it as a method\
    else\
        if val then \
            cfxZones.setFlagValue(theFlag, val, theZone)\
            if cfxZones.verbose or theZone.verbose then\
                trigger.action.outText(\"+++zones: flag <\" .. theFlag .. \"> changed to #\" .. val, 30)\
            end \
            return\
        end \
    end\
    --trigger.action.outText(\"+++zones: polling \" .. theZone.name .. \" method \" .. method .. \" flag \" .. theFlag, 30)\
    local currVal = cfxZones.getFlagValue(theFlag, theZone)\
    if method == \"inc\" or method == \"f+1\" then \
        --trigger.action.setUserFlag(theFlag, currVal + 1)\
        cfxZones.setFlagValue(theFlag, currVal+1, theZone)\
        \
    elseif method == \"dec\" or method == \"f-1\" then \
        -- trigger.action.setUserFlag(theFlag, currVal - 1)\
        cfxZones.setFlagValue(theFlag, currVal-1, theZone)\
\
    elseif method == \"off\" or method == \"f=0\" then \
        -- trigger.action.setUserFlag(theFlag, 0)\
        cfxZones.setFlagValue(theFlag, 0, theZone)\
\
    elseif method == \"flip\" or method == \"xor\" then \
        if currVal ~= 0 then \
--            trigger.action.setUserFlag(theFlag, 0)\
            cfxZones.setFlagValue(theFlag, 0, theZone)\
\
        else \
            --trigger.action.setUserFlag(theFlag, 1)\
            cfxZones.setFlagValue(theFlag, 1, theZone)\
        end\
        \
    elseif dcsCommon.stringStartsWith(method, \"pulse\") then \
        cfxZones.pulseFlag(theFlag, method, theZone)\
        \
    elseif dcsCommon.stringStartsWith(method, \"+\") then \
        -- we add whatever is to the right \
        local remainder = dcsCommon.removePrefix(method, \"+\")\
        local adder = cfxZones.evalRemainder(remainder)\
        cfxZones.setFlagValue(theFlag, currVal+adder, theZone)\
        if theZone.verbose then \
            trigger.action.outText(\"+++zones: (poll) updating with '+' flag <\" .. theFlag .. \"> in <\" .. theZone.name .. \"> by <\" .. adder .. \"> to <\" .. adder + currVal .. \">\", 30)\
        end\
        \
    elseif dcsCommon.stringStartsWith(method, \"-\") then \
        -- we subtract whatever is to the right \
        local remainder = dcsCommon.removePrefix(method, \"-\")\
        local adder = cfxZones.evalRemainder(remainder)\
        cfxZones.setFlagValue(theFlag, currVal-adder, theZone)\
\
    else \
        if method ~= \"on\" and method ~= \"f=1\" then \
            trigger.action.outText(\"+++zones: unknown method <\" .. method .. \"> - using 'on'\", 30)\
        end\
        -- default: on.\
--        trigger.action.setUserFlag(theFlag, 1)\
        cfxZones.setFlagValue(theFlag, 1, theZone)\
    end\
    \
    if cfxZones.verbose then\
        local newVal = cfxZones.getFlagValue(theFlag, theZone)\
        trigger.action.outText(\"+++zones: flag <\" .. theFlag .. \"> changed from \" .. currVal .. \" to \" .. newVal, 30)\
    end \
end\
\
function cfxZones.pollFlag(theFlag, method, theZone) \
    local allFlags = {}\
    if dcsCommon.containsString(theFlag, \",\") then \
        if cfxZones.verbose then \
            trigger.action.outText(\"+++zones: will poll flag set <\" .. theFlag .. \"> with \" .. method, 30)\
        end\
        allFlags = dcsCommon.splitString(theFlag, \",\")\
    else \
        table.insert(allFlags, theFlag)\
    end\
    \
    for idx, aFlag in pairs(allFlags) do \
        aFlag = dcsCommon.trim(aFlag)\
        -- note: mey require range preprocessing, but that's not\
        -- a priority \
        cfxZones.doPollFlag(aFlag, method, theZone)\
    end \
    \
end\
\
function cfxZones.expandFlagName(theFlag, theZone) \
    if not theFlag then return \"!NIL\" end \
    local zoneName = \"<dummy>\"\
    if theZone then \
        zoneName = theZone.name -- for flag wildcards\
    end\
    \
    if type(theFlag) == \"number\" then \
        -- straight number, return \
        return theFlag\
    end\
    \
    -- we assume it's a string now\
    theFlag = dcsCommon.trim(theFlag) -- clear leading/trailing spaces\
    local nFlag = tonumber(theFlag) \
    if nFlag then -- a number, legal\
        return theFlag\
    end\
        \
    -- now do wildcard processing. we have alphanumeric\
    if dcsCommon.stringStartsWith(theFlag, \"*\") then  \
        theFlag = zoneName .. theFlag\
    end\
    return theFlag\
end\
\
function cfxZones.setFlagValueMult(theFlag, theValue, theZone)\
    local allFlags = {}\
    if dcsCommon.containsString(theFlag, \",\") then \
        if cfxZones.verbose then \
            trigger.action.outText(\"+++zones: will multi-set flags <\" .. theFlag .. \"> to \" .. theValue, 30)\
        end\
        allFlags = dcsCommon.splitString(theFlag, \",\")\
    else \
        table.insert(allFlags, theFlag)\
    end\
    \
    for idx, aFlag in pairs(allFlags) do \
        aFlag = dcsCommon.trim(aFlag)\
        -- note: mey require range preprocessing, but that's not\
        -- a priority \
        cfxZones.setFlagValue(aFlag, theValue, theZone)\
    end \
end\
\
function cfxZones.setFlagValue(theFlag, theValue, theZone)\
    local zoneName = \"<dummy>\"\
    if not theZone then \
        trigger.action.outText(\"+++Zne: no zone on setFlagValue\", 30) -- mod me for detector\
    else \
        zoneName = theZone.name -- for flag wildcards\
    end\
    \
    if type(theFlag) == \"number\" then \
        -- straight set, ME flag \
        trigger.action.setUserFlag(theFlag, theValue)\
        return \
    end\
    \
    -- we assume it's a string now\
    theFlag = dcsCommon.trim(theFlag) -- clear leading/trailing spaces\
    local nFlag = tonumber(theFlag) \
    if nFlag then \
        trigger.action.setUserFlag(theFlag, theValue)\
        return \
    end\
    \
    -- some QoL: detect \"<none>\"\
    if dcsCommon.containsString(theFlag, \"<none>\") then \
        trigger.action.outText(\"+++Zone: warning - setFlag has '<none>' flag name in zone <\" .. zoneName .. \">\", 30) -- if error, intended break\
    end\
    \
    -- now do wildcard processing. we have alphanumeric\
    if dcsCommon.stringStartsWith(theFlag, \"*\") then  \
        theFlag = zoneName .. theFlag\
    end\
    trigger.action.setUserFlag(theFlag, theValue)\
end \
\
function cfxZones.getFlagValue(theFlag, theZone)\
    local zoneName = \"<dummy>\"\
    if not theZone or not theZone.name then \
        trigger.action.outText(\"+++Zne: no zone or zone name on getFlagValue\", 30)\
    else \
        zoneName = theZone.name -- for flag wildcards\
    end\
    \
    if type(theFlag) == \"number\" then \
        -- straight get, ME flag \
        return tonumber(trigger.misc.getUserFlag(theFlag))\
    end\
    \
    -- we assume it's a string now\
    theFlag = dcsCommon.trim(theFlag) -- clear leading/trailing spaces\
    local nFlag = tonumber(theFlag) \
    if nFlag then \
        return tonumber(trigger.misc.getUserFlag(theFlag))\
    end\
    \
    -- some QoL: detect \"<none>\"\
    if dcsCommon.containsString(theFlag, \"<none>\") then \
        trigger.action.outText(\"+++Zone: warning - getFlag has '<none>' flag name in zone <\" .. zoneName .. \">\", 30) -- break here\
    end\
    \
    -- now do wildcard processing. we have alphanumeric\
    if dcsCommon.stringStartsWith(theFlag, \"*\") then  \
            theFlag = zoneName .. theFlag\
    end\
    return tonumber(trigger.misc.getUserFlag(theFlag))\
end\
\
function cfxZones.isMEFlag(inFlag)\
    -- do NOT use me\
    trigger.action.outText(\"+++zne: warning: deprecated isMEFlag\", 30)\
    return true \
    -- returns true if inFlag is a pure positive number\
end\
\
function cfxZones.verifyMethod(theMethod, theZone)\
    local lMethod = string.lower(theMethod)\
    if lMethod == \"#\" or lMethod == \"change\" then \
        return true\
    end\
\
    if lMethod == \"0\" or lMethod == \"no\" or lMethod == \"false\" \
       or lMethod == \"off\" then \
        return true  \
    end\
    \
    if lMethod == \"1\" or lMethod == \"yes\" or lMethod == \"true\" \
       or lMethod == \"on\" then \
        return true  \
    end\
    \
    if lMethod == \"inc\" or lMethod == \"+1\" then \
        return true\
    end\
    \
    if lMethod == \"dec\" or lMethod == \"-1\" then \
        return true \
    end \
    \
    if lMethod == \"lohi\" or lMethod == \"pulse\" then \
        return true\
    end\
    \
    if lMethod == \"hilo\" then \
        return true\
    end\
    \
    -- number constraints\
    -- or flag constraints     -- ONLY RETURN TRUE IF CHANGE AND CONSTRAINT MET \
    local op = string.sub(theMethod, 1, 1) \
    local remainder = string.sub(theMethod, 2)\
    remainder = dcsCommon.trim(remainder) -- remove all leading and trailing spaces\
\
    if true then \
        -- we have a comparison = \">\", \"=\", \"<\" followed by a number \
        -- THEY TRIGGER EACH TIME lastVal <> currVal AND condition IS MET  \
        if op == \"=\" then \
            return true\
        end\
        \
        if op == \"#\" or op == \"~\" then \
            return true\
        end \
        \
        if op == \"<\" then \
            return true\
        end\
        \
        if op == \">\" then \
            return true\
        end\
    end\
    \
    return false \
end\
\
-- method-based flag testing \
function cfxZones.evalFlagMethodImmediate(currVal, theMethod, theZone)\
    -- immediate eval - does not look at last val. \
    -- return true/false/value based on theMethod's contraints \
    -- simple constraints\
    local lMethod = string.lower(theMethod)\
    if lMethod == \"#\" or lMethod == \"change\" then \
        -- ALWAYS RETURNS TRUE for currval <> 0, flase if currval = 0\
        return currVal ~= 0  \
    end\
    \
    if lMethod == \"0\" or lMethod == \"no\" or lMethod == \"false\" \
       or lMethod == \"off\" then \
        -- WARNING: ALWAYS RETURNS FALSE\
        return false  \
    end\
    \
    if lMethod == \"1\" or lMethod == \"yes\" or lMethod == \"true\" \
       or lMethod == \"on\" then \
        -- WARNING: ALWAYS RETURNS TRUE\
        return true  \
    end\
    \
    if lMethod == \"inc\" or lMethod == \"+1\" then \
        return currVal+1 -- this may be unexpected\
    end\
    \
    if lMethod == \"dec\" or lMethod == \"-1\" then \
        return currVal-1 -- this may be unexpectd\
    end \
    \
    -- number constraints\
    -- or flag constraints \
    -- ONLY RETURN TRUE IF CHANGE AND CONSTRAINT MET \
    local op = string.sub(theMethod, 1, 1) \
    local remainder = string.sub(theMethod, 2)\
    remainder = dcsCommon.trim(remainder) -- remove all leading and trailing spaces\
    local rNum = tonumber(remainder)\
    if not rNum then \
        -- we use remainder as name for flag \
        -- PROCESS ESCAPE SEQUENCES\
        local esc = string.sub(remainder, 1, 1)\
        local last = string.sub(remainder, -1)\
        if esc == \"@\" then \
            remainder = string.sub(remainder, 2)\
            remainder = dcsCommon.trim(remainder)\
        end\
        \
        if esc == \"(\" and last == \")\" and string.len(remainder) > 2 then \
            -- note: iisues with startswith(\"(\") ???\
            remainder = string.sub(remainder, 2, -2)\
            remainder = dcsCommon.trim(remainder)        \
        end\
        if esc == \"\\\"\" and last == \"\\\"\" and string.len(remainder) > 2 then \
            remainder = string.sub(remainder, 2, -2)\
            remainder = dcsCommon.trim(remainder)        \
        end\
        if cfxZones.verbose then \
            trigger.action.outText(\"+++zne: accessing flag <\" .. remainder .. \">\", 30)\
        end \
        rNum = cfxZones.getFlagValue(remainder, theZone)\
    end \
    if rNum then \
        -- we have a comparison = \">\", \"=\", \"<\" followed by a number  \
        if op == \"=\" then \
            return currVal == rNum\
        end\
        \
        if op == \"#\" or op == \"~\" then \
            return currVal ~= rNum \
        end \
        \
        if op == \"<\" then \
            return currVal < rNum\
        end\
        \
        if op == \">\" then \
            return currVal > rNum\
        end\
    end\
    \
    -- if we get here, we have an error \
    local zoneName = \"<NIL>\"\
    if theZone then zoneName = theZone.name end \
    trigger.action.outText(\"+++Zne: illegal |\" .. theMethod .. \"| in eval for zone \" .. zoneName, 30 )\
    return false     \
end\
\
function cfxZones.testFlagByMethodForZone(currVal, lastVal, theMethod, theZone)\
    -- return true/false based on theMethod's contraints \
    -- simple constraints\
    -- ONLY RETURN TRUE IF CHANGE AND CONSTRAINT MET \
    local lMethod = string.lower(theMethod)\
    if lMethod == \"#\" or lMethod == \"change\" then \
        -- check if currVal different from lastVal\
        return currVal ~= lastVal  \
    end\
    \
    if lMethod == \"0\" or lMethod == \"no\" or lMethod == \"false\" \
       or lMethod == \"off\" then \
        -- WARNING: ONLY RETURNS TRUE IF FALSE AND lastval not zero!\
        return currVal == 0 and currVal ~= lastVal  \
    end\
    \
    if lMethod == \"1\" or lMethod == \"yes\" or lMethod == \"true\" \
       or lMethod == \"on\" then \
        -- WARNING: only returns true if lastval was false!!!!\
        return (currVal ~= 0 and lastVal == 0)  \
    end\
    \
    if lMethod == \"inc\" or lMethod == \"+1\" then \
--        return currVal == lastVal+1 -- better: test for greater than \
        return currVal > lastVal\
    end\
    \
    if lMethod == \"dec\" or lMethod == \"-1\" then \
        --return currVal == lastVal-1\
        return currVal < lastVal \
    end \
    \
    if lMethod == \"lohi\" or lMethod == \"pulse\" then \
        return (lastVal <= 0 and currVal > 0)\
    end\
    \
    if lMethod == \"hilo\" then \
        return (lastVal > 0 and currVal <= 0)\
    end\
    \
    -- number constraints\
    -- or flag constraints \
    -- ONLY RETURN TRUE IF CHANGE AND CONSTRAINT MET \
    local op = string.sub(theMethod, 1, 1) \
    local remainder = string.sub(theMethod, 2)\
    remainder = dcsCommon.trim(remainder) -- remove all leading and trailing spaces\
    local rNum = tonumber(remainder)\
    if not rNum then \
        -- we use remainder as name for flag \
        -- PROCESS ESCAPE SEQUENCES\
        local esc = string.sub(remainder, 1, 1)\
        local last = string.sub(remainder, -1)\
        if esc == \"@\" then \
            remainder = string.sub(remainder, 2)\
            remainder = dcsCommon.trim(remainder)\
        end\
        \
        if esc == \"(\" and last == \")\" and string.len(remainder) > 2 then \
            -- note: iisues with startswith(\"(\") ???\
            remainder = string.sub(remainder, 2, -2)\
            remainder = dcsCommon.trim(remainder)        \
        end\
        if esc == \"\\\"\" and last == \"\\\"\" and string.len(remainder) > 2 then \
            remainder = string.sub(remainder, 2, -2)\
            remainder = dcsCommon.trim(remainder)        \
        end\
        if cfxZones.verbose then \
            trigger.action.outText(\"+++zne: accessing flag <\" .. remainder .. \">\", 30)\
        end \
        rNum = cfxZones.getFlagValue(remainder, theZone)\
    end \
    if rNum then \
        -- we have a comparison = \">\", \"=\", \"<\" followed by a number \
        -- THEY TRIGGER EACH TIME lastVal <> currVal AND condition IS MET  \
        if op == \"=\" then \
            return currVal == rNum and lastVal ~= currVal\
        end\
        \
        if op == \"#\" or op == \"~\" then \
            return currVal ~= rNum and lastVal ~= currVal \
        end \
        \
        if op == \"<\" then \
            return currVal < rNum and lastVal ~= currVal\
        end\
        \
        if op == \">\" then \
            return currVal > rNum and lastVal ~= currVal\
        end\
    end\
    \
    -- if we get here, we have an error \
    local zoneName = \"<NIL>\"\
    if theZone then zoneName = theZone.name end \
    trigger.action.outText(\"+++Zne: illegal method constraints |\" .. theMethod .. \"| for zone \" .. zoneName, 30 )\
    return false \
end\
\
\
function cfxZones.testZoneFlag(theZone, theFlagName, theMethod, latchName)\
    -- returns two values: true/false method result, and curr value\
    -- returns true if method constraints are met for flag theFlagName\
    -- as defined by theMethod \
    if not theMethod then \
        theMethod = \"change\"\
    end \
    \
    -- will read and update theZone[latchName] as appropriate \
    if not theZone then \
        trigger.action.outText(\"+++Zne: no zone for testZoneFlag\", 30)\
        return nil, nil \
    end \
    if not theFlagName then \
        -- this is common, no error, only on verbose \
        if cfxZones.verbose then \
            trigger.action.outText(\"+++Zne: no flagName for zone \" .. theZone.name .. \" for testZoneFlag\", 30)\
        end \
        return nil, nil\
    end\
    if not latchName then \
        trigger.action.outText(\"+++Zne: no latchName for zone \" .. theZone.name .. \" for testZoneFlag\", 30)\
        return nil, nil \
    end\
    -- get current value \
    local currVal = cfxZones.getFlagValue(theFlagName, theZone)\
    \
    -- get last value from latch\
    local lastVal = theZone[latchName]\
    if not lastVal then \
        trigger.action.outText(\"+++Zne: latch <\" .. latchName .. \"> not valid for zone \" .. theZone.name, 30) -- intentional break here \
        return nil, nil\
    end\
    \
    -- now, test by method \
    -- we should only test if currVal <> lastVal \
    if currVal == lastVal then\
        return false, currVal\
    end \
    \
    --trigger.action.outText(\"+++Zne: about to test: c = \" .. currVal .. \", l = \" .. lastVal, 30)\
    local testResult = cfxZones.testFlagByMethodForZone(currVal, lastVal, theMethod, theZone)\
\
    -- update latch by method\
    theZone[latchName] = currVal \
\
    -- return result\
    return testResult, currVal\
end\
\
\
\
function cfxZones.flagArrayFromString(inString)\
-- original code from RND flag\
    if string.len(inString) < 1 then \
        trigger.action.outText(\"+++zne: empty flags\", 30)\
        return {} \
    end\
    if cfxZones.verbose then \
        trigger.action.outText(\"+++zne: processing <\" .. inString .. \">\", 30)\
    end \
    \
    local flags = {}\
    local rawElements = dcsCommon.splitString(inString, \",\")\
    -- go over all elements \
    for idx, anElement in pairs(rawElements) do \
        anElement = dcsCommon.trim(anElement)\
        if dcsCommon.stringStartsWithDigit(anElement) and dcsCommon.containsString(anElement, \"-\") then \
            -- interpret this as a range\
            local theRange = dcsCommon.splitString(anElement, \"-\")\
            local lowerBound = theRange[1]\
            lowerBound = tonumber(lowerBound)\
            local upperBound = theRange[2]\
            upperBound = tonumber(upperBound)\
            if lowerBound and upperBound then\
                -- swap if wrong order\
                if lowerBound > upperBound then \
                    local temp = upperBound\
                    upperBound = lowerBound\
                    lowerBound = temp \
                end\
                -- now add add numbers to flags\
                for f=lowerBound, upperBound do \
                    table.insert(flags, tostring(f))\
                end\
            else\
                -- bounds illegal\
                trigger.action.outText(\"+++zne: ignored range <\" .. anElement .. \"> (range)\", 30)\
            end\
        else\
            -- single number\
            f = dcsCommon.trim(anElement) -- DML flag upgrade: accept strings tonumber(anElement)\
            if f then \
                table.insert(flags, f)\
\
            else \
                trigger.action.outText(\"+++zne: ignored element <\" .. anElement .. \"> (single)\", 30)\
            end\
        end\
    end\
    if cfxZones.verbose then \
        trigger.action.outText(\"+++zne: <\" .. #flags .. \"> flags total\", 30)\
    end \
    return flags\
end\
\
--\
-- ===================\
-- PROPERTY PROCESSING\
-- =================== \
--\
\
function cfxZones.getAllZoneProperties(theZone, caseInsensitive) -- return as dict \
    if not caseInsensitive then caseInsensitive = false end \
    if not theZone then return {} end \
    \
    local dcsProps = theZone.properties -- zone properties in dcs format \
    local props = {}\
    -- dcs has all properties as array with values .key and .value \
    -- so convert them into a dictionary \
    for i=1, #dcsProps do \
        local theProp = dcsProps[i]\
        local theKey = \"dummy\"\
        if string.len(theProp.key) > 0 then theKey = theProp.key end \
        if caseInsensitive then theKey = theKey:upper() end \
        props[theKey] = theProp.value\
    end\
    return props \
end\
\
function cfxZones.extractPropertyFromDCS(theKey, theProperties)\
-- trim\
    theKey = dcsCommon.trim(theKey) \
--    make lower case conversion if not case sensitive\
    if not cfxZones.caseSensitiveProperties then \
        theKey = string.lower(theKey)\
    end\
\
-- iterate all keys and compare to what we are looking for     \
    for i=1, #theProperties do\
        local theP = theProperties[i]\
         \
        local existingKey = dcsCommon.trim(theP.key)  \
        if not cfxZones.caseSensitiveProperties then \
            existingKey = string.lower(existingKey)\
        end\
        if existingKey == theKey then \
            return theP.value\
        end\
        \
        -- now check after removing all blanks \
        existingKey = dcsCommon.removeBlanks(existingKey)\
        if existingKey == theKey then \
            return theP.value\
        end\
    end\
    return nil \
end\
\
function cfxZones.getZoneProperty(cZone, theKey)\
    if not cZone then \
        trigger.action.outText(\"+++zone: no zone in getZoneProperty\", 30)\
--        breek.here.noew = 1\
        return nil\
    end \
    if not theKey then \
        trigger.action.outText(\"+++zone: no property key in getZoneProperty for zone \" .. cZone.name, 30)\
--        breakme.here = 1\
        return \
    end    \
\
    local props = cZone.properties\
    local theVal = cfxZones.extractPropertyFromDCS(theKey, props)\
    return theVal\
end\
\
function cfxZones.getStringFromZoneProperty(theZone, theProperty, default)\
    \
    if not default then default = \"\" end\
    local p = cfxZones.getZoneProperty(theZone, theProperty)\
    if not p then return default end\
    if type(p) == \"string\" then \
        p = dcsCommon.trim(p)\
        if p == \"\" then p = default end \
        return p\
    end\
    return default -- warning. what if it was a number first?\
end\
\
function cfxZones.getMinMaxFromZoneProperty(theZone, theProperty)\
    local p = cfxZones.getZoneProperty(theZone, theProperty)\
    local theNumbers = dcsCommon.splitString(p, \" \")\
\
    return tonumber(theNumbers[1]), tonumber(theNumbers[2])\
    \
end\
\
function cfxZones.randomInRange(minVal, maxVal)\
    if maxVal < minVal then \
        local t = minVal\
        minVal = maxVal \
        maxVal = t\
    end\
    return cfxZones.randomDelayFromPositiveRange(minVal, maxVal)\
end\
\
function cfxZones.randomDelayFromPositiveRange(minVal, maxVal) \
    if not maxVal then return minVal end \
    if not minVal then return maxVal end \
    local delay = maxVal\
    if minVal > 0 and minVal < delay then \
        -- we want a randomized from time from minTime .. delay\
        local varPart = delay - minVal + 1\
        varPart = dcsCommon.smallRandom(varPart) - 1\
        delay = minVal + varPart\
    end\
    return delay \
end\
\
function cfxZones.getPositiveRangeFromZoneProperty(theZone, theProperty, default, defaultmax)\
    -- reads property as string, and interprets as range 'a-b'. \
    -- if not a range but single number, returns both for upper and lower \
    --trigger.action.outText(\"***Zne: enter with <\" .. theZone.name .. \">: range for property <\" .. theProperty .. \">!\", 30)\
    if not default then default = 0 end \
    if not defaultmax then defaultmax = default end \
    \
    local lowerBound = default\
    local upperBound = defaultmax \
    \
    local rangeString = cfxZones.getStringFromZoneProperty(theZone, theProperty, \"\")\
    if dcsCommon.containsString(rangeString, \"-\") then \
        local theRange = dcsCommon.splitString(rangeString, \"-\")\
        lowerBound = theRange[1]\
        lowerBound = tonumber(lowerBound)\
        upperBound = theRange[2]\
        upperBound = tonumber(upperBound)\
        if lowerBound and upperBound then\
            -- swap if wrong order\
            if lowerBound > upperBound then \
                local temp = upperBound\
                upperBound = lowerBound\
                lowerBound = temp \
            end\
\
        else\
            -- bounds illegal\
            trigger.action.outText(\"+++Zne: illegal range  <\" .. rangeString .. \">, using \" .. default .. \"-\" .. defaultmax, 30)\
            lowerBound = default\
            upperBound = defaultmax \
        end\
    else \
        upperBound = cfxZones.getNumberFromZoneProperty(theZone, theProperty, defaultmax) -- between pulses \
        lowerBound = upperBound\
    end\
\
    return lowerBound, upperBound\
end\
\
function cfxZones.hasProperty(theZone, theProperty) \
    if not theProperty then \
        trigger.action.outText(\"+++zne: WARNING - hasProperty called with nil theProperty for zone <\" .. theZone.name .. \">\", 30)\
        return false \
    end \
    local foundIt = cfxZones.getZoneProperty(theZone, theProperty)\
    if not foundIt then \
        -- check for possible forgotten or exchanged IO flags \
        if string.sub(theProperty, -1) == \"?\" then\
            local lessOp = theProperty:sub(1,-2)\
            if cfxZones.getZoneProperty(theZone, lessOp) ~= nil then \
                trigger.action.outText(\"*** NOTE: \" .. theZone.name .. \"'s property <\" .. lessOp .. \"> may be missing a Query ('?') symbol\", 30)\
            end\
            local lessPlus = lessOp .. \"!\"\
            if cfxZones.getZoneProperty(theZone, lessPlus) ~= nil then \
                trigger.action.outText(\"*** NOTE: \" .. theZone.name .. \"'s property <\" .. lessOp .. \"> may be using '!' instead of '?' for input\", 30)\
            end\
            return false \
        end\
        \
        if string.sub(theProperty, -1) == \"!\" then \
            local lessOp = theProperty:sub(1,-2)\
            if cfxZones.getZoneProperty(theZone, lessOp) ~= nil then \
                trigger.action.outText(\"*** NOTE: \" .. theZone.name .. \"'s property <\" .. lessOp .. \"> may be missing a Bang! ('!') symbol\", 30)\
            end\
            local lessPlus = lessOp .. \"?\"\
            if cfxZones.getZoneProperty(theZone, lessPlus) ~= nil then \
                trigger.action.outText(\"*** NOTE: \" .. theZone.name .. \"'s property <\" .. lessOp .. \"> may be using '!' instead of '?' for input\", 30)\
            end\
            return false \
        end\
        \
        if string.sub(theProperty, -1) == \":\" then \
            local lessOp = theProperty:sub(1,-2)\
            if cfxZones.getZoneProperty(theZone, lessOp) ~= nil then \
                trigger.action.outText(\"*** NOTE: \" .. theZone.name .. \"'s property <\" .. lessOp .. \"> may be missing a colon (':') at end\", 30)\
            end\
            return false \
        end\
        \
        return false \
    end\
    return true \
--    return foundIt ~= nil \
end\
\
function cfxZones.getBoolFromZoneProperty(theZone, theProperty, defaultVal)\
    if not defaultVal then defaultVal = false end \
    if type(defaultVal) ~= \"boolean\" then \
        defaultVal = false \
    end\
\
    if not theZone then \
        trigger.action.outText(\"WARNING: NIL Zone in getBoolFromZoneProperty\", 30)\
        return defaultVal\
    end\
\
\
    local p = cfxZones.getZoneProperty(theZone, theProperty)\
    if not p then return defaultVal end\
\
    -- make sure we compare so default always works when \
    -- answer isn't exactly the opposite\
    p = p:lower() \
    p = dcsCommon.trim(p) \
    if defaultVal == false then \
        -- only go true if exact match to yes or true \
        theBool = false \
        theBool = (p == 'true') or (p == 'yes') or p == \"1\"\
        return theBool\
    end\
    \
    local theBool = true \
    -- only go false if exactly no or false or \"0\"\
    theBool = (p ~= 'false') and (p ~= 'no') and (p ~= \"0\") \
    return theBool\
end\
\
function cfxZones.getCoalitionFromZoneProperty(theZone, theProperty, default)\
    if not default then default = 0 end\
    local p = cfxZones.getZoneProperty(theZone, theProperty)\
    if not p then return default end  \
    if type(p) == \"number\" then -- can't currently really happen\
        if p == 1 then return 1 end \
        if p == 2 then return 2 end \
        return 0\
    end\
    \
    if type(p) == \"string\" then \
        if p == \"1\" then return 1 end \
        if p == \"2\" then return 2 end \
        if p == \"0\" then return 0 end \
        \
        p = p:lower()\
        \
        if p == \"red\" then return 1 end \
        if p == \"blue\" then return 2 end \
        if p == \"neutral\" then return 0 end\
        if p == \"all\" then return 0 end \
        return default \
    end\
    \
    return default \
end\
\
function cfxZones.getNumberFromZoneProperty(theZone, theProperty, default)\
--TODO: trim string \
    if not default then default = 0 end\
    local p = cfxZones.getZoneProperty(theZone, theProperty)\
    p = tonumber(p)\
    if not p then return default else return p end\
end\
\
function cfxZones.getVectorFromZoneProperty(theZone, theProperty, minDims, defaultVal)\
    if not minDims then minDims = 0 end \
    if not defaultVal then defaultVal = 0 end \
    local s = cfxZones.getStringFromZoneProperty(theZone, theProperty, \"\")\
    local sVec = dcsCommon.splitString(s, \",\")\
    local nVec = {}\
    for idx, numString in pairs (sVec) do \
        local n = tonumber(numString)\
        if not n then n = defaultVal end\
        table.insert(nVec, n)\
    end\
    -- make sure vector contains at least minDims values \
    while #nVec < minDims do \
        table.insert(nVec, defaultVal)\
    end\
    \
    return nVec \
end\
\
function cfxZones.getSmokeColorStringFromZoneProperty(theZone, theProperty, default) -- smoke as 'red', 'green', or 1..5\
    if not default then default = \"red\" end \
    local s = cfxZones.getStringFromZoneProperty(theZone, theProperty, default)\
    s = s:lower()\
    s = dcsCommon.trim(s)\
    -- check numbers \
    if (s == \"0\") then return \"green\" end\
    if (s == \"1\") then return \"red\" end\
    if (s == \"2\") then return \"white\" end\
    if (s == \"3\") then return \"orange\" end\
    if (s == \"4\") then return \"blue\" end\
    \
    if s == \"green\" or\
       s == \"red\" or\
       s == \"white\" or\
       s == \"orange\" or\
       s == \"blue\" then return s end\
\
    return default \
end\
\
function cfxZones.getFlareColorStringFromZoneProperty(theZone, theProperty, default) -- smoke as 'red', 'green', or 1..5\
    if not default then default = \"red\" end \
    local s = cfxZones.getStringFromZoneProperty(theZone, theProperty, default)\
    s = s:lower()\
    s = dcsCommon.trim(s)\
    -- check numbers \
    if (s == \"rnd\") then return \"random\" end \
    if (s == \"0\") then return \"green\" end\
    if (s == \"1\") then return \"red\" end\
    if (s == \"2\") then return \"white\" end\
    if (s == \"3\") then return \"yellow\" end\
    if (s == \"-1\") then return \"random\" end  \
    \
    if s == \"green\" or\
       s == \"red\" or\
       s == \"white\" or\
       s == \"yellow\" or \
       s == \"random\" then\
    return s end\
\
    return default \
end\
\
\
--\
-- Zone-based wildcard processing\
-- \
\
-- process <z>\
function cfxZones.processZoneStatics(inMsg, theZone)\
    if theZone then \
        inMsg = inMsg:gsub(\"<z>\", theZone.name)\
    end\
    return inMsg \
end\
\
-- process <t>, <lat>, <lon>, <ele>, <mgrs> \
function cfxZones.processSimpleZoneDynamics(inMsg, theZone, timeFormat, imperialUnits)\
    if not inMsg then return \"<nil inMsg>\" end\
    -- replace <t> with current mission time HMS\
    local absSecs = timer.getAbsTime()-- + env.mission.start_time\
    while absSecs > 86400 do \
        absSecs = absSecs - 86400 -- subtract out all days \
    end\
    if not timeFormat then timeFormat = \"<:h>:<:m>:<:s>\" end \
    local timeString  = dcsCommon.processHMS(timeFormat, absSecs)\
    local outMsg = inMsg:gsub(\"<t>\", timeString)\
    \
    -- replace <lat> with lat of zone point and <lon> with lon of zone point \
    -- and <mgrs> with mgrs coords of zone point \
    local currPoint = cfxZones.getPoint(theZone)\
    local lat, lon = coord.LOtoLL(currPoint)\
    lat, lon = dcsCommon.latLon2Text(lat, lon)\
    local alt = land.getHeight({x = currPoint.x, y = currPoint.z})\
    if imperialUnits then \
        alt = math.floor(alt * 3.28084) -- feet \
    else \
        alt = math.floor(alt) -- meters \
    end \
    outMsg = outMsg:gsub(\"<lat>\", lat)\
    outMsg = outMsg:gsub(\"<lon>\", lon)\
    outMsg = outMsg:gsub(\"<ele>\", alt)\
    local grid = coord.LLtoMGRS(coord.LOtoLL(currPoint))\
    local mgrs = grid.UTMZone .. ' ' .. grid.MGRSDigraph .. ' ' .. grid.Easting .. ' ' .. grid.Northing\
    outMsg = outMsg:gsub(\"<mgrs>\", mgrs)\
    return outMsg\
end \
\
-- process <v: flag>, <rsp: flag> <rrnd>\
function cfxZones.processDynamicValues(inMsg, theZone, msgResponses)\
    -- replace all occurences of <v: flagName> with their values \
    local pattern = \"<v:%s*[%s%w%*%d%.%-_]+>\" -- no list allowed but blanks and * and . and - and _ --> we fail on the other specials to keep this simple \
    local outMsg = inMsg\
    repeat -- iterate all patterns one by one \
        local startLoc, endLoc = string.find(outMsg, pattern)\
        if startLoc then \
            local theValParam = string.sub(outMsg, startLoc, endLoc)\
            -- strip lead and trailer \
            local param = string.gsub(theValParam, \"<v:%s*\", \"\")\
            param = string.gsub(param, \">\",\"\")\
            -- param = dcsCommon.trim(param) -- trim is called anyway\
            -- access flag\
            local val = cfxZones.getFlagValue(param, theZone)\
            val = tostring(val)\
            if not val then val = \"NULL\" end \
            -- replace pattern in original with new val \
            outMsg = string.gsub(outMsg, pattern, val, 1) -- only one sub!\
        end\
    until not startLoc\
    \
    -- now process rsp \
    pattern = \"<rsp:%s*[%s%w%*%d%.%-_]+>\" -- no list allowed but blanks and * and . and - and _ --> we fail on the other specials to keep this simple \
\
    if msgResponses and (#msgResponses > 0) then -- only if this zone has an array\
        --trigger.action.outText(\"enter response proccing\", 30)\
        repeat -- iterate all patterns one by one \
            local startLoc, endLoc = string.find(outMsg, pattern)\
            if startLoc then \
                --trigger.action.outText(\"response: found an occurence\", 30)\
                local theValParam = string.sub(outMsg, startLoc, endLoc)\
                -- strip lead and trailer \
                local param = string.gsub(theValParam, \"<rsp:%s*\", \"\")\
                param = string.gsub(param, \">\",\"\")\
                \
                -- access flag\
                local val = cfxZones.getFlagValue(param, theZone)\
                if not val or (val < 1) then val = 1 end \
                if val > msgResponses then val = msgResponses end \
                \
                val = msgResponses[val]\
                val = dcsCommon.trim(val)\
                -- replace pattern in original with new val \
                outMsg = string.gsub(outMsg, pattern, val, 1) -- only one sub!\
            end\
        until not startLoc\
        \
        -- rnd response \
        local rndRsp = dcsCommon.pickRandom(msgResponses)\
        outMsg = outMsg:gsub (\"<rrnd>\", rndRsp)\
    end\
    \
    return outMsg\
end\
\
-- process <t: flag>\
function cfxZones.processDynamicTime(inMsg, theZone, timeFormat)\
    if not timeFormat then timeFormat = \"<:h>:<:m>:<:s>\" end\
    -- replace all occurences of <t: flagName> with their values \
    local pattern = \"<t:%s*[%s%w%*%d%.%-_]+>\" -- no list allowed but blanks and * and . and - and _ --> we fail on the other specials to keep this simple \
    local outMsg = inMsg\
    repeat -- iterate all patterns one by one \
        local startLoc, endLoc = string.find(outMsg, pattern)\
        if startLoc then \
            local theValParam = string.sub(outMsg, startLoc, endLoc)\
            -- strip lead and trailer \
            local param = string.gsub(theValParam, \"<t:%s*\", \"\")\
            param = string.gsub(param, \">\",\"\")\
            -- access flag\
            local val = cfxZones.getFlagValue(param, theZone)\
            -- use this to process as time value \
            --trigger.action.outText(\"time: accessing <\" .. param .. \"> and received <\" .. val .. \">\", 30)\
            local timeString  = dcsCommon.processHMS(timeFormat, val)\
            \
            if not timeString then timeString = \"NULL\" end \
            -- replace pattern in original with new val \
            outMsg = string.gsub(outMsg, pattern, timeString, 1) -- only one sub!\
        end\
    until not startLoc\
    return outMsg\
end\
\
-- process <lat/lon/ele/mgrs/lle/latlon/alt/vel/hdg/rhdg/type/player: zone/unit>\
function cfxZones.processDynamicLoc(inMsg, imperialUnits, responses)\
    local locales = {\"lat\", \"lon\", \"ele\", \"mgrs\", \"lle\", \"latlon\", \"alt\", \"vel\", \"hdg\", \"rhdg\", \"type\", \"player\"}\
    local outMsg = inMsg\
    local uHead = 0\
    for idx, aLocale in pairs(locales) do \
        local pattern = \"<\" .. aLocale .. \":%s*[%s%w%*%d%.%-_]+>\"\
        repeat -- iterate all patterns one by one \
            local startLoc, endLoc = string.find(outMsg, pattern)\
            if startLoc then\
                local theValParam = string.sub(outMsg, startLoc, endLoc)\
                -- strip lead and trailer \
                local param = string.gsub(theValParam, \"<\" .. aLocale .. \":%s*\", \"\")\
                param = string.gsub(param, \">\",\"\")\
                -- find zone or unit\
                param = dcsCommon.trim(param)\
                local thePoint = nil \
                local tZone = cfxZones.getZoneByName(param)\
                local tUnit = Unit.getByName(param)\
                local spd = 0\
                local angels = 0 \
                local theType = \"<errType>\"\
                local playerName = \"Unknown\"\
                if tZone then\
                    theType = \"Zone\"\
                    playerName = \"?zone?\"\
                    thePoint = cfxZones.getPoint(tZone)\
                    if tZone.linkedUnit and Unit.isExist(tZone.linkedUnit) then \
                        local lU = tZone.linkedUnit\
                        local masterPoint = lU:getPoint()\
                        thePoint.y = masterPoint.y \
                        spd = dcsCommon.getUnitSpeed(lU)\
                        spd = math.floor(spd * 3.6)\
                        uHead = math.floor(dcsCommon.getUnitHeading(tUnit) * 57.2958) -- to degrees.\
                    else \
                        -- since zones always have elevation of 0, \
                        -- now get the elevation from the map \
                        thePoint.y = land.getHeight({x = thePoint.x, y = thePoint.z})\
                    end\
                elseif tUnit then \
                    if Unit.isExist(tUnit) then\
                        theType = tUnit:getTypeName()\
                        if tUnit.getPlayerName and tUnit:getPlayerName() then\
                            playerName = tUnit:getPlayerName()\
                        end\
                        thePoint = tUnit:getPoint()\
                        spd = dcsCommon.getUnitSpeed(tUnit)\
                        -- convert m/s to km/h \
                        spd = math.floor(spd * 3.6)\
                        uHead = math.floor(dcsCommon.getUnitHeading(tUnit) * 57.2958) -- to degrees. \
                    end\
                else \
                    -- nothing to do, remove me.\
                end\
\
                local locString = \"err\"\
                if thePoint then \
                    -- now that we have a point, we can do locale-specific\
                    -- processing. return result in locString\
                    local lat, lon, alt = coord.LOtoLL(thePoint)\
                    lat, lon = dcsCommon.latLon2Text(lat, lon)\
                    angels = math.floor(thePoint.y) \
                    if imperialUnits then \
                        alt = math.floor(alt * 3.28084) -- feet\
                        spd = math.floor(spd * 0.539957) -- km/h to knots    \
                        angels = math.floor(angels * 3.28084)\
                    else \
                        alt = math.floor(alt) -- meters \
                    end \
                    \
                    if angels > 1000 then \
                        angels = math.floor(angels / 100) * 100 \
                    end\
                    \
                    if aLocale == \"lat\" then locString = lat \
                    elseif aLocale == \"lon\" then locString = lon \
                    elseif aLocale == \"ele\" then locString = tostring(alt)\
                    elseif aLocale == \"lle\" then locString = lat .. \" \" .. lon .. \" ele \" .. tostring(alt) \
                    elseif aLocale == \"latlon\" then locString = lat .. \" \" .. lon \
                    elseif aLocale == \"alt\" then locString = tostring(angels) -- don't confuse alt and angels, bad var naming here\
                    elseif aLocale == \"vel\" then locString = tostring(spd)\
                    elseif aLocale == \"hdg\" then locString = tostring(uHead)\
                    elseif aLocale == \"type\" then locString = theType \
                    elseif aLocale == \"player\" then locString = playerName \
                    elseif aLocale == \"rhdg\" and (responses) then \
                        local offset = cfxZones.rspMapper360(uHead, #responses)\
                        locString = dcsCommon.trim(responses[offset])\
                    else \
                        -- we have mgrs\
                        local grid = coord.LLtoMGRS(coord.LOtoLL(thePoint))\
                        locString = grid.UTMZone .. ' ' .. grid.MGRSDigraph .. ' ' .. grid.Easting .. ' ' .. grid.Northing\
                    end\
                end\
                -- replace pattern in original with new val \
                outMsg = string.gsub(outMsg, pattern, locString, 1) -- only one sub!\
            end -- if startloc\
        until not startLoc\
    end -- for all locales \
    return outMsg\
end\
\
function cfxZones.rspMapper360(directionInDegrees, numResponses)\
    -- maps responses around a clock. Clock has 12 'responses' (12, 1, .., 11), \
    -- with the first (12) also mapping to the last half arc \
    -- this method dynamically 'winds' the responses around \
    -- a clock and returns the index of the message to display \
    if numResponses < 1 then numResponses = 1 end \
    directionInDegrees = math.floor(directionInDegrees) \
    while directionInDegrees < 0 do directionInDegrees = directionInDegrees + 360 end \
    while directionInDegrees >= 360 do directionInDegrees = directionInDegrees - 360 end \
    -- now we have 0..360 \
    -- calculate arc per item \
    local arcPerItem = 360 / numResponses\
    local halfArc = arcPerItem / 2\
\
    -- we now map 0..360 to (0-halfArc..360-halfArc) by shifting \
    -- direction by half-arc and clipping back 0..360\
    -- and now we can directly derive the index of the response \
    directionInDegrees = directionInDegrees + halfArc\
    if directionInDegrees >= 360 then directionInDegrees = directionInDegrees - 360 end \
    \
    local index = math.floor(directionInDegrees / arcPerItem) + 1 -- 1 .. numResponses \
    \
    return index \
end\
\
-- replaces dcsCommon with same name \
-- timeFormat is optional, default is \"<:h>:<:m>:<:s>\"\
-- imperialUnits is optional, defaults to meters \
-- responses is an array of string, defaults to {}\
function cfxZones.processStringWildcards(inMsg, theZone, timeFormat, imperialUnits, responses)\
    if not inMsg then return \"<nil inMsg>\" end\
    local formerType = type(inMsg)\
    if formerType ~= \"string\" then inMsg = tostring(inMsg) end\
    if not inMsg then inMsg = \"<inMsg is incompatible type \" .. formerType .. \">\" end\
    local theMsg = inMsg\
    -- process common DCS stuff like /n \
    theMsg = dcsCommon.processStringWildcards(theMsg) -- call old inherited\
    -- process <z>\
    theMsg = cfxZones.processZoneStatics(theMsg, theZone)\
    -- process <t>, <lat>, <lon>, <ele>, <mgrs>\
    theMsg = cfxZones.processSimpleZoneDynamics(theMsg, theZone, timeFormat, imperialUnits)\
    -- process <v: flag>, <rsp: flag> <rrnd>\
    theMsg = cfxZones.processDynamicValues(theMsg, theZone, responses)\
    -- process <t: flag>\
    theMsg = cfxZones.processDynamicTime(theMsg, theZone, timeFormat)\
    -- process <lat/lon/ele/mgrs/lle/latlon/alt/vel/hdg/rhdg/type/player: zone/unit>\
    theMsg = cfxZones.processDynamicLoc(theMsg, imperialUnits, responses)\
\
    return theMsg\
end\
\
--\
-- ============\
-- MOVING ZONES \
-- ============ \
-- \
-- Moving zones contain a link to their unit\
-- they are always located at an offset (x,z) or delta, phi \
-- to their master unit. delta phi allows adjustment for heading\
-- The cool thing about moving zones in cfx is that they do not\
-- require special handling, they are always updated \
-- and work with 'pointinzone' etc automatically\
\
-- Always works on cfx Zones, NEVER on DCS zones.\
--\
-- requires that readFromDCS has been done\
--\
function cfxZones.getDCSOrigin(aZone)\
    local o = {}\
    o.x = aZone.dcsOrigin.x\
    o.y = 0\
    o.z = aZone.dcsOrigin.z \
    return o\
end\
\
function cfxZones.getLinkedUnit(theZone)\
    if not theZone then return nil end \
    if not theZone.linkedUnit then return nil end \
    if not Unit.isExist(theZone.linkedUnit) then return nil end \
    return theZone.linkedUnit \
end\
\
function cfxZones.getPoint(aZone, getHeight) -- always works, even linked, returned point can be reused\
-- returned y (when using getHeight) is that of the land, else 0 \
    if not getHeight then getHeight = false end \
    if aZone.linkedUnit then \
        local theUnit = aZone.linkedUnit\
        -- has a link. is link existing?\
        if Unit.isExist(theUnit) then \
            -- updates zone position \
            cfxZones.centerZoneOnUnit(aZone, theUnit)\
            local dx = aZone.dx\
            local dy = aZone.dy\
            if aZone.useHeading then \
                dx, dy = cfxZones.calcHeadingOffset(aZone, theUnit)\
            end\
            cfxZones.offsetZone(aZone, dx, dy)\
        end\
    end\
    local thePos = {}\
    thePos.x = aZone.point.x\
    thePos.z = aZone.point.z\
    if not getHeight then \
        thePos.y = 0 -- aZone.y \
    else \
        thePos.y = land.getHeight({x = thePos.x, y = thePos.z})\
    end\
    \
    return thePos \
end\
\
function cfxZones.linkUnitToZone(theUnit, theZone, dx, dy) -- note: dy is really Z, don't get confused!!!!\
    theZone.linkedUnit = theUnit\
    if not dx then dx = 0 end\
    if not dy then dy = 0 end \
    theZone.dx = dx\
    theZone.dy = dy \
    theZone.rxy = math.sqrt(dx * dx + dy * dy) -- radius \
    local unitHeading = dcsCommon.getUnitHeading(theUnit)\
    local bearingOffset = math.atan2(dy, dx) -- rads \
    if bearingOffset < 0 then bearingOffset = bearingOffset + 2 * 3.141592 end \
\
    local dPhi = bearingOffset - unitHeading\
    if dPhi < 0 then dPhi = dPhi + 2 * 3.141592 end\
    if (theZone.verbose and theZone.useHeading) then \
        trigger.action.outText(\"Zone is at <\" .. math.floor(57.2958 * dPhi) .. \"> relative to unit heading\", 30)\
    end\
    theZone.dPhi = dPhi -- constant delta between unit heading and \
    -- direction to zone \
    theZone.uHdg = unitHeading -- original unit heading to turn other \
    -- units if need be \
    --trigger.action.outText(\"Link setup: dx=<\" .. dx .. \">, dy=<\" .. dy .. \"> unit original hdg = <\" .. math.floor(57.2958 * unitHeading)  .. \">\", 30)\
end\
\
function cfxZones.zonesLinkedToUnit(theUnit) -- returns all zones linked to this unit \
    if not theUnit then return {} end \
    local linkedZones = {}\
    for idx, theZone in pairs (cfxZones.zones) do \
        if theZone.linkedUnit == theUnit then \
            table.insert(linkedZones, theZone)\
        end\
    end\
    return linkedZones\
end\
\
function cfxZones.calcHeadingOffset(aZone, theUnit)\
    -- recalc dx and dy based on ry and current heading \
    -- since 0 degrees is [0,1] = [0,r] the calculation of \
    -- rotated coords can be simplified from \
    -- xr = x cos phi - y sin phi = -r sin phi\
    -- yr = y cos phi + x sin phi = r cos phi \
    local unitHeading = dcsCommon.getUnitHeading(theUnit)\
    -- add heading offset \
    local zoneBearing = unitHeading + aZone.dPhi \
    if zoneBearing > 2 * 3.141592 then zoneBearing = zoneBearing - 2 * 3.141592 end \
                    \
    -- in DCS, positive x is north (wtf?) and positive z is east \
    local dy = (-aZone.rxy) * math.sin(zoneBearing)\
    local dx = aZone.rxy * math.cos(zoneBearing)\
    \
    --trigger.action.outText(\"zone bearing is \" .. math.floor(zoneBearing * 57.2958) .. \" dx = <\" .. dx .. \"> , dy = <\" .. dy .. \">\", 30)\
    return dx, -dy -- note: dy is z coord!!!!\
end\
\
function cfxZones.updateMovingZones()\
    cfxZones.updateSchedule = timer.scheduleFunction(cfxZones.updateMovingZones, {}, timer.getTime() + 1/cfxZones.ups)\
    -- simply scan all cfx zones for the linkName property, and if present\
    -- update the zone's points\
    for aName,aZone in pairs(cfxZones.zones) do\
        -- only do this if ther is a linkName property, \
        -- else this zone isn't linked. link name is harmonized from \
        -- both linkUnit non-DML and linedUnit DML        \
        if aZone.linkName then \
            if aZone.linkBroken then \
                -- try to relink \
                cfxZones.initLink(aZone)\
            else --if aZone.linkName then  \
                -- always re-acquire linkedUnit via Unit.getByName()\
                -- this way we gloss over any replacements via spawns\
                aZone.linkedUnit = Unit.getByName(aZone.linkName)\
            end\
            \
            if aZone.linkedUnit then \
                local theUnit = aZone.linkedUnit\
                -- has a link. is link existing?\
                if theUnit:isExist() then \
                    cfxZones.centerZoneOnUnit(aZone, theUnit)\
                    local dx = aZone.dx \
                    local dy = aZone.dy -- this is actually z \
                    if aZone.useHeading then \
                        dx, dy = cfxZones.calcHeadingOffset(aZone, theUnit)\
                    end\
                    cfxZones.offsetZone(aZone, dx, dy)\
                else \
                    -- we lost link (track level)\
                    aZone.linkBroken = true \
                    aZone.linkedUnit = nil \
                end\
            else \
                -- we lost link (top level)\
                aZone.linkBroken = true \
                aZone.linkedUnit = nil \
            end\
        else \
            -- this zone isn't linked\
        end\
    end\
end\
\
function cfxZones.initLink(theZone)\
\
    theZone.linkBroken = true \
    theZone.linkedUnit = nil \
    theUnit = Unit.getByName(theZone.linkName)\
    if theUnit then\
\
        local dx = 0\
        local dz = 0\
        if theZone.useOffset or theZone.useHeading then \
            local A = cfxZones.getDCSOrigin(theZone)\
            local B = theUnit:getPoint()\
            local delta = dcsCommon.vSub(A,B) \
            dx = delta.x \
            dz = delta.z\
        end\
        cfxZones.linkUnitToZone(theUnit, theZone, dx, dz) -- also sets theZone.linkedUnit\
\
        if theZone.verbose then \
            trigger.action.outText(\"Link established for zone <\" .. theZone.name .. \"> to unit <\" .. theZone.linkName .. \">: dx=<\" .. math.floor(dx) .. \">, dz=<\" .. math.floor(dz) .. \"> dist = <\" .. math.floor(math.sqrt(dx * dx + dz * dz)) .. \">\" , 30)\
        end \
        theZone.linkBroken = nil \
\
    else \
        if theZone.verbose then \
            trigger.action.outText(\"Linked unit: no unit <\" .. theZone.linkName .. \"> to link <\" .. theZone.name .. \"> to\", 30)\
        end\
    end\
end\
\
function cfxZones.startMovingZones()\
    -- read all zones, and look for a property called 'linkedUnit'\
    -- which will make them a linked zone if there is a unit that exists\
    -- also suppors 'useOffset' and 'useHeading'\
    for aName,aZone in pairs(cfxZones.zones) do\
        \
        local lU = nil \
        -- check if DCS zone has the linkUnit new attribute introduced in \
        -- late 2022 with 2.8\
        if aZone.dcsZone.linkUnit then \
            local theID = aZone.dcsZone.linkUnit \
            lU = dcsCommon.getUnitNameByID(theID)\
            if not lU then \
                trigger.action.outText(\"WARNING: Zone <\" .. aZone.name .. \">: cannot resolve linked unit ID <\" .. theID .. \">\", 30)\
                lU = \"***DML link err***\"\
            end\
        elseif cfxZones.hasProperty(aZone, \"linkedUnit\") then \
            lU = cfxZones.getZoneProperty(aZone, \"linkedUnit\")\
        end\
        \
        -- sanity check \
        if aZone.dcsZone.linkUnit and cfxZones.hasProperty(aZone, \"linkedUnit\") then \
            trigger.action.outText(\"WARNING: Zone <\" .. aZone.name .. \"> has dual unit link definition. Will use link to unit <\" .. lU .. \">\", 30)\
        end\
        \
        if lU then \
            aZone.linkName = lU\
            aZone.useOffset = cfxZones.getBoolFromZoneProperty(aZone, \"useOffset\", false)\
            aZone.useHeading = cfxZones.getBoolFromZoneProperty(aZone, \"useHeading\", false)\
            \
            cfxZones.initLink(aZone)\
\
        end\
        \
    end\
end\
\
\
--\
-- ===========\
-- INIT MODULE\
-- ===========\
--\
\
function cfxZones.initZoneVerbosity()\
    for aName,aZone in pairs(cfxZones.zones) do\
        -- support for zone-local verbose flag \
        aZone.verbose = cfxZones.getBoolFromZoneProperty(aZone, \"verbose\", false)\
    end\
end\
\
function cfxZones.init()\
    -- read all zones into my own db\
    cfxZones.readFromDCS(true) -- true: erase old\
\
    -- pre-read zone owner for all zones\
    local pZones = cfxZones.zonesWithProperty(\"owner\")\
    for n, aZone in pairs(pZones) do\
        aZone.owner = cfxZones.getCoalitionFromZoneProperty(aZone, \"owner\", 0)\
    end\
        \
    -- enable all zone's verbose flags if present\
    -- must be done BEFORE we start the moving zones \
    cfxZones.initZoneVerbosity()\
    \
    -- now initialize moving zones\
    cfxZones.startMovingZones()\
    cfxZones.updateMovingZones() -- will auto-repeat\
    \
    trigger.action.outText(\"cf/x Zones v\".. cfxZones.version .. \": loaded, zones:\" .. dcsCommon.getSizeOfTable(cfxZones.zones), 30)\
\
end\
\
-- get everything rolling\
cfxZones.init()\
",
                    ["predicate"] = "a_do_script",
                }, -- end of [2]
                [3] = 
                {
                    ["text"] = "-- cfxCommander - issue dcs commands to groups etc\
--\
-- supports scheduling\
-- *** EXTENDS ZONES: 'pathing' attribute \
--\
cfxCommander = {}\
cfxCommander.version = \"1.1.3\"\
--[[-- VERSION HISTORY\
 - 1.0.5 - createWPListForGroupToPointViaRoads: detect no road found \
 - 1.0.6 - build in more group checks in assign wp list \
         - added sanity checks for doScheduledTask\
         - assignWPListToGroup now can schedule tasks \
         - makeGroupGoThere supports scheduling\
         - makeGroupGoTherePreferringRoads supports scheduling \
         - scheduleTaskForGroup supports immediate execution\
         - makeGroupHalt\
 - 1.0.7 - warning if road shorter than direct\
         - forceOffRoad option\
         - noRoadsAtAll option \
 - 1.1.0 - load libs \
         - pathing zones. Currently only supports \
         - offroad to override road-usage\
         - pathing zones are overridden by noRoadsAtAll\
         - CommanderConfig zones \
 - 1.1.1 - default pathing for pathing zone is normal, not offroad \
 - 1.1.2 - makeGroupTransmit \
         - makeGroupStopTransmitting\
         - verbose check before path warning\
         - added delay defaulting for most scheduling functions \
 - 1.1.3 - isExist() guard improvements for multiple methods\
         - cleaned up comments\
 \
--]]--\
\
cfxCommander.requiredLibs = {\
    \"dcsCommon\", -- common is of course needed for everything\
    \"cfxZones\", -- zones management for pathing zones \
}\
\
cfxCommander.verbose = false \
cfxCommander.forceOffRoad = true -- if true, vehicles path follow roads, but may drive offroad (they follow vertex points from path but not the road as they are still commanded 'offroad')\
cfxCommander.noRoadsAtAll = true  -- if true, always go direct, overrides forceOffRoad when true. Always a two-point path. Here, there, bang! \
cfxCommander.pathZones = {} -- zones that can override road settings\
\
--\
-- path zone\
--\
function cfxCommander.processPathingZone(aZone) -- process attribute and add to zone\
    local pathing = cfxZones.getStringFromZoneProperty(aZone, \"pathing\", \"normal\") -- must be \"offroad\" to force offroad\
    pathing = pathing:lower()\
    -- currently no validation of attribute \
    aZone.pathing = pathing\
end \
\
function cfxCommander.addPathingZone(aZone)\
    table.insert(cfxCommander.pathZones, aZone)\
end \
\
function cfxCommander.hasPathZoneFor(here, there)\
    for idx, aZone in pairs(cfxCommander.pathZones) do \
        if cfxZones.pointInZone(here, aZone) then return aZone end \
        if cfxZones.pointInZone(there, aZone) then return aZone end\
    end\
    return nil\
end\
\
--\
-- Config Zone Reading if present \
--\
function cfxCommander.readConfigZone()\
    -- note: must match exactly!!!!\
    local theZone = cfxZones.getZoneByName(\"CommanderConfig\") \
    if not theZone then \
        trigger.action.outText(\"+++cmdr: no config zone!\", 30) \
        return \
    end \
    \
    trigger.action.outText(\"+++cmdr: found config zone!\", 30) \
    \
    cfxCommander.verbose = cfxZones.getBoolFromZoneProperty(theZone, \"verbose\", false)\
    cfxCommander.forceOffRoad = cfxZones.getBoolFromZoneProperty(theZone, \"forceOffRoad\", false) -- if true, vehicles path follow roads, but may drive offroad\
    cfxCommander.noRoadsAtAll = cfxZones.getBoolFromZoneProperty(theZone, \"noRoadsAtAll\", false)\
\
end\
\
--\
-- Options are key, value pairs. Scheduler when you are creating groups\
-- \
\
function cfxCommander.doOption(data) \
    if cfxCommander.verbose then \
        trigger.action.outText(\"Commander: setting option \" .. data.key .. \" --> \" .. data.value, 30)\
    end\
\
    local theController = data.group:getController()\
    theController:setOption(data.key, data.value)\
end\
\
function cfxCommander.scheduleOptionForGroup(group, key, value, delay) \
    local data = {}\
    if not delay then delay = 0.1 end \
    data.group = group\
    data.key = key\
    data.value = value \
    timer.scheduleFunction(cfxCommander.doOption, data, timer.getTime() + delay)\
end\
\
--\
-- performCommand is a special version of issuing a command\
-- that can be easily schduled by pushing the commandData on \
-- the stack with scheduling it \
-- group or name must be filled to get the group,\
-- and the command table is what is going to be passed to the setCommand\
-- commands are given in an array, so you can stack commands \
function cfxCommander.performCommands(commandData)\
    -- see if we have a group\
    if not commandData.group then \
        commandData.group = Group.getByName(commandData.name) -- better be inited!\
    end\
    -- get the AI\
    local theController = commandData.group:getController()\
    for i=1, #commandData.commands do\
        if cfxCommander.verbose then \
            trigger.action.outText(\"Commander: performing \" .. commandData.commands[i].id, 30)\
        end\
        theController:setCommand(commandData.commands[i])\
    end\
    \
    return nil -- a timer called us, so we return no desire to be rescheduled\
end\
\
function cfxCommander.scheduleCommands(data, delay)\
    if not delay then delay = 1 end \
    timer.scheduleFunction(cfxCommander.performCommands, data, timer.getTime() + delay)\
end\
\
function cfxCommander.scheduleSingleCommand(group, command, delay) \
    if not delay then delay = 1 end \
    local data = createCommandDataTableFor(group)\
    cfxCommander.addCommand(data, command)\
    cfxCommander.scheduleCommands(data, delay)\
end\
\
\
function cfxCommander.createCommandDataTableFor(group, name)\
    local cD = {}\
    if not group then \
        cD.name = name\
    else\
        cD.group = group\
    end\
    cD.commands={}\
    return cD\
end\
\
function cfxCommander.addCommand(theCD, theCommand)\
    if not theCD then return end \
    if not theCommand then return end \
    \
    table.insert(theCD.commands, theCommand)\
end\
\
function cfxCommander.createSetFrequencyCommand(freq, modulator)\
    local theCmd = {}\
    if not freq then freq = 100 end \
    if not modulator then modulator = 0 end -- AM = 0, default\
    theCmd.id = 'SetFrequency'\
    theCmd.params = {}\
    theCmd.params.frequency = freq * 10000 -- 88 --> 880000. 124 --> 1.24 MHz\
    theCmd.params.modulation = modulator\
    return theCmd\
end\
\
-- oneShot is optional. if present and anything but false, will cause message to \
-- me sent only once, no loops\
function cfxCommander.createTransmissionCommand(filename, oneShot)\
    local looping = true\
    if not filename then filename = \"dummy\" end \
    if oneShot then looping = false end\
    local theCmd = {}\
    theCmd.id = 'TransmitMessage'\
    theCmd.params = {}\
    theCmd.params.loop = looping\
    theCmd.params.file = \"l10n/DEFAULT/\" .. filename -- need to prepend the resource string\
    return theCmd\
end\
\
function cfxCommander.createStopTransmissionCommand()\
    local theCmd = {}\
    theCmd.id = 'stopTransmission'\
    theCmd.params = {}\
    return theCmd\
end\
\
--\
-- tasks\
-- \
\
function cfxCommander.doScheduledTask(data) \
    if cfxCommander.verbose then \
        trigger.action.outText(\"Commander: setting task \" .. data.task.id .. \" for group \" .. data.group:getName(), 30)\
    end\
    local theGroup = data.group \
    if not theGroup then return end \
    if not Group.isExist(theGroup) then return end \
--    if not theGroup.isExist then return end\
    \
    local theController = theGroup:getController()\
    theController:pushTask(data.task)\
end\
\
function cfxCommander.scheduleTaskForGroup(group, task, delay)\
    if not delay then delay = 0 end \
    local data = {}\
    data.group = group\
    data.task = task\
    if delay < 0.001 then \
        cfxCommander.doScheduledTask(data) -- immediate execution\
        return \
    end\
    timer.scheduleFunction(cfxCommander.doScheduledTask, data, timer.getTime() + delay)\
end\
\
function cfxCommander.createAttackGroupCommand(theGroupToAttack)\
    local task = {}\
    task.id = 'AttackGroup'\
    task.params = {}\
    task.params.groupID = theGroupToAttack:getID()\
    return task\
end\
\
function cfxCommander.createEngageGroupCommand(theGroupToAttack)\
    local task = {}\
    task.id = 'EngageGroup'\
    task.params = {}\
    task.params.groupID = theGroupToAttack:getID()\
    return task\
end\
\
--\
-- waypoints, routes etc \
--\
\
-- basic waypoint is for ground units. point can be xyz or xy \
function cfxCommander.createBasicWaypoint(point, speed, formation)\
    local wp = {}\
    wp.x = point.x\
    -- support xyz and xy format\
    if point.z then \
        wp.y = point.z\
    else\
        wp.y = point.y\
    end\
    \
    if not speed then speed = 6 end -- 6 m/s = 20 kph\
    wp.speed = speed \
    \
    if cfxCommander.forceOffRoad then \
        formation = \"Off Road\"\
    end\
    \
    if not formation then formation = \"Off Road\" end\
    -- legal formations:\
    -- Off road\
    -- On Road -- second letter upper case?\
    -- Cone \
    -- Rank\
    -- Diamond\
    -- Vee\
    -- EchelonR\
    -- EchelonL\
    wp.action = formation -- silly name, but that's how ME does it\
    wp.type = 'Turning Point'\
    return wp\
\
end\
\
function cfxCommander.buildTaskFromWPList(wpList)\
    -- build the task that will make a group follow the WP list\
    -- we do this by creating a \"Mission\" task around the WP List\
    -- WP list is consumed by this action\
    local missionTask = {}\
    missionTask.id = \"Mission\"\
    missionTask.params = {}\
    missionTask.params.route = {}\
    missionTask.params.route.points=wpList\
    return missionTask\
end\
\
function cfxCommander.assignWPListToGroup(group, wpList, delay)\
    if not delay then delay = 0 end \
    if not group then return end \
    if type(group) == 'string' then -- group name, nice mist trick \
        group = Group.getByName(group)\
    end\
    if not group then return end \
    if not Group.isExist(group) then return end \
    \
    local theTask = cfxCommander.buildTaskFromWPList(wpList)\
    local ctrl = group:getController()\
\
--[[--\
    if delay < 0.001 then -- immediate action\
        if ctrl then\
            ctrl:setTask(theTask)\
        end\
    else \
        -- delay execution of this command by the specified amount \
        -- of seconds \
        cfxCommander.scheduleTaskForGroup(group, theTask, delay)\
    end\
--]]--\
    cfxCommander.scheduleTaskForGroup(group, theTask, delay)\
end\
\
function cfxCommander.createWPListForGroupToPoint(group, point, speed, formation)\
    if type(group) == 'string' then -- group name\
        group = Group.getByName(group)\
    end\
\
    local wpList = {}\
    -- here we are, and we want to go there. In DCS, this means that\
    -- we need to create a wp list consisting of here and there\
    local here = dcsCommon.getGroupLocation(group)\
    local wpHere = cfxCommander.createBasicWaypoint(here, speed, formation)\
    local wpThere = cfxCommander.createBasicWaypoint(point, speed, formation)\
    wpList[1] = wpHere\
    wpList[2] = wpThere\
    return wpList\
end\
\
-- make a ground units group head to a waypoint by replacing the entire mission\
-- with a two-waypoint lsit from (here) to there at speed and formation. formation\
-- default is 'off road'\
function cfxCommander.makeGroupGoThere(group, there, speed, formation, delay)\
    if not delay then delay = 0 end \
    if type(group) == 'string' then -- group name\
        group = Group.getByName(group)\
    end\
    local wp = cfxCommander.createWPListForGroupToPoint(group, there, speed, formation)\
    \
    cfxCommander.assignWPListToGroup(group, wp, delay)\
end\
\
function cfxCommander.calculatePathLength(roadPoints)\
    local totalLen = 0\
    if #roadPoints < 2 then return 0 end\
    for i=1, #roadPoints-1 do\
        totalLen = totalLen + dcsCommon.dist(roadPoints[i], roadPoints[i+1])\
    end\
    return totalLen\
end\
\
-- make ground units go from here (group location) to there, using roads if possible\
function cfxCommander.createWPListForGroupToPointViaRoads(group, point, speed)\
    if type(group) == 'string' then -- group name\
        group = Group.getByName(group)\
    end\
\
    local wpList = {}\
    -- here we are, and we want to go there. In DCS, this means that\
    -- we need to create a wp list consisting of here and there\
    -- when going via roads, we add to more wayoints:\
    -- go on-roads and leaveRoads. \
    -- only if we can get these two additional points, we do that, else we \
    -- fall back to direct route \
    \
    local here = dcsCommon.getGroupLocation(group)\
\
    -- now generate a list of all points from here to there that uses roads\
    local rawRoadPoints = land.findPathOnRoads('roads', here.x, here.z, point.x, point.z)\
    -- this is the entire path. calculate the length and make \
    -- sure that path on-road isn't more than twice as long \
    -- that can happen if a bridge is out or we need to go around a hill\
    if not rawRoadPoints or #rawRoadPoints<3 then \
        trigger.action.outText(\"+++ no roads leading there. Taking direct approach\", 30)\
        return cfxCommander.createWPListForGroupToPoint(group, point, speed)\
    end\
    \
    local pathLength = cfxCommander.calculatePathLength(rawRoadPoints)\
    local direct = dcsCommon.dist(here, point)\
    if pathLength < direct and cfxCommander.verbose then \
        trigger.action.outText(\"+++dcsC: WARNING road path (\" .. pathLength .. \") shorter than direct route(\" .. direct .. \"), will not path correctly\", 30)\
    end\
    \
    if pathLength > (2 * direct) then \
        -- road takes too long, take direct approach\
        --trigger.action.outText(\"+++ road path (\" .. pathLength .. \") > twice direct route(\" .. direct .. \"), commencing direct off-road\", 30)\
        return cfxCommander.createWPListForGroupToPoint(group, point, speed)\
    end\
    \
    --trigger.action.outText(\"+++ \".. group:getName() .. \": choosing road path l=\" .. pathLength .. \" over direct route d=\" .. direct, 30)\
    \
    -- if we are here, the road trip is valid \
    for idx, wp in pairs(rawRoadPoints) do \
        -- createBasic... supports w.xy format\
        local theNewWP = cfxCommander.createBasicWaypoint(wp, speed, \"On Road\") -- force off road for better compatibility?\
        table.insert(wpList, theNewWP)\
    end\
    \
    \
    \
    -- now make first and last entry OFF Road\
    local wpc = wpList[1]\
    wpc.action = \"Off Road\"\
    wpc = wpList[#wpList]\
    wpc.action = \"Off Road\"\
\
    return wpList\
end\
\
function cfxCommander.makeGroupGoTherePreferringRoads(group, there, speed, delay)\
    if type(group) == 'string' then -- group name\
        group = Group.getByName(group)\
    end\
    if not delay then delay = 0 end \
\
\
    if cfxCommander.noRoadsAtAll then \
        -- we don't even follow roads, completely forced off\
        cfxCommander.makeGroupGoThere(group, there, speed, \"Off Road\", delay)\
        return \
    end\
\
    -- see if we have an override situation \
    -- for one of the two points where a pathing Zone \
    -- overrides the roads setting \
    if #cfxCommander.pathZones > 0 then  \
        local here = dcsCommon.getGroupLocation(group)\
        local oRide = cfxCommander.hasPathZoneFor(here, there)\
        if oRide and oRide.pathing == \"offroad\" then \
            -- yup, override road preference\
            cfxCommander.makeGroupGoThere(group, there, speed, \"Off Road\", delay)\
            return \
        end\
    end\
\
    -- viaRoads will only use roads if the road trip isn't more than twice \
    -- as long as the direct route \
    local wp = cfxCommander.createWPListForGroupToPointViaRoads(group, there, speed)\
    cfxCommander.assignWPListToGroup(group, wp, delay)\
end\
\
\
function cfxCommander.makeGroupHalt(group, delay)\
    if not group then return end \
    if not Group.isExist(group) then return end \
    if not delay then delay = 0 end \
    local theTask = {id = 'Hold', params = {}}\
    cfxCommander.scheduleTaskForGroup(group, theTask, delay)\
end\
\
function cfxCommander.makeGroupTransmit(group, tenKHz, filename, oneShot, delay)\
    if not group then return end \
    if not tenKHz then tenKHz = 20 end -- default to 200KHz\
    if not delay then delay = 1.0 end \
    if not filename then return end \
    if not oneShot then oneShot = false end \
    \
    -- now build the transmission command\
    local theCommands = cfxCommander.createCommandDataTableFor(group)\
    local cmd = cfxCommander.createSetFrequencyCommand(tenKHz) -- freq in 10000 Hz\
    cfxCommander.addCommand(theCommands, cmd)\
    cmd = cfxCommander.createTransmissionCommand(filename, oneShot)\
    cfxCommander.addCommand(theCommands, cmd)\
    cfxCommander.scheduleCommands(theCommands, delay)\
end \
\
function cfxCommander.makeGroupStopTransmitting(group, delay)\
    if not delay then delay = 1 end \
    if not group then return end \
    local theCommands = cfxCommander.createCommandDataTableFor(group)\
    local cmd = cfxCommander.createStopTransmissionCommand()\
    cfxCommander.addCommand(theCommands, cmd)\
    cfxCommander.scheduleCommands(theCommands, delay)\
end\
\
\
function cfxCommander.start()\
    -- make sure we have loaded all relevant libraries \
    if not dcsCommon.libCheck(\"cfx Commander\", cfxCommander.requiredLibs) then \
        trigger.action.outText(\"cf/x Commander aborted: missing libraries\", 30)\
        return false \
    end\
    \
    -- identify and process all 'pathing' zones\
    local pathZones = cfxZones.getZonesWithAttributeNamed(\"pathing\")\
    \
    -- now create a spawner for all, add them to the spawner updater, and spawn for all zones that are not\
    -- paused \
    for k, aZone in pairs(pathZones) do \
        cfxCommander.processPathingZone(aZone) -- process attribute and add to zone\
        cfxCommander.addPathingZone(aZone) -- remember it so we can smoke it\
    end\
    \
    -- read config overides \
    cfxCommander.readConfigZone()\
    \
    return true\
end\
\
if cfxCommander.start() then \
    trigger.action.outText(\"cfxCommander v\" .. cfxCommander.version .. \" loaded\", 30)\
else \
    trigger.action.outText(\"+++cfxCommander load FAILED\", 30)\
    cfxCommander = nil\
end\
\
--[[-- known issues\
\
- troops remain motionless until all are repaired or produced after cature\
- long roads / roads not taken in persia \
- all troops red and blue become motionless when one zone is occupied\
- after capture, the troop capturing remains, all others can go on. one will always remain there \
- rethink the factor to add to road, and simply add 100m \
\
 TODO: break long distances into smaller paths, and gravitate towards pathing zones if they have a 'gravitate' or similar attribute \
--]]--\
",
                    ["predicate"] = "a_do_script",
                }, -- end of [3]
                [4] = 
                {
                    ["text"] = "cfxGroundTroops = {}\
cfxGroundTroops.version = \"1.7.8\"\
cfxGroundTroops.ups = 1\
cfxGroundTroops.verbose = false \
cfxGroundTroops.requiredLibs = {\
    \"dcsCommon\", -- common is of course needed for everything\
                 -- pretty stupid to check for this since we \
                 -- need common to invoke the check, but anyway\
    \"cfxCommander\", -- generic data module for weight \
    -- cfxOwnedZones is optional \
}\
-- ground troops: a module to manage ground toops. makes groups of ground troops\
-- patrol and engage enemies and signal idle\
-- understands cfxOwnedZones orders 'attackOwnedZone' and will re-direct\
-- troops when a zone was captured by interacting with cfxOwnedZones to \
-- find the nearest non-owned zone and direct the group there \
\
-- USAGE\
-- Allocate a group in game and issue them marching orders towars a goal \
-- then createGroundTroops to allocate a structure used by this \
-- module and addTroopsToPool to have them then managed by this \
-- module \
\
cfxGroundTroops.deployedTroops = {} -- indexed by group name \
\
--[[--\
 version history\
   1.3.0 - added \"wait-\" prefix to have toops do nothing \
         - added lazing \
   1.3.1 - sound for lazing msg is \"UI_SCI-FI_Tone_Bright_Dry_20_stereo.wav\"\
         - lazing --> lasing in text \
   1.3.2 - set ups to 2 \
   1.4.0 - queued updates except for lazers \
   1.4.1 - makeTroopsEngageZone now issues hold before moving on 5 seconds later\
         - getTroopReport\
           - include size of group \
   1.4.2 - uses unitIsInfantry from dcsCommon \
   1.5.0 - new scheduled updates per troop to reduce processor load \
         - tiebreak code \
   1.5.1 - small bugfix in scheduled code \
   1.5.2 - checkSchedule \
         - speed warning in scheduler\
         - go off road when speed warning too much \
   1.5.3 - monitor troops \
         - managed queue for ground troops \
         - on second switch to offroad now removed from MQ\
   1.5.4 - removed debugging messages\
   1.5.5 - removed bug in troop report reading nil destination \
   1.6.0 - check modules \
   1.6.1 - troopsCallback management so you can be informed if a \
           troop you have added to the pool is dead or has achieved a goal.\
           callback will list reasons \"dead\" and \"arrived\"\
           updateAttackers\
   1.6.2 - also accept 'lase' as 'laze', translate directly \
   1.7.0 - now can use groundTroopsConfig zone\
   1.7.1 - addTroopsDeadCallback() renamed to addTroopsCallback() \
         - invokeCallbacksFor also accepts and passes on data block\
         - troops is always passed in data block as .troops \
   1.7.2 - callback when group is neutralized on guard orders\
         - callback when group is being engaged under guard orders \
   1.7.3 - callbacks for lase:tracking and lase:stop \
   1.7.4 - verbose flag, warnings suppressed \
   1.7.5 - some troop.group hardening with isExist()\
   1.7.6 - fixed switchToOffroad \
   1.7.7 - no longer case sensitive for orders \
   1.7.7 - updateAttackers() now inspects 'moving' status and invokes makeTroopsEngageZone\
         - makeTroopsEngageZone() sets 'moving' status to true\
         - createGroundTroops() sets moving status to false \
         - updateZoneAttackers() uses moving  \
   1.7.8 - better guards before invoking ownedZones\
\
  an entry into the deployed troop table has the following attributes\
  - group - the group \
  - orders: \"guard\" - will guard the spot and look for enemies in range\
            \"patrol\" - will walk between way points back and forth \
            \"laze\" - will stay in place and try to laze visible vehicles in range\
            \"attackOwnedZone\" - interface to cfxOwnedZones module, seeks out\
              enemy zones to attack and capture them\
            \"wait-<some other orders>\" do nothing. the \"wait\" prefix will be removed some time and <some other order> then revealed. Used at least by heloTroops\
            \"train\" - target dummies. ROE=HOLD, no ground loop \
            \"attack\" - transition to destination, once there, stop and \
            switch to guard. requires destination zone be set to a valid cfxZone\
  - coalition - the coalition from the group\
  - enemy - if set, the group this group it is engaging. this means the group is fighting and not idle\
  - name - name of group, dan be freely changed\
  - signature - \"cfx\" to tell apart from dcs groups \
  - range = range to look for enemies. default is 300m. In \"laze\" orders, range to laze\
  - lazeTarget - target currently lazing\
  - lazeCode - laser code. default is 1688\
  - moving - has been given orders to move somewhere already. used for first movement order with attack orders \
\
 \
 usage:\
 take a dcs group of ground troops and create a cfx ground troop record with \
  createGroundTroops()\
 then add this to the manager with \
  addGroundTroopsToPool()\
 \
 you can control what the group is to do by changing the cfx troop attribute orders \
 you can install a callback that will notify you if a troop reached a goal or\
 was killed with addTroopsCallback() which will also give a reason\
 callback pattern is myCallback(reason, theGroup, orders, data) with troop being the \
 group, and orders the original orders, and reason a string containing why the \
 callback was invoked. Currently defined reasons are\
   - \"dead\" - entire group was killed \
   - \"arrived\" - at least a part of group arrived at destination (only with some orders)\
--]]--\
\
--\
-- UPDATE MODELS\
-- standard is update all every time: fastest, but may cause \
-- performance issues\
-- queued will work one every pass (except for lazed), distributing the load much better \
-- schedueld installs a callback for each group separately and thus distributes the load over time much better \
\
cfxGroundTroops.queuedUpdates = false -- set to true to process one group per turn. To work this way, scheduledUpdates must be false \
cfxGroundTroops.scheduledUpdates = true -- set to false to allow queing of standard updates. overrides queuedUpdates \
cfxGroundTroops.monitorNumbers = false -- set to true to debug managed group size \
\
cfxGroundTroops.standardScheduleInterval = 30 -- 30 seconds between calls\
cfxGroundTroops.guardUpdateInterval = 30 -- every 30 seconds we check up on guards\
cfxGroundTroops.trackingUpdateInterval = 0.5 -- 0.5 seconds for lazer tracking etc \
\
cfxGroundTroops.maxManagedTroops = 67 -- -1 is infinite, any positive number turn on cap on managed troops and palces excess troops in queue \
cfxGroundTroops.troopQueue = {} -- FIFO stack \
-- return the best tracking interval for this type of orders \
\
--\
-- READ CONFIG ZONE TO OVERRIDE SETTING\
--\
function cfxGroundTroops.readConfigZone()\
    -- note: must match exactly!!!!\
    local theZone = cfxZones.getZoneByName(\"groundTroopsConfig\") \
    if not theZone then \
        if cfxGroundTroops.verbose then \
            trigger.action.outText(\"***gndT: NO config zone!\", 30) \
        end\
        theZone = cfxZones.createSimpleZone(\"groundTroopsConfig\") \
    end \
        \
    -- ok, for each property, load it if it exists\
    if cfxZones.hasProperty(theZone, \"queuedUpdates\")  then \
        cfxGroundTroops.queuedUpdates = cfxZones.getBoolFromZoneProperty(theZone, \"queuedUpdates\", false)\
    end\
    \
    if cfxZones.hasProperty(theZone, \"scheduledUpdates\")  then \
        cfxGroundTroops.scheduledUpdates = cfxZones.getBoolFromZoneProperty(theZone, \"scheduledUpdates\", false)\
    end\
    \
    if cfxZones.hasProperty(theZone, \"maxManagedTroops\")  then \
        cfxGroundTroops.maxManagedTroops = cfxZones.getNumberFromZoneProperty(theZone, \"maxManagedTroops\", 65)\
    end\
    \
    if cfxZones.hasProperty(theZone, \"monitorNumbers\")  then \
        cfxGroundTroops.monitorNumbers = cfxZones.getBoolFromZoneProperty(theZone, \"monitorNumbers\", false)\
    end\
    \
    if cfxZones.hasProperty(theZone, \"standardScheduleInterval\")  then \
        cfxGroundTroops.standardScheduleInterval = cfxZones.getNumberFromZoneProperty(theZone, \"standardScheduleInterval\", 30)\
    end\
    \
    if cfxZones.hasProperty(theZone, \"guardUpdateInterval\")  then \
        cfxGroundTroops.guardUpdateInterval = cfxZones.getNumberFromZoneProperty(theZone, \"guardUpdateInterval\", 30)\
    end\
    \
    if cfxZones.hasProperty(theZone, \"trackingUpdateInterval\")  then \
        cfxGroundTroops.trackingUpdateInterval = cfxZones.getNumberFromZoneProperty(theZone, \"trackingUpdateInterval\", 0.5)\
    end\
    \
    if cfxZones.hasProperty(theZone, \"verbose\")  then \
        cfxGroundTroops.verbose = cfxZones.getBoolFromZoneProperty(theZone, \"verbose\", false)\
    end\
\
    if cfxGroundTroops.verbose then \
        trigger.action.outText(\"+++gndT: read config zone!\", 30) \
    end\
end\
\
\
-- \
-- Callback handling\
--\
\
cfxGroundTroops.troopsCallback = {}\
\
function cfxGroundTroops.addTroopsCallback(theCallback)\
    table.insert(cfxGroundTroops.troopsCallback, theCallback)\
end\
\
function cfxGroundTroops.invokeCallbacksFor(reason, troops, data)\
    if not data then data = {} end\
    data.troops = troops \
    for idx, theCB in pairs (cfxGroundTroops.troopsCallback) do \
        theCB(reason, troops.group, troops.orders, data)\
    end\
end\
\
function cfxGroundTroops.getScheduleInterval(orders)\
    if orders == \"laze\" then \
        return cfxGroundTroops.trackingUpdateInterval\
    end\
    return cfxGroundTroops.standardScheduleInterval\
end\
\
-- create controller commands to attack a group \"enemies\"\
-- enemies are an attribute of the troop structure\
-- usually called from a group on guard when idling \
function cfxGroundTroops.makeTroopsEngageEnemies(troop)\
    local group = troop.group\
    if not Group.isExist(group) then \
        trigger.action.outText(\"+++gndT: troup don't exist, dropping\", 30)\
        return \
    end\
    \
    local enemies = troop.enemy\
    local from = dcsCommon.getGroupLocation(group)\
    if not from then return end -- the commandos died\
    local there = dcsCommon.getGroupLocation(enemies)\
    if not there then return end\
    \
    -- we lerp to 2/3 of enemy location\
    there = dcsCommon.vLerp(from, there, 0.66) \
    \
    local speed = 10 -- m/s = 10 km/h -- wait. 10 m/s is 36 km/h \
    cfxCommander.makeGroupGoThere(group, there, speed)\
    local attask = cfxCommander.createAttackGroupCommand(enemies)\
    cfxCommander.scheduleTaskForGroup(group, attask, 0.5)\
    troop.moving = true \
end\
\
-- make the troops engage a cfxZone passed in the destination \
-- attribute \
function cfxGroundTroops.makeTroopsEngageZone(troop)\
    local group = troop.group\
    if not group:isExist() then \
        trigger.action.outText(\"+++gndT: make troops engage zone: troops do not exist, exiting\", 30)\
        return \
    end\
    \
    local enemyZone = troop.destination -- must be cfxZone \
    local from = dcsCommon.getGroupLocation(group)\
    if not from then return end -- the group died\
    local there = enemyZone.point -- access zone position\
    if not there then return end\
        \
    local speed = 14 -- m/s; 10 m/s = 36 km/h\
    \
    -- make troops stop in 1 second, then start in 5 seconds to give AI respite \
    cfxCommander.makeGroupHalt(group, 1) -- 1 second delay\
    cfxCommander.makeGroupGoTherePreferringRoads(group, there, speed, 5)\
\
    -- remember that we have issued a move order \
    troop.moving = true     \
end\
\
function cfxGroundTroops.switchToOffroad(troops)\
    -- we may need to test if we already did this, \
    -- but not for now \
    \
    -- this is called when troops are stuck \
    -- on their route for longer than allowed\
    -- we now force a direct approach \
    local group = troops.group\
    if not group:isExist() then \
        return\
    end \
    \
    local enemies = troops.destination\
    local from = dcsCommon.getGroupLocation(group)\
    if not from then return end -- the commandos died\
    local there = enemies.point\
    if not there then return end\
        \
    local speed = 14 -- m/s; 10 m/s = 36 km/h\
    \
    cfxCommander.makeGroupHalt(group, 0) -- no delay, halt now\
    cfxCommander.makeGroupGoThere(group, there, speed, \"Off Road\", 5)\
    \
    troops.lastOrderDate = timer.getTime()\
    troops.speedWarning = 0\
end\
\
--\
-- update loop for troops that have 'attackOwnedZones' as \
-- their orders\
-- if they have no destination zone, or the zone they are \
-- are heading for is already owned by their side, then look for \
-- the closest enemy zone, and cut attack orders to move there \
function cfxGroundTroops.getClosestEnemyZone(troop)\
    local p = dcsCommon.getGroupLocation(troop.group)\
    local tempZone = cfxZones.createSimpleZone(\"tz\", p, 100)\
    tempZone.owner = troop.side\
    local newTarget = cfxOwnedZones.getNearestEnemyOwnedZone(tempZone, true) -- 'true' will also target neutral zones \
    return newTarget\
end\
\
function cfxGroundTroops.updateZoneAttackers(troop)\
    if not troop then return end \
    if not cfxOwnedZones then \
        trigger.action.outText(\"+++gndT: update zone attackers requires ownedZones\", 30)\
        return \
    end\
    troop.insideDestination = false -- mark as not inside \
    \
    local newTargetZone = cfxGroundTroops.getClosestEnemyZone(troop)\
    if not newTargetZone then\
        -- all target zones are friendly, go to guard mode\
        troop.orders = \"guard\"\
        return \
    end\
    \
    if newTargetZone ~= troop.destination then \
        troop.destination = newTargetZone \
        cfxGroundTroops.makeTroopsEngageZone(troop)\
        troop.lastOrderDate = timer.getTime()\
        troop.speedWarning = 0\
        return\
    end\
    \
    -- if we get here, we should be under way to our nearest enemy zone\
    if not troop.moving then \
        cfxGroundTroops.makeTroopsEngageZone(troop)\
        return \
    end \
    \
    -- if we get here, we are under way to troop.destination\
    -- check if we are inside the zone, and if so, set variable to true \
    local p = dcsCommon.getGroupLocation(troop.group)\
    troop.insideDestination = cfxZones.isPointInsideZone(p, troop.destination)\
    \
    -- if we get here, we need no change \
    \
end\
\
-- attackers simply travel to their destination (zone), and then switch to \
-- guard orders once they arrive \
function cfxGroundTroops.updateAttackers(troop) \
    if not troop then return end \
    if not troop.destination then return end \
    if not troop.group:isExist() then return end \
    \
    -- if we are not moving, we need to issue move oders now\
    -- this can happen if previously, there was a 'wait' command \
    -- and this now was removed so we end up in the method \
    if not troop.moving then \
        cfxGroundTroops.makeTroopsEngageZone(troop)\
        return \
    end \
    \
    \
    if cfxZones.isGroupPartiallyInZone(troop.group, troop.destination) then\
        -- we have arrived\
        -- we could now also initiate a general callback with reason\
        cfxGroundTroops.invokeCallbacksFor(\"arrived\", troop)\
        troop.orders = \"guard\"\
        return \
    end\
    \
    \
--    if we get here, we need no change \
end\
\
-- update loop for a group that has \"guard\" orders.\
-- basically it stands around and looks for enemies \
-- until it finds a group, and then engages the enemy\
-- when engaged, it is not looking for other enemies\
-- 'engaged' means that the troop.enemy attribute is set\
 \
function cfxGroundTroops.updateGuards(troop)\
    if not troop.group:isExist() then \
        return \
    end \
    \
    local theEnemy = troop.enemy\
    if theEnemy then \
        -- see if enemy is dead \
        if not dcsCommon.isGroupAlive(theEnemy) then \
            troop.enemy = nil\
            -- yup, zed's dead. next time around, we won't be checking this again\
            trigger.action.outText(troop.name .. \" has neutralized enemy forces\", 30)\
            --DONE: invoke callback for defeating troops\
            local data = {}\
            data.enemy = theEnemy\
            cfxGroundTroops.invokeCallbacksFor(\"neutralized\", troop, data)\
            return\
        end\
        -- yes, we are still engaged\
        return \
    end\
    \
    -- we are currently unengaged. look for an enemy\
    if not troop.range then troop.range = 300 end\
    troop.coalition = troop.group:getCoalition()\
    local enemyCoal = dcsCommon.getEnemyCoalitionFor(troop.coalition)\
    local cat = Group.Category.GROUND\
    local p = dcsCommon.getGroupLocation(troop.group)\
    local enemies, enemyDist = dcsCommon.getClosestLivingGroupToPoint(p, enemyCoal, cat) \
    local maxRange = troop.range -- meters \
    -- if we have enemies then schedule a path to go there\
    if enemies and (enemyDist < maxRange) then \
        troop.enemy = enemies\
        --timer.scheduleFunction(cfxGroundTroops.makeGroupEngageEnemies, troop, timer.getTime() + 1.0)\
        cfxGroundTroops.makeTroopsEngageEnemies(troop)\
        trigger.action.outText(troop.name .. \" is engaging enemy forces at range \" .. math.floor(enemyDist) .. \"meters\", 30)\
        --DONE: invoke callback for engaging troops, pass data \
        local data = {}\
        data.enemy = enemies\
        cfxGroundTroops.invokeCallbacksFor(\"engaging\", troop, data)\
    elseif enemies then \
        --trigger.action.outText(troop.name .. \" enemiy out of range: \" .. math.floor(enemyDist) .. \"meters\", 30)\
    else \
        --trigger.action.outText(troop.name .. \" no enemies\", 30)\
    end\
end\
\
--\
-- update loop for units that laze targets.\
-- they can only laze if they are alive, but update \
-- will take care of that, so when we are here, there \
-- is at least one of them alive\
-- \
\
function cfxGroundTroops.findLazeTarget(troop)\
    local here = troop.group:getUnit(1):getPoint()\
    troop.coalition = troop.group:getCoalition()\
    local enemyCoal = dcsCommon.getEnemyCoalitionFor(troop.coalition)\
    --local enemySide = dcsCommon.getEnemyCoalitionFor(troop.side)\
    local cat = Group.Category.GROUND\
    local enemyGroups = dcsCommon.getLivingGroupsAndDistInRangeToPoint(here, troop.range, enemyCoal, cat) \
    -- we now have a list of possible targets in range\
    if #enemyGroups < 1 then     \
        -- no targets in range\
        return nil \
    end\
\
    here = {x = here.x, y = here.y + 2.0, z = here.z} -- raise by 2.0m\
    \
    -- iterate through the list until we find the first target \
    -- that fits the bill and return it\
--    trigger.action.outText(\"+++ looking at \" .. #enemyGroups .. \" laze groups\", 30)\
    for i=1, #enemyGroups do    \
        -- get all units for this group \
        local aGroup = enemyGroups[i].group -- remember, they are in a {dist, group} tuple\
        local theUnits = aGroup:getUnits()\
        -- iterate all units \
        for udx, aUnit in pairs(theUnits) do \
            if (aUnit:isExist() and aUnit:getLife() > 1) then \
                -- unit lives \
                -- now, we need to filter infantry. we do this by \
                -- pre-fetching the typeString\
                --troop.lazeTargetType = aUnit:getTypeName()\
                -- and checking if the name contains some infantry-\
                -- typical strings. Idea taken from JTAC script \
                local isInfantry =  dcsCommon.unitIsInfantry(theUnit)\
    \
                \
                if not isInfantry then \
                    -- this is a vehicle, is it in line of sight?\
                    -- raise the point 2m above ground for both points\
                    -- as done in jtac script\
                    local there = aUnit:getPoint()  \
                    there = {x = there.x, y = there.y + 2.0, z = there.z}\
                   \
                    if land.isVisible(here, there) then \
                        -- we found a visible vehicle in \
                        -- the nearest group to us in range \
                        -- that is visible!\
                        return aUnit\
                    else \
                        --trigger.action.outText(\"+++ \".. aUnit:getName() ..\"cant be seen\", 30)\
                    end -- if visible\
                else \
                    -- trigger.action.outText(\"+++ \".. aUnit:getName() ..\" (\".. troop.lazeTargetType .. \") is infantry\", 30)\
                end -- if not infantry \
            end -- if alive \
        end -- for all units\
    end -- for all enemy groups\
    --trigger.action.outText(\"+++ find nearest laze target did not find anything to laze\", 30)\
    return nil -- no unit found \
end\
\
function cfxGroundTroops.lazerOff(troop)\
    if troop.lazerPointer then \
        troop.lazerPointer:destroy()\
    end\
    troop.lazerPointer = nil \
    troop.lazingUnit = nil \
end\
\
function cfxGroundTroops.trackLazer(troop)\
    -- the only thing that must be set when entering here is\
    -- lazeTarget. We set up the rest\
    if not troop.lazingUnit then \
        troop.lazingUnit = troop.group:getUnit(1) -- get first unit\
        if troop.lazingUnit:getLife() < 1 then \
            trigger.action.outText(\"+++ LazingUnit is dead, getUnit works differently from what docs say, need to filter for lively units\", 30)\
        end\
    end\
    \
    if not troop.lazerPointer then\
        local there = troop.lazeTarget:getPoint()\
        troop.lazerPointer = Spot.createLaser(troop.lazingUnit,{x = 0, y = 2, z = 0}, there, 1688)\
        troop.lazeTargetType = troop.lazeTarget:getTypeName()\
        trigger.action.outTextForCoalition(troop.side, troop.name .. \" tally target - lasing \" .. troop.lazeTargetType .. \"!\", 30)\
         trigger.action.outSoundForCoalition(troop.side, \"UI_SCI-FI_Tone_Bright_Dry_20_stereo.wav\")\
        troop.lastLazerSpot = there -- remember last spot\
        local data = {}\
        data.enemy = troop.lazeTarget\
        data.tracker = troop.lazingUnit\
        cfxGroundTroops.invokeCallbacksFor(\"lase:tracking\", troop, data)\
        return\
    end\
    \
    -- if true then return end \
    \
    -- if we get here, we update the lazerPointer\
    local there = troop.lazeTarget:getPoint()\
    -- we may only want to update the laser spot when dist > trigger\
    troop.lazerPointer:setPoint(there)\
    -- we may want to report dist\
    troop.lastLazerSpot = there\
end\
\
function cfxGroundTroops.updateLaze(troop)\
    -- check if we have a laze target. \
    -- check if lazing unit was killed, and therefore lost target\
    if troop.lazingUnit then \
        -- check that unit still alive\
        if troop.lazingUnit:isExist() and \
        troop.lazingUnit:getLife() >= 1 then\
        else \
            cfxGroundTroops.lazerOff(troop)\
            troop.lazeTarget = nil\
            trigger.action.outTextForCoalition(troop.side, troop.name .. \" reports lasing \" .. troop.lazeTargetType .. \" interrupted. Re-acquiring.\", 30)\
            trigger.action.outSoundForCoalition(troop.side, \"UI_SCI-FI_Tone_Bright_Dry_20_stereo.wav\")\
            troop.lazingUnit = nil \
            cfxGroundTroops.invokeCallbacksFor(\"lase:stop\", troop)\
            return -- we'll re-acquire through a new unit next round\
        end\
    end\
    \
    -- if we get here, a lazing unit \
    --local here = troop.lazingUnit:getPoint()\
    \
    if troop.lazeTarget then \
        -- check if that target is alive and in range\
        if troop.lazeTarget:isExist() and troop.lazeTarget:getLife() >= 1 then\
            -- note: when we laze a target, we know that we have a lazing unit\
            local here = troop.lazingUnit:getPoint()\
            -- check if it has moved out of range \
            local there = troop.lazeTarget:getPoint()\
            if dcsCommon.dist(here, there) > troop.range then \
                -- troop out of range\
                trigger.action.outTextForCoalition(troop.side, troop.name .. \" lost sight of lazed target \" .. troop.lazeTargetType, 30)\
                trigger.action.outSoundForCoalition(troop.side, \"UI_SCI-FI_Tone_Bright_Dry_20_stereo.wav\")\
                troop.lazeTarget = nil\
                cfxGroundTroops.lazerOff(troop)\
                troop.lazingUnit = nil\
                cfxGroundTroops.invokeCallbacksFor(\"lase:stop\", troop)\
                return \
            end\
            \
            -- if we get here, we need to update the target point \
            cfxGroundTroops.trackLazer(troop)\
            return\
        else\
            -- target died\
            trigger.action.outTextForCoalition(troop.side, troop.name .. \" confirms kill for \" .. troop.lazeTargetType, 30)\
            trigger.action.outSoundForCoalition(troop.side, \"UI_SCI-FI_Tone_Bright_Dry_20_stereo.wav\")\
            troop.lazeTarget = nil\
            cfxGroundTroops.lazerOff(troop)\
            troop.lazingUnit = nil\
            cfxGroundTroops.invokeCallbacksFor(\"lase:stop\", troop)\
            return\
        end        \
    end\
    \
    -- if we get here, we must look for a laze target \
    troop.lazeTarget = cfxGroundTroops.findLazeTarget(troop)\
    if troop.lazeTarget then \
        cfxGroundTroops.trackLazer(troop) -- will also set up lazing unit \
    end\
end\
\
\
function cfxGroundTroops.updateWait(troop)\
    -- currently nothing to do\
    \
end\
\
function cfxGroundTroops.updateTroops(troop)\
    -- if orders start with \"wait-\" then the troops \
    -- simply do nothing\
    if dcsCommon.stringStartsWith(troop.orders, \"wait-\") then\
        -- the troops are waiting to be picked update\
        -- when they are dropped again, thre prefix to \
        -- their order is removed, and the 'real' orders \
        -- are revealed. For now, do nothing\
        cfxGroundTroops.updateWait(troop)\
    --REMEMBER: LOWER CASE ONLY!\
    elseif troop.orders == \"guard\" then \
        cfxGroundTroops.updateGuards(troop)\
    \
    elseif troop.orders == \"attackownedzone\" then \
        cfxGroundTroops.updateZoneAttackers(troop)\
\
    elseif troop.orders == \"laze\" then \
        cfxGroundTroops.updateLaze(troop)\
    \
    elseif troop.orders == \"attackzone\" then \
        cfxGroundTroops.updateAttackers(troop)\
        \
    else \
        trigger.action.outText(\"+++ updated troops \" .. troop.name .. \" have unknown orders \" .. troop.orders, 30)\
    end\
    \
end\
\
--\
-- we have to systems to process during update: \
-- once all, and one per turn, with the exception \
-- of lazers, who get updated every turn\
-- \
\
--\
-- all at once \
--\
function cfxGroundTroops.update()\
    cfxGroundTroops.updateSchedule = timer.scheduleFunction(cfxGroundTroops.update, {}, timer.getTime() + 1/cfxGroundTroops.ups)\
    -- iterate all my troops and build next \
    -- versions pool\
    local liveTroops = {} -- filtered table, indexed by name \
    for idx, troop in pairs(cfxGroundTroops.deployedTroops) do \
        local group = troop.group \
        if not dcsCommon.isGroupAlive(group) then \
            -- group dead. remove from pool\
            -- this happens by not copying it into the poos\
            cfxGroundTroops.invokeCallbacksFor(\"dead\", troop) -- notify anyone who is interested that we are no longer proccing these \
        else \
            -- work with this groop according to its orders\
            cfxGroundTroops.updateTroops(troop)\
            -- since group is alive remember it for next loop\
            liveTroops[idx] = troop -- do NOT use insert as we have indexed table by name\
        end\
    end\
    -- liveTroops holds all troops that are still alive and will\
    -- be revisited next loop\
    cfxGroundTroops.deployedTroops = liveTroops\
end\
\
--\
-- UpdateQueued looks for the first unordered (.receivedOrders == false) group\
-- and processes them. if orders are 'laze', it will always be ordered \
--\
\
\
function cfxGroundTroops.updateQueued()\
    cfxGroundTroops.updateSchedule = timer.scheduleFunction(cfxGroundTroops.updateQueued, {}, timer.getTime() + 1/cfxGroundTroops.ups)\
    -- iterate all my troops and build next \
    -- versions pool\
    local liveTroops = {}\
    local hasOrdered = false -- so far, no orders have been given \
    for idx, troop in pairs(cfxGroundTroops.deployedTroops) do \
        local group = troop.group \
        if not dcsCommon.isGroupAlive(group) then \
            -- group dead. remove from pool\
            -- this happens by not copying it to liveTroops \
            -- trigger.action.outText(\"+++ removing ground troops \" .. troop.name, 30)\
            cfxGroundTroops.invokeCallbacksFor(\"dead\", troop) -- notify anyone who is interested that we are no longer proccing these \
        else \
            -- check if this is a lazer \
            if troop.orders == \"laze\" then \
                -- lazers are updated each turn \
                cfxGroundTroops.updateLaze(troop)\
            else \
                if not hasOrdered and not (troop.receivedOrders) then \
                -- work with this groop according to its orders\
                cfxGroundTroops.updateTroops(troop)\
                troop.receivedOrders = true -- this one has received orders \
                hasOrdered = true \
                end \
            end\
            liveTroops[idx] = troop -- do NOT use insert as we have indexed table\
        end\
    end\
    -- liveTroops holds all troops that are still alive and will\
    -- be revisited next loop\
    cfxGroundTroops.deployedTroops = liveTroops\
    \
    -- if no orders have been passed, clear all troop's .receivedOrders flag \
    -- and the loop starts anew next loop \
    if not hasOrdered then \
        for idx, troop in pairs(cfxGroundTroops.deployedTroops) do\
            troop.receivedOrders = nil  \
        end\
    end\
end\
\
--\
-- in updateCheckOnly we simply check the ground queue \
-- if there are troops added that need scheduling (i.e. have \
-- been passed in by addTroops and schedule them \
--\
function cfxGroundTroops.updateCheckOnly()\
    -- re-schedule myself in 1 second \
    timer.scheduleFunction(cfxGroundTroops.updateCheckOnly, {}, timer.getTime() + 1)\
    \
    -- iterate through all troops, and \
    -- see if there are any that have not been scheduled \
    -- to schedule them for updates in 1 second\
    -- that will be the first time that they are scheduled,\
    -- all others will be self-scheduled \
    for idx, troop in pairs(cfxGroundTroops.deployedTroops) do \
        if not troop.hasBeenScheduled then \
            local params = {troop}\
            troop.hasBeenScheduled = true \
            troop.updateID = timer.scheduleFunction(cfxGroundTroops.updateSingleScheduled, params, timer.getTime() + 1)\
            --trigger.action.outText(\"+++groundT: scheduling troops <\".. troop.group:getName() ..\"> with orders <\" .. troop.orders .. \">\", 30)\
        end\
    end\
    -- note that alive checks are now done during the scheduled\
    -- update, not every time for all\
\
end\
\
function cfxGroundTroops.updateSingleScheduled(params)\
    local troops = params[1]\
    troops.updateID = nil -- erase update id \
    if not troops then \
        trigger.action.outText(\"+++groundT WARNING: nil troop in updateSingle\", 30)\
        return -- no further action required, no longer updates\
    end\
    \
    local group = troops.group \
    -- see if we have been taken out of the pool or updated\
    -- if so, exit \
    \
    if not group:isExist() then \
        -- simply never again look at it. \
        return \
    end\
    \
    if cfxGroundTroops.deployedTroops[troops.group:getName()] ~= troops then \
        -- trigger.action.outText(\"+++groundT NOTE: troops <\".. troops.group:getName() ..\"> was removed from pool. Cancel Update\", 30)\
        return -- no further reschedule\
    end\
    \
    -- see if scheduling is turned off\
    if not troops.reschedule then \
        trigger.action.outText(\"+++groundT NOTE: no longer updating <\".. troops.group:getName() ..\"> per reschedule param\", 30)\
        return \
    end\
    \
    -- now, check if still alive \
    if not dcsCommon.isGroupAlive(group) then \
        -- group dead, no longer updates \
        --trigger.action.outText(\"+++groundT NOTE: <\".. troops.group:getName() ..\"> dead, removing\", 30)\
        cfxGroundTroops.invokeCallbacksFor(\"dead\", troops) -- notify anyone who is interested that we are no longer proccing these \
        cfxGroundTroops.removeTroopsFromPool(troops)\
        return -- nothing else to do\
    end\
    \
    -- now, execute the update itself, standard update \
    --trigger.action.outText(\"+++groundT: singleU troop <\".. troops.group:getName() ..\"> with orders <\" .. troops.orders .. \">\", 30)\
    cfxGroundTroops.updateTroops(troops)\
    \
    -- check max speed of group. if < 0.1 then note and increase \
    -- speedWarning. if not, reset speed warning \
    if troops.orders == \"attackownedzone\" and dcsCommon.getGroupMaxSpeed(troops.group) < 0.1 then \
        if not troops.speedWarning then troops.speedWarning = 0 end\
        troops.speedWarning = troops.speedWarning + 1\
    else\
        troops.speedWarning = 0 -- reset\
    end\
    \
    if troops.speedWarning > 5 then -- make me 5\
        lastOrder = timer.getTime() - troops.lastOrderDate \
        --trigger.action.outText(\"+++groundT WARNING: <\".. troops.group:getName() ..\"> (S:\".. troops.side .. \") to \" .. troops.destination.name .. \": stopped for \" .. troops.speedWarning .. \" iters, orderage=\" .. lastOrder, 30)\
        -- this may be a matter of too many waypoints. \
        -- maybe issue orders to go to their destination directly?\
        -- now force an order to go directly.\
        if troops.speedWarning > 5 then \
            if troops.isOffroad then \
                -- we already switched to off-road. take me \
                -- out of the managed queue, I'm not going \
                -- anywhere\
                -- trigger.action.outText(\"+++groundT <\".. troops.group:getName() ..\"> is going nowhere. Removed from managed troops\", 30)\
                cfxGroundTroops.removeTroopsFromPool(troops)\
            else \
                cfxGroundTroops.switchToOffroad(troops)\
                -- trigger.action.outText(\"+++groundT <\".. troops.group:getName() ..\"> SWITCHED TO OFFROAD\", 30)\
                troops.isOffroad = true -- so we know that we already did that\
            end\
        end \
    end\
    \
    -- now reschedule updte for my best time \
    local updateTime = cfxGroundTroops.getScheduleInterval(troops.orders)\
    troops.updateID = timer.scheduleFunction(cfxGroundTroops.updateSingleScheduled, params, timer.getTime() + updateTime)\
end\
\
\
--\
-- PILEUP and TIE BRAKERS\
--\
-- there may come a situation where troops gather in \
-- one zone because the zone isn't won - some other troops \
-- are there and noone moves. \
-- a tie-break is required\
--\
\
-- checkpile up: every so often, we test if we have run into a \
-- pileup-situation. this happens if there are more than n \
-- units with group-attacker order in the same zone, and that \
-- zone is their destination \
-- this can be easily detected by the insideDestination flag \
-- checkPileUp should be run every minute or so \
 \
function cfxGroundTroops.checkPileUp()\
    -- schedule my next call \
    --trigger.action.outText(\"+++groundT: pileup check\", 30)\
    timer.scheduleFunction(cfxGroundTroops.checkPileUp, {}, timer.getTime() + 60)\
    local thePiles = {}\
    if not cfxOwnedZones then \
        -- trigger.action.outText(\"+++groundT: pileUp - owned zones not yet ready\", 30)\
        return \
    end\
    \
    -- create a list of all piles \
    for idx, oz in pairs(cfxOwnedZones.zones) do \
        local newPile = {}\
        newPile[1] = 0 -- no red inZone here \
        newPile[2] = 0 -- no blue inZone here \
        newPile.zone = oz -- the zone we are looking at \
        thePiles[oz] = newPile \
    end\
    \
    -- now iterate through all currently alive groups and \
    -- attribute them to their piles \
    for idx, troop in pairs(cfxGroundTroops.deployedTroops) do \
        -- get each group and count them if they are inside\
        -- their destination \
        if troop.insideDestination and troop.group:isExist() then\
            local side = troop.group:getCoalition()\
            local thePile = thePiles[troop.destination]\
            local theSide = troop.group:getCoalition()\
            thePile[theSide] = thePile[theSide] + 1 -- we count groups, not units  \
        end\
    end\
    \
    -- a pileup happens, if there are more than 3 groups in destination zone\
    -- with NO other troops present (usually the case)\
    -- or when there are 5 groups more than the number for the other side \
    -- so now scan all piles\
    for idx, thePile in pairs(thePiles) do \
        -- check red pileup \
        if thePile[1] > 3 and thePile[2] == 0 then \
            -- simple pileup. 3 groups, no others except defenders and \
            -- perhaps transients \
            cfxGroundTroops.breakTie(thePile, 1)\
        elseif thePile[1] >= thePile[2] + 5 then \
            -- numerical pileup \
            cfxGroundTroops.breakTie(thePile, 1)\
        end\
        \
        -- check blue loside \
        if thePile[2] >= 3 and thePile[1] == 0 then \
            -- simple pileup. 3 groups, no others except defenders and \
            -- perhaps transients \
            cfxGroundTroops.breakTie(thePile, 2)\
        elseif thePile[2] >= thePile[1] + 5 then \
            -- numerical pileup \
            cfxGroundTroops.breakTie(thePile, 2)\
        end\
    end\
end\
\
function cfxGroundTroops.breakTie(thePile, winner)\
    trigger.action.outText(\"+++ groundT: TIEBREAK - winner is \" .. winner .. \" in zone \" .. thePile.zone.name .. \": \" .. thePile[1] .. \":\" .. thePile[2] , 30)\
    -- now add some code to do the actual tie breaking: remove all units that \
    -- are inside the zone and who belong to the other side \
    local loser = 1 -- red default \
    local theZone = thePile.zone \
    if winner == 1 then loser = 2 end \
    -- now get all ground groups for the losing side\
    local losingGround = coalition.getGroups(loser, Group.Category.GROUND)\
    for idx, theGroup in pairs(losingGround) do \
        -- if alive, check if inside the zone \
        if theGroup:isExist() and dcsCommon.isGroupAlive(theGroup) then \
            -- make sure it's not a transient\
            if not isDeployedGroundTroop(theGroup) then \
                local p = dcsCommon.getGroupLocation(theGroup) \
                if cfxZones.isPointInsideZone(p, theZone) then \
                    trigger.action.outText(\"+++ groundT: TIEBREAK - destroying group \" .. theGroup:getName() , 30)\
                    -- we delete this group now\
                    theGroup:destroy()\
                end\
            end\
        end\
    end\
end\
\
--\
-- sanity checks for rescheduling\
--\
function cfxGroundTroops.checkSchedules()\
    timer.scheduleFunction(cfxGroundTroops.checkSchedules, {}, timer.getTime() + 10)\
    for idx, troop in pairs(cfxGroundTroops.deployedTroops) do\
        -- check if troop is not scheduled \
        -- if this happens to a group more than a certain times,\
        -- it has somehow dropped out of the reschedule \
        -- plan and needs to be scheduled \
        if troop.updateID == nil then \
            troop.unscheduleCount = troop.unscheduleCount + 1\
            if (troop.unscheduleCount > 1) and troop.group:isExist() then \
                trigger.action.outText(\"+++ groundT: unscheduled group  \" .. troop.group:getName() .. \" cnt=\" .. troop.unscheduleCount , 30)\
            end \
        end\
    end\
end\
\
--\
-- REPORTING \
--\
-- \
-- get a report of troops as string \
-- \
function cfxGroundTroops.getTroopReport(theSide, ignoreInfantry)\
    if not ignoreInfantry then ignoreInfantry = false end \
    local report = \"GROUND FORCES REPORT\"\
    for idx, troop in pairs(cfxGroundTroops.deployedTroops) do \
        if troop.side == theSide and troop.group:isExist() then \
            local unitNum = troop.group:getSize()\
            report = report .. \"\\n\" .. troop.name .. \" (\".. unitNum ..\"): <\" .. troop.orders .. \">\" \
            if troop.orders == \"attackownedzone\" then \
                if troop.destination then     \
                    report = report .. \" move towards \" .. troop.destination.name \
                else \
                    report = report .. \" (selecting destination)\"\
                end\
            end\
        end\
    end\
    report = report .. \"\\n---END REPORT\\n\"\
    return report \
end\
\
\
--\
-- CREATE / ADD / REMOVE \
--\
\
--\
-- createGroundTroop\
-- use this to create a cfxGroundTroops from a dcs group\
--\
function cfxGroundTroops.createGroundTroops(inGroup, range, orders) \
    local newTroops = {}\
    if not orders then \
        orders = \"guard\" \
    end\
    if orders:lower() == \"lase\" then \
        orders = \"laze\" -- we use WRONG spelling here, cause we're cool. yeah, right.\
    end\
    newTroops.insideDestination = false\
    newTroops.unscheduleCount = 0 -- will count up as we aren't scheduled\
    newTroops.speedWarning = 0\
    newTroops.isOffroad = false -- if true, we switched to direct orders, not roads, after standstill\
    newTroops.group = inGroup\
    newTroops.orders = orders:lower()\
    newTroops.coalition = inGroup:getCoalition()\
    newTroops.side = newTroops.coalition -- because we'e been using both.\
    newTroops.name = inGroup:getName()\
    newTroops.moving = false -- set to not have received move orders yet \
    newTroops.signature = \"cfx\" -- to verify this is groundTroop group, not dcs groups\
    if not range then range = 300 end\
    newTroops.range = range\
    return newTroops\
end\
\
function cfxGroundTroops.addGroundTroopsToPool(troops) -- troops MUST be a table that I understand, with \
    if not troops then return end\
    if troops.signature ~= \"cfx\" then \
        trigger.action.outText(\"+++ adding ground troops with unsupported troop signature\", 30)\
        return \
    end\
    if not troops.orders then troops.orders = \"guard\" end \
    troops.orders = troops.orders:lower()\
    troops.reschedule = true -- in case we use scheduled update \
    -- we now add to internal array. this is worked on by all \
    -- update meths, on scheduled upadtes, it is only used to \
    -- pick up, and do the initial schedule, after that they \
    -- all re-schedule themselves \
    troops.hasBeenScheduled = false -- so far, no updates \
    -- hasBeenScheduled is used by updateCheckOnly when scheduled \
    -- updates are used. \
    \
    -- now add to actively managed table or queue it if enabled\
    if cfxGroundTroops.maxManagedTroops > 0 and dcsCommon.getSizeOfTable(cfxGroundTroops.deployedTroops) >= cfxGroundTroops.maxManagedTroops then \
        -- we need to queue \
        table.insert(cfxGroundTroops.troopQueue, troops)\
    else\
        -- add to deployed set\
        cfxGroundTroops.deployedTroops[troops.group:getName()] = troops\
    end\
end\
\
function cfxGroundTroops.removeTroopsFromPool(troops)\
    \
    if not troops then return end \
    if troops.signature ~= \"cfx\" then return end\
\
    if not troops.group:isExist() then \
        trigger.action.outText(\"warning: removeFromPool called with inexistant group\", 30)\
        return \
    end\
    \
    if cfxGroundTroops.deployedTroops[troops.group:getName()] then \
        local troop = cfxGroundTroops.deployedTroops[troops.group:getName()]\
        troops.reschedule = false -- so a reschedule wont update any more\
        cfxGroundTroops.deployedTroops[troops.group:getName()] = nil\
        return \
    end\
    \
    -- if we get here, we need to check if perhaps the troops \
    -- are in the queue\
    for i=1, #cfxGroundTroops.troopQueue do \
        if cfxGroundTroops.troopQueue[i] == troops then \
            table.remove(cfxGroundTroops.troopQueue, i)\
            return\
        end\
    end\
end\
\
function isDeployedGroundTroop(aGroup) \
    if not aGroup then return false end \
    -- see if its already managed\
    if cfxGroundTroops.deployedTroops[aGroup:getName()] ~= nil then \
        return true \
    end \
    \
    -- see if it's in the queue \
    for i=1, #cfxGroundTroops.troopQueue do \
        if cfxGroundTroops.troopQueue[i] == troops then \
            return true\
        end\
    end\
    -- if we get here, it's neither managed nor queued\
    return false \
--    return cfxGroundTroops.deployedTroops[aGroup:getName()] ~= nil \
end\
\
function cfxGroundTroops.getGroundTroopsForGroup(aGroup) \
    if not (cfxGroundTroops.deployedTroops[aGroup:getName()]) then\
        -- see if it's queued \
        for i=1, #cfxGroundTroops.troopQueue do \
            local troops = cfxGroundTroops.troopQueue[i]\
            if troops.group == aGroup then \
                return troops\
            end\
        end\
        \
        if cfxGroundTroops.verbose then \
            trigger.action.outText(\"+++gndT - WARNING: cannot find group \" .. aGroup:getName() .. \" for troop retrieval. Known troops are:\", 30)\
        end \
        for k,v in pairs(cfxGroundTroops.deployedTroops) do \
            trigger.action.outText(\"+++ \".. k .. \": has v: \" .. v.name, 30)\
        end\
        return nil\
    end\
    \
    return cfxGroundTroops.deployedTroops[aGroup:getName()]\
end\
\
function cfxGroundTroops.monitorQueues()\
    timer.scheduleFunction(cfxGroundTroops.monitorQueues, {}, timer.getTime() + 5)\
    \
    -- calculate the numbers \
    local num = dcsCommon.getSizeOfTable(cfxGroundTroops.deployedTroops)\
    \
    local msg = \"+++ gndT - Groups Managed: <\" .. num .. \">\"\
    -- display the numbers\
    if cfxGroundTroops.maxManagedTroops > 0 then \
        msg = msg .. \" capped at \" .. cfxGroundTroops.maxManagedTroops .. \", q size is <\" .. #cfxGroundTroops.troopQueue .. \">\"\
    end\
    trigger.action.outText(msg, 30)\
end\
\
\
-- manageQueue: if depth of deployedTroops is below max and we have \
-- items in queue, pop off first one and put in managed table \
-- checked once every 2 seconds \
function cfxGroundTroops.manageQueues() \
    timer.scheduleFunction(cfxGroundTroops.manageQueues, {}, timer.getTime() + 2)\
    if cfxGroundTroops.maxManagedTroops < 1 then return end\
    \
    -- if we get here, we have a limit on managed \
    -- items \
    if #cfxGroundTroops.troopQueue < 1 then return end \
    \
    -- if we here, there are items waiting in the queue\
    while dcsCommon.getSizeOfTable(cfxGroundTroops.deployedTroops) < cfxGroundTroops.maxManagedTroops and #cfxGroundTroops.troopQueue > 0 do \
        -- trnasfer items from the front to the managed queue \
        local theTroops = cfxGroundTroops.troopQueue[1]\
        table.remove(cfxGroundTroops.troopQueue, 1)\
        if theTroops.group:isExist() then \
            cfxGroundTroops.deployedTroops[theTroops.group:getName()] = theTroops\
        end\
        -- trigger.action.outText(\"+++gT: dequed and activaed \" .. theTroops.group:getName(), 30)\
    end\
end\
\
\
function cfxGroundTroops.start()\
    if not dcsCommon.libCheck(\"cfx Ground Troops\",\
                              cfxGroundTroops.requiredLibs)\
    then \
        trigger.action.outText(\"cf/x Ground Troops aborted: missing libraries\", 30)\
        return false \
    end\
    \
    -- read optional config zone \
    cfxGroundTroops.readConfigZone()\
    \
    if cfxGroundTroops.scheduledUpdates then \
        cfxGroundTroops.queuedUpdates = false \
        cfxGroundTroops.updateCheckOnly()\
        cfxGroundTroops.checkSchedules() -- check regularly if all troops have been updated by checking their ID\
    elseif cfxGroundTroops.queuedUpdates then \
        cfxGroundTroops.updateQueued()\
    else     \
        cfxGroundTroops.update()\
    end \
    -- now install a regular pileup check \
    timer.scheduleFunction(cfxGroundTroops.checkPileUp, {}, timer.getTime() + 60) \
    \
    if cfxGroundTroops.monitorNumbers then \
        timer.scheduleFunction(cfxGroundTroops.monitorQueues, {}, timer.getTime() + 5) \
    end\
    \
    if cfxGroundTroops.maxManagedTroops > 0 then\
        timer.scheduleFunction(cfxGroundTroops.manageQueues, {}, timer.getTime() + 1) \
    end \
    \
    trigger.action.outText(\"cf/x Ground Troops v\" .. cfxGroundTroops.version .. \" started\", 30)\
    \
    if not cfxOwnedZones then \
        --trigger.action.outText(\"+++groundT: pileUp - owned zones not yet ready\", 30)\
    end\
    return true \
end\
\
if not cfxGroundTroops.start() then \
    cfxGroundTroops = nil \
    trigger.action.outText(\"cfxGroundTroops aborted load\", 30)\
end\
\
--[[--\
 TO DO \
 \
 - implement 'patrol' orders!!! \
   \
   when ordering a new route, issue a command to stop in 1 second\
 and another with new marching orders in 5 seconds \
 look at setTask() and resetTask() for controller\
 - change group logic to set itself up to 'requestOrders' with group as parameter, so they can decide themselves how quickly they want to be re-tasked\
 \
 - DONE enqueue and dequeue methods with capped ground troops size \
 - named locs have strategic values attached (default = 1), and distance is divided by strat value to get at priority when rerouting \
 \
 - difficulty increase: make enemy troops better by raining their spawned level \
 \
 - check out simple slot block SSB (pre-moose) to see if we can implement slot blocking for downed pilots \
 \
 - new 'wanda' (wander) module to make airports more lively: zone, have individuals/single vehicle wander around. two waypoints (start and stop), that are zones, and whenever they reach one or are at speed 0, they get a new one. may have pause before they go to next. \
 variant on above: selection of zones that are somehow connected, and destinations are made between these for patrolling zone. can force order, loop, and ping-pong. \
--]]--",
                    ["predicate"] = "a_do_script",
                }, -- end of [4]
                [5] = 
                {
                    ["text"] = "cfxOwnedZones = {}\
cfxOwnedZones.version = \"2.0.0\"\
cfxOwnedZones.verbose = false \
cfxOwnedZones.announcer = true \
cfxOwnedZones.name = \"cfxOwnedZones\" \
--[[-- VERSION HISTORY\
\
2.0.0 - factored from cfxOwnedZones 1.x, separating out production\
\
--]]--\
cfxOwnedZones.requiredLibs = {\
    \"dcsCommon\", \
    \"cfxZones\",  \
}\
\
cfxOwnedZones.zones = {}\
cfxOwnedZones.ups = 1\
cfxOwnedZones.initialized = false \
--[[--\
 owned zones is a module that manages conquerable zones and keeps a record\
 of who owns the zone based on rules  \
\
 \
 *** EXTENTDS ZONES ***, so compatible with cfxZones, pilotSafe (limited airframes), may conflict with FARPZones \
\
\
 owned zones are identified by the 'owner' property. It can be initially set to nothing (default), NEUTRAL, RED or BLUE\
\
 when a zone changes hands, a callback can be installed to be told of that fact\
 callback has the format (zone, newOwner, formerOwner) with zone being the Zone, and new owner and former owners\
 --]]--\
 \
cfxOwnedZones.conqueredCallbacks = {}\
\
--\
-- callback handling\
--\
\
function cfxOwnedZones.addCallBack(conqCallback)\
    local cb = {}\
    cb.callback = conqCallback -- we use this so we can add more data later\
    cfxOwnedZones.conqueredCallbacks[conqCallback] = cb\
    \
end\
\
function cfxOwnedZones.invokeConqueredCallbacks(aZone, newOwner, lastOwner)\
    for key, cb in pairs (cfxOwnedZones.conqueredCallbacks) do \
        cb.aZone = aZone -- set these up for if we need them later\
        cb.newOwner = newOwner\
        cb.lastOwner = lastOwner\
        -- invoke callback\
        cb.callback(aZone, newOwner, lastOwner)\
    end\
end\
\
function cfxOwnedZones.side2name(theSide)\
    if theSide == 1 then return \"REDFORCE\" end\
    if theSide == 2 then return \"BLUEFORCE\" end\
    return \"Neutral\"\
end\
\
function cfxOwnedZones.conqTemplate(aZone, newOwner, lastOwner) \
    if true then return end -- do not output\
\
    if lastOwner == 0 then \
        trigger.action.outText(cfxOwnedZones.side2name(newOwner) .. \" have taken possession zone \" .. aZone.name, 30)\
        return \
    end\
    \
    trigger.action.outText(\"Zone \" .. aZone.name .. \" was taken by \".. cfxOwnedZones.side2name(newOwner) .. \" from \" .. cfxOwnedZones.side2name(lastOwner), 30)\
end\
\
--\
-- M I S C\
--\
\
function cfxOwnedZones.drawZoneInMap(aZone)\
    -- will save markID in zone's markID\
    if aZone.markID then \
        trigger.action.removeMark(aZone.markID)\
    end \
    if aZone.hidden then return end \
    \
    local lineColor = {1.0, 0, 0, 1.0} -- red \
    local fillColor = {1.0, 0, 0, 0.2} -- red \
    local owner = aZone.owner -- cfxOwnedZones.getOwnerForZone(aZone)\
    if owner == 2 then \
        lineColor = {0.0, 0, 1.0, 1.0}\
        fillColor = {0.0, 0, 1.0, 0.2}\
    elseif owner == 0 then \
        lineColor = {0.8, 0.8, 0.8, 1.0}\
        fillColor = {0.8, 0.8, 0.8, 0.2}\
    end\
    \
    local theShape = 2 -- circle\
    local markID = dcsCommon.numberUUID()\
\
    trigger.action.circleToAll(-1, markID, aZone.point, aZone.radius, lineColor, fillColor, 1, true, \"\")\
    aZone.markID = markID \
    \
end\
\
function cfxOwnedZones.getOwnedZoneByName(zName)\
    for zKey, theZone in pairs (cfxOwnedZones.zones) do \
        if theZone.name == zName then return theZone end \
    end\
    return nil\
end\
\
function cfxOwnedZones.addOwnedZone(aZone)\
    local owner = aZone.owner --cfxZones.getCoalitionFromZoneProperty(aZone, \"owner\", 0) -- is already readm read it again\
    \
    if cfxZones.hasProperty(aZone, \"conquered!\") then \
        aZone.conqueredFlag = cfxZones.getStringFromZoneProperty(aZone, \"conquered!\", \"*<cfxnone>\")\
    end\
    if cfxZones.hasProperty(aZone, \"redCap!\") then \
        aZone.redCap = cfxZones.getStringFromZoneProperty(aZone, \"redCap!\", \"none\")\
    end\
    if cfxZones.hasProperty(aZone, \"redLost!\") then \
        aZone.redLost = cfxZones.getStringFromZoneProperty(aZone, \"redLost!\", \"none\")\
    end\
    if cfxZones.hasProperty(aZone, \"blueCap!\") then \
        aZone.blueCap = cfxZones.getStringFromZoneProperty(aZone, \"blueCap!\", \"none\")\
    end\
    if cfxZones.hasProperty(aZone, \"blueLost!\") then \
        aZone.blueLost = cfxZones.getStringFromZoneProperty(aZone, \"blueLost!\", \"none\")\
    end\
    if cfxZones.hasProperty(aZone, \"neutral!\") then \
        aZone.neutralCap = cfxZones.getStringFromZoneProperty(aZone, \"neutral!\", \"none\")\
    end\
    if cfxZones.hasProperty(aZone, \"ownedBy\") then \
        aZone.ownedBy = cfxZones.getStringFromZoneProperty(aZone, \"ownedBy\", \"none\")\
    end\
\
    aZone.ownedTriggerMethod = cfxZones.getStringFromZoneProperty(aZone, \"triggerMethod\", \"change\")\
    if cfxZones.hasProperty(aZone, \"ownedTriggerMethod\") then \
        aZone.ownedTriggerMethod = cfxZones.getStringFromZoneProperty(aZone, \"ownedTriggerMethod\", \"change\")\
    end\
        \
    aZone.unbeatable = cfxZones.getBoolFromZoneProperty(aZone, \"unbeatable\", false)\
    aZone.untargetable = cfxZones.getBoolFromZoneProperty(aZone, \"untargetable\", false)\
    \
    aZone.hidden = cfxZones.getBoolFromZoneProperty(aZone, \"hidden\", false)\
    cfxOwnedZones.zones[aZone] = aZone \
    cfxOwnedZones.drawZoneInMap(aZone)\
end\
\
--\
-- U P D A T E \
--\
\
function cfxOwnedZones.bangNeutral(value)\
    if not cfxOwnedZones.neutralTriggerFlag then return end \
    local newVal = trigger.misc.getUserFlag(cfxOwnedZones.neutralTriggerFlag) + value \
    trigger.action.setUserFlag(cfxOwnedZones.neutralTriggerFlag, newVal)\
end\
\
function cfxOwnedZones.bangRed(value)\
    if not cfxOwnedZones.redTriggerFlag then return end \
    local newVal = trigger.misc.getUserFlag(cfxOwnedZones.redTriggerFlag) + value \
    trigger.action.setUserFlag(cfxOwnedZones.redTriggerFlag, newVal)\
end\
\
function cfxOwnedZones.bangBlue(value)\
    if not cfxOwnedZones.blueTriggerFlag then return end \
    local newVal = trigger.misc.getUserFlag(cfxOwnedZones.blueTriggerFlag) + value \
    trigger.action.setUserFlag(cfxOwnedZones.blueTriggerFlag, newVal)\
end\
\
function cfxOwnedZones.bangSide(theSide, value)\
    if theSide == 2 then \
        cfxOwnedZones.bangBlue(value)\
        return \
    end \
    if theSide == 1 then \
        cfxOwnedZones.bangRed(value)\
        return \
    end \
    cfxOwnedZones.bangNeutral(value)\
end\
\
function cfxOwnedZones.zoneConquered(aZone, theSide, formerOwner) -- 0 = neutral 1 = RED 2 = BLUE \
    local who = \"REDFORCE\"\
    if theSide == 2 then who = \"BLUEFORCE\" \
    elseif theSide == 0 then who = \"NEUTRAL\" end\
    \
    if cfxOwnedZones.announcer then \
        if theSide == 0 then \
            trigger.action.outText(aZone.name .. \" has become NEUTRAL\", 30)\
        else \
            trigger.action.outText(who .. \" have secured zone \" .. aZone.name, 30)\
        end\
        aZone.owner = theSide -- just to be sure \
        -- play different sounds depending on who's won\
        if theSide == 1 then \
            trigger.action.outSoundForCoalition(1, cfxOwnedZones.winSound)\
            trigger.action.outSoundForCoalition(2, cfxOwnedZones.loseSound)\
        elseif theSide == 2 then  \
            trigger.action.outSoundForCoalition(2, cfxOwnedZones.winSound)\
            trigger.action.outSoundForCoalition(1, cfxOwnedZones.loseSound)\
        else \
            -- no sound played, new owner is neutral \
        end\
    end \
\
    if aZone.conqueredFlag then \
        cfxZones.pollFlag(aZone.conqueredFlag, \"inc\", aZone)\
    end \
    \
    if theSide == 1 and aZone.redCap then \
        cfxZones.pollFlag(aZone.redCap, \"inc\", aZone)\
    end\
    \
    if formerOwner == 1 and aZone.redLost then \
        cfxZones.pollFlag(aZone.redLost, \"inc\", aZone)\
    end\
    \
    if theSide == 2 and aZone.blueCap then \
        cfxZones.pollFlag(aZone.blueCap, \"inc\", aZone)\
    end\
    \
    if formerOwner == 2 and aZone.blueLost then \
        cfxZones.pollFlag(aZone.blueLost, \"inc\", aZone)\
    end\
    \
    if theSide == 0 and aZone.neutralCap then \
        cfxZones.pollFlag(aZone.neutralCap, \"inc\", aZone)\
    end\
    \
    -- invoke callbacks now\
    cfxOwnedZones.invokeConqueredCallbacks(aZone, theSide, formerOwner)\
    \
    -- bang! flag support \
    cfxOwnedZones.bangSide(theSide, 1) -- winner \
    cfxOwnedZones.bangSide(formerOwner, -1) -- loser \
    \
    -- update map\
    cfxOwnedZones.drawZoneInMap(aZone) -- update status in map. will erase previous version \
\
end\
\
function cfxOwnedZones.update()\
    -- to speed this up we might only want to check the first unit \
    -- in group, and if inside, count the entire group as inside \
    -- new. unit counting update \
    cfxOwnedZones.updateSchedule = timer.scheduleFunction(cfxOwnedZones.update, {}, timer.getTime() + 1/cfxOwnedZones.ups)\
    -- iterate all groups and their units to count how many \
    -- units are in each zone \
    for idz, theZone in pairs(cfxOwnedZones.zones) do \
        theZone.numRed = 0\
        theZone.numBlue = 0 \
        -- count red units\
        local allRed = coalition.getGroups(1, Group.Category.GROUND)\
        for idx, aGroup in pairs(allRed) do \
            if Group.isExist(aGroup) then \
                if cfxOwnedZones.fastEval then \
                    -- we only check first unit that is alive\
                    local theUnit = dcsCommon.getGroupUnit(aGroup)\
                    if theUnit and cfxZones.unitInZone(theUnit, theZone) then\
                        theZone.numRed = theZone.numRed + aGroup:getSize()\
                    end\
                else \
                    local allUnits = aGroup:getUnits() \
                    for idy, theUnit in pairs(allUnits) do \
                        if cfxZones.unitInZone(theUnit, theZone) then \
                            theZone.numRed = theZone.numRed + 1\
                        end\
                    end\
                end\
            end\
        end\
        -- count blue units \
        local allBlue = coalition.getGroups(2, Group.Category.GROUND)\
        for idx, aGroup in pairs(allBlue) do \
            if Group.isExist(aGroup) then \
                if cfxOwnedZones.fastEval then \
                    -- we only check first unit that is alive\
                    local theUnit = dcsCommon.getGroupUnit(aGroup)\
                    if theUnit and cfxZones.unitInZone(theUnit, theZone) then\
                        theZone.numBlue = theZone.numBlue + aGroup:getSize()\
                    end\
                else \
                    local allUnits = aGroup:getUnits() \
                    for idy, theUnit in pairs(allUnits) do \
                        if cfxZones.unitInZone(theUnit, theZone) then\
                            theZone.numBlue = theZone.numBlue + 1\
                        end\
                    end\
                end\
            end\
        end\
        -- trigger.action.outText(theZone.name .. \" blue: \" .. theZone.numBlue .. \" red \" .. theZone.numRed, 30)\
        local lastOwner = theZone.owner\
        local newOwner = 0 -- neutral is default \
        if theZone.unbeatable then -- Parker Lewis can't lose. Neither this zone.\
            newOwner = lastOwner \
        end\
        \
        -- determine new owner \
        if theZone.unbeatable then \
            -- we do nothing \
        elseif theZone.numRed < 1 and theZone.numBlue < 1 then \
            -- no troops here. Become neutral?\
            if cfxOwnedZones.numKeep < 1 then \
                newOwner = lastOwner -- keep it, else turns neutral\
            else \
                -- noone here, zone becomes neutral\
                newOwner = 0 -- not strictly required. to be explicit \
            end\
        elseif theZone.numRed < 1 then \
            -- only blue here. enough to keep? \
            if theZone.numBlue >= cfxOwnedZones.numCap then \
                newOwner = 2 -- blue owns it\
            elseif lastOwner == 2 and theZone.numBlue >= cfxOwnedZones.numKeep then \
                -- enough to keep if owned before\
                newOwner = 2\
            else \
                newOwner = 0 -- just to make it explicit\
            end \
        elseif theZone.numBlue < 1 then \
            -- only red here. enough to keep?\
            if theZone.numRed >= cfxOwnedZones.numCap then \
                newOwner = 1 \
            elseif lastOwner == 1 and theZone.numRed >= cfxOwnedZones.numKeep then \
                newOwner = 1 \
            else \
                newOwner = 0 \
            end                 \
        else \
            -- blue and red units here.\
            -- owner keeps hanging on only they have enough \
            -- units left\
            if cfxOwnedZones.easyContest then \
                -- this zone is immediately contested\
                newOwner = 0 -- just to be explicit \
            elseif cfxOwnedZones.numKeep < 1 then \
                -- old owner keeps it until none left \
                newOwner = lastOwner\
            else\
                if lastOwner == 1 then \
                    -- red can keep it as long as enough units here \
                    if theZone.numRed >= cfxOwnedZones.numKeep then \
                        newOwner = 1\
                    end -- else 0\
                elseif lastOwner == 2 then\
                    -- blue can keep it if enough units here\
                    if theZone.numBlue >= cfxOwnedZones.numKeep then \
                        newOwner = 2\
                    end -- else 0 \
                else -- stay 0 \
                end\
            end\
        end\
    \
        -- now see if owner changed, and react accordingly \
        if newOwner == lastOwner then \
            -- nothing happened, do nothing \
        else \
            trigger.action.outText(theZone.name .. \" change hands from  \" .. lastOwner .. \" to \" .. newOwner, 30)\
            if newOwner == 0 then -- zone turned neutral \
                cfxOwnedZones.zoneConquered(theZone, newOwner, lastOwner)\
            else\
                cfxOwnedZones.zoneConquered(theZone, newOwner, lastOwner)\
            end\
        end\
        theZone.owner = newOwner\
        \
        -- update ownership flag if exists\
        if theZone.ownedBy then \
            cfxZones.setFlagValue(theZone.ownedBy, theZone.owner, theZone)\
        end\
        \
    end -- iterating all zones \
\
end\
\
function cfxOwnedZones.sideOwnsAll(theSide) \
    for key, aZone in pairs(cfxOwnedZones.zones) do \
        if aZone.owner ~= theSide then \
            return false\
        end\
    end\
    -- if we get here, all your base are belong to us \
    return true\
end\
\
function cfxOwnedZones.hasOwnedZones() \
    for idx, zone in pairs (cfxOwnedZones.zones) do\
        return true -- even the first returns true\
    end\
    -- no owned zones\
    return false \
end\
\
-- getting closest owned zones etc\
-- required for groundTroops and factory attackers \
-- methods provided only for other modules (e.g. cfxGroundTroops or \
-- factoryZone \
--\
\
function cfxOwnedZones.collectZones(mode)\
    return cfxOwnedZones.zones \
    --if not mode then mode = \"OWNED\" end \
    -- Note: since cfxGroundTroops currently simply uses owner flag\
    -- we cannot migrate to a differentiation between factory and \
    -- owned. All produced attackers always attack owned zones.\
end\
\
function cfxOwnedZones.getEnemyZonesFor(aCoalition) \
    local enemyZones = {}\
    local allZones = cfxOwnedZones.collectZones()  \
    local ourEnemy = dcsCommon.getEnemyCoalitionFor(aCoalition)\
    for zKey, aZone in pairs(allZones) do \
        if aZone.owner == ourEnemy then -- only check enemy owned zones\
            -- note: will include untargetable zones \
            table.insert(enemyZones, aZone)            \
        end\
    end\
    return enemyZones\
end\
\
function cfxOwnedZones.getNearestOwnedZoneToPoint(aPoint)\
    local shortestDist = math.huge\
    local closestZone = nil\
    local allZones = cfxOwnedZones.collectZones() \
    \
    for zKey, aZone in pairs(allZones) do \
        local zPoint = cfxZones.getPoint(aZone) \
        currDist = dcsCommon.dist(zPoint, aPoint)\
        if aZone.untargetable ~= true and \
           currDist < shortestDist then \
            shortestDist = currDist\
            closestZone = aZone\
        end\
    end\
    \
    return closestZone, shortestDist\
end\
\
function cfxOwnedZones.getNearestOwnedZone(theZone)\
    local shortestDist = math.huge\
    local closestZone = nil\
    local aPoint = cfxZones.getPoint(theZone)\
    local allZones = cfxOwnedZones.collectZones()\
    for zKey, aZone in pairs(allZones) do\
        local zPoint = cfxZones.getPoint(aZone) \
        currDist = dcsCommon.dist(zPoint, aPoint)\
        if aZone.untargetable ~= true and currDist < shortestDist then \
            shortestDist = currDist\
            closestZone = aZone\
        end\
    end\
    \
    return closestZone, shortestDist\
end\
\
function cfxOwnedZones.getNearestEnemyOwnedZone(theZone, targetNeutral)\
    if not targetNeutral then targetNeutral = false else targetNeutral = true end\
    local shortestDist = math.huge\
    local closestZone = nil\
    local allZones = cfxOwnedZones.collectZones()\
    local ourEnemy = dcsCommon.getEnemyCoalitionFor(theZone.owner)\
    if not ourEnemy then return nil end -- we called for a neutral zone. they have no enemies \
    local zPoint = cfxZones.getPoint(theZone)\
    \
    for zKey, aZone in pairs(allZones) do \
        if targetNeutral then \
            -- return all zones that do not belong to us\
            if aZone.owner ~= theZone.owner then \
                local aPoint = cfxZones.getPoint(aZone)\
                currDist = dcsCommon.dist(aPoint, zPoint)\
                if aZone.untargetable ~= true and currDist < shortestDist then \
                    shortestDist = currDist\
                    closestZone = aZone\
                end\
            end\
        else \
            -- return zones that are taken by the Enenmy\
            if aZone.owner == ourEnemy then -- only check own zones\
                local aPoint = cfxZones.getPoint(aZone)\
                currDist = dcsCommon.dist(zPoint, aPoint)\
                if aZone.untargetable ~= true and currDist < shortestDist then \
                    shortestDist = currDist\
                    closestZone = aZone\
                end\
            end\
        end \
    end\
    \
    return closestZone, shortestDist\
end\
\
function cfxOwnedZones.getNearestFriendlyZone(theZone, targetNeutral)\
    if not targetNeutral then targetNeutral = false else targetNeutral = true end\
    local shortestDist = math.huge\
    local closestZone = nil\
    local ourEnemy = dcsCommon.getEnemyCoalitionFor(theZone.owner)\
    if not ourEnemy then return nil end -- we called for a neutral zone. they have no enemies nor friends, all zones would be legal.\
    local zPoint = cfxZones.getPoint(theZone)\
    local allZones = cfxOwnedZones.collectZones() \
\
    for zKey, aZone in pairs(allZones) do \
        if targetNeutral then \
            -- target all zones that do not belong to the enemy\
            if aZone.owner ~= ourEnemy then\
                local aPoint = cfxZones.getPoint(aZone)\
                currDist = dcsCommon.dist(zPoint, aPoint)\
                if aZone.untargetable ~= true and currDist < shortestDist then \
                    shortestDist = currDist\
                    closestZone = aZone\
                end\
            end\
        else \
            -- only target zones that are taken by us\
            if aZone.owner == theZone.owner then -- only check own zones\
                local aPoint = cfxZones.getPoint(aZone)\
                currDist = dcsCommon.dist(zPoint, aPoint)\
                if aZone.untargetable ~= true and currDist < shortestDist then \
                    shortestDist = currDist\
                    closestZone = aZone\
                end\
            end\
        end \
    end\
    \
    return closestZone, shortestDist\
end\
\
function cfxOwnedZones.enemiesRemaining(aZone)\
    if cfxOwnedZones.getNearestEnemyOwnedZone(aZone) then return true end\
    return false\
end\
\
--\
-- load / save data \
--\
\
function cfxOwnedZones.saveData()\
    -- this is called from persistence when it's time to \
    -- save data. returns a table with all my data \
    local theData = {}\
    local allZoneData = {}\
    -- iterate all my zones and create data \
    for idx, theZone in pairs(cfxOwnedZones.zones) do\
        local zoneData = {}\
\
        if theZone.conqueredFlag then \
            zoneData.conquered = cfxZones.getFlagValue(theZone.conqueredFlag, theZone)\
        end \
\
        zoneData.owner = theZone.owner \
        allZoneData[theZone.name] = zoneData\
    end\
    \
    -- now iterate all attack groups that we have spawned and that \
    -- (maybe) are still alive \
    -- now write the info for the flags that we output for #red, etc\
    local flagInfo = {}\
    flagInfo.neutral = cfxZones.getFlagValue(cfxOwnedZones.neutralTriggerFlag, cfxOwnedZones)\
    flagInfo.red = cfxZones.getFlagValue(cfxOwnedZones.redTriggerFlag, cfxOwnedZones)\
    flagInfo.blue = cfxZones.getFlagValue(cfxOwnedZones.blueTriggerFlag, cfxOwnedZones)\
    -- assemble the data \
    theData.zoneData = allZoneData\
    theData.flagInfo = flagInfo\
    \
    -- return it \
    return theData\
end\
\
function cfxOwnedZones.loadData()\
    -- remember to draw in map with new owner \
    if not persistence then return end \
    local theData = persistence.getSavedDataForModule(\"cfxOwnedZones\")\
    if not theData then \
        if cfxOwnedZones.verbose then \
            trigger.action.outText(\"owdZ: no save date received, skipping.\", 30)\
        end\
        return\
    end\
    -- theData contains the following tables:\
    --   zoneData: per-zone data \
    --   flagInfo: module-global flags \
    --   attackers: all spawned attackers that we feed to groundTroops\
    local allZoneData = theData.zoneData \
    for zName, zData in pairs(allZoneData) do \
        -- access zone \
        local theZone = cfxOwnedZones.getOwnedZoneByName(zName)\
        if theZone then \
            theZone.owner = zData.owner \
            if zData.conquered then \
                cfxZones.setFlagValue(theZone.conqueredFlag, zData.conquered, theZone)\
            end\
            -- update mark in map \
            cfxOwnedZones.drawZoneInMap(theZone)\
        else \
            trigger.action.outText(\"owdZ: load - data mismatch: cannot find zone <\" .. zName .. \">, skipping zone.\", 30)\
        end\
    end\
    \
    -- now process module global flags \
    local flagInfo = theData.flagInfo\
    if flagInfo then \
        cfxZones.setFlagValue(cfxOwnedZones.neutralTriggerFlag, flagInfo.neutral, cfxOwnedZones)\
        cfxZones.setFlagValue(cfxOwnedZones.redTriggerFlag, flagInfo.red, cfxOwnedZones)\
        cfxZones.setFlagValue(cfxOwnedZones.blueTriggerFlag, flagInfo.blue, cfxOwnedZones)\
    end\
end\
\
 \
--\
function cfxOwnedZones.readConfigZone(theZone)\
    if not theZone then theZone = cfxZones.createSimpleZone(\"ownedZonesConfig\") end \
    \
    cfxOwnedZones.name = \"cfxOwnedZones\" -- just in case, so we can access with cfxZones \
    cfxOwnedZones.verbose = cfxZones.getBoolFromZoneProperty(theZone, \"verbose\", false)\
    cfxOwnedZones.announcer = cfxZones.getBoolFromZoneProperty(theZone, \"announcer\", true)\
    \
    cfxOwnedZones.redTriggerFlag = cfxZones.getStringFromZoneProperty(theZone, \"r!\", \"*<cfxnone>\")\
    cfxOwnedZones.blueTriggerFlag = cfxZones.getStringFromZoneProperty(theZone, \"b!\", \"*<cfxnone>\")\
    cfxOwnedZones.neutralTriggerFlag = cfxZones.getStringFromZoneProperty(theZone, \"n!\", \"*<cfxnone>\")\
\
    -- numKeep, numCap, fastEval, easyContest\
    cfxOwnedZones.numCap = cfxZones.getNumberFromZoneProperty(theZone, \"numCap\", 1) -- minimal number of units required to cap zone \
    cfxOwnedZones.numKeep = cfxZones.getNumberFromZoneProperty(theZone, \"numKeep\", 0) -- number required to keep zone \
    cfxOwnedZones.fastEval = cfxZones.getBoolFromZoneProperty(theZone, \"fastEval\", true)\
    cfxOwnedZones.easyContest = cfxZones.getBoolFromZoneProperty(theZone, \"easyContest\", false)\
    -- winSound, loseSound \
    cfxOwnedZones.winSound = cfxZones.getStringFromZoneProperty(theZone, \"winSound\", \"Quest Snare 3.wav\" )\
    cfxOwnedZones.loseSound = cfxZones.getStringFromZoneProperty(theZone, \"loseSound\", \"Death BRASS.wav\")\
end\
\
function cfxOwnedZones.init()\
    -- check libs\
    if not dcsCommon.libCheck(\"cfx Owned Zones\", \
        cfxOwnedZones.requiredLibs) then\
        return false \
    end\
\
    -- read my config zone\
    local theZone = cfxZones.getZoneByName(\"ownedZonesConfig\") \
    cfxOwnedZones.readConfigZone(theZone)\
\
    \
    -- collect all owned zones by their 'owner' property \
    -- start the process\
    local pZones = cfxZones.zonesWithProperty(\"owner\")\
    \
    -- now add all zones to my zones table, and convert the owner property into \
    -- a proper attribute \
    for k, aZone in pairs(pZones) do\
        cfxOwnedZones.addOwnedZone(aZone)\
    end\
    \
    if persistence then \
        -- sign up for persistence \
        callbacks = {}\
        callbacks.persistData = cfxOwnedZones.saveData\
        persistence.registerModule(\"cfxOwnedZones\", callbacks)\
        -- now load my data \
        cfxOwnedZones.loadData()\
    end\
    \
    initialized = true \
    cfxOwnedZones.updateSchedule = timer.scheduleFunction(cfxOwnedZones.update, {}, timer.getTime() + 1/cfxOwnedZones.ups)\
    \
    trigger.action.outText(\"cx/x owned zones v\".. cfxOwnedZones.version .. \" started\", 30)\
    return true \
end\
\
if not cfxOwnedZones.init() then \
    trigger.action.outText(\"cf/x Owned Zones aborted: missing libraries\", 30)\
    cfxOwnedZones = nil \
end\
\
\
\
",
                    ["predicate"] = "a_do_script",
                }, -- end of [5]
                [6] = 
                {
                    ["text"] = "factoryZone = {}\
factoryZone.version = \"1.0.0\"\
factoryZone.verbose = false \
factoryZone.name = \"factoryZone\" \
\
--[[-- VERSION HISTORY\
\
1.0.0 - refactored production part from cfxOwnedZones 1.xpcall\
\
--]]--\
factoryZone.requiredLibs = {\
    \"dcsCommon\",\
    \"cfxZones\",  \
    \"cfxCommander\", -- to make troops do stuff\
    \"cfxOwnedZones\" -- attackers rely on this \
}\
\
factoryZone.zones = {} -- my factory zones \
factoryZone.ups = 1\
factoryZone.initialized = false \
factoryZone.defendingTime = 100 -- seconds until new defenders are produced\
factoryZone.attackingTime = 300 -- seconds until new attackers are produced \
factoryZone.shockTime = 200 -- 'shocked' period of inactivity\
factoryZone.repairTime = 200 -- time until we raplace one lost unit, also repairs all other units to 100%  \
\
-- persistence: all attackers we ever sent out.\
-- is regularly verified and cut to size \
factoryZone.spawnedAttackers = {}\
\
-- factoryZone is a module that manages production of units\
-- inside zones and can switch production based on who owns the \
-- zone. Zone ownership can by dynamic (by using OwnedZones or \
-- using scripts to change the 'owner' flag\
--\
-- *** EXTENTDS ZONES ***\
--\
-- zone attributes when owned\
--  owner: coalition that owns the zone. Managed externally\
--  status: FSM for spawning\
--  defendersRED/BLUE - coma separated type string for the group to spawn on defense cycle completion\
--  attackersRED/BLUE - as above for attack cycle. \
--  timeStamp - time when zone switched into current state \
--  spawnRadius - overrides zone's radius when placing defenders. can be use to place defenders inside or outside zone itself\
--  formation - defender's formation\
--  attackFormation - attackers formation \
--  attackRadius - radius of circle in which attackers are spawned. informs formation \
--  attackDelta - polar coord: r from zone center where attackers are spawned\
--  attackPhi - polar degrees where attackers are to be spawned\
--  paused - will not spawn. default is false \
--  unbeatable - can't be conquered by other side. default is false\
--  untargetable - will not be targeted by either side. make unbeatable\
--  owned zones untargetable, or they'll become a troop magnet for \
--  zoneAttackers \
\
--\
-- M I S C\
--\
\
\
function factoryZone.getFactoryZoneByName(zName)\
    for zKey, theZone in pairs (factoryZone.zones) do \
        if theZone.name == zName then return theZone end \
    end\
    return nil\
end\
\
function factoryZone.addFactoryZone(aZone)\
    aZone.worksFor = cfxZones.getCoalitionFromZoneProperty(aZone, \"factory\", 0) -- currently unused, have RED/BLUE separate types \
    aZone.state = \"init\"\
    aZone.timeStamp = timer.getTime()\
    aZone.defendersRED = cfxZones.getStringFromZoneProperty(aZone, \"defendersRED\", \"none\")\
    aZone.defendersBLUE = cfxZones.getStringFromZoneProperty(aZone, \"defendersBLUE\", \"none\")\
    if cfxZones.hasProperty(aZone, \"attackersRED\") then \
        -- legacy support\
        aZone.attackersRED = cfxZones.getStringFromZoneProperty(aZone, \"attackersRED\", \"none\")\
    else\
        aZone.attackersRED = cfxZones.getStringFromZoneProperty(aZone, \"productionRED\", \"none\")\
    end\
    \
    if cfxZones.hasProperty(aZone, \"attackersBLUE\") then     \
        -- legacy support \
        aZone.attackersBLUE = cfxZones.getStringFromZoneProperty(aZone, \"attackersBLUE\", \"none\")\
    else \
        aZone.attackersBLUE = cfxZones.getStringFromZoneProperty(aZone, \"productionBLUE\", \"none\")\
    end\
    \
    aZone.formation = cfxZones.getStringFromZoneProperty(aZone, \"formation\", \"circle_out\")\
    aZone.attackFormation = cfxZones.getStringFromZoneProperty(aZone, \"attackFormation\", \"circle_out\") -- cfxZones.getZoneProperty(aZone, \"attackFormation\")\
    aZone.spawnRadius = cfxZones.getNumberFromZoneProperty(aZone, \"spawnRadius\", aZone.radius-5) -- \"-5\" so they remaininside radius \
    aZone.attackRadius = cfxZones.getNumberFromZoneProperty(aZone, \"attackRadius\", aZone.radius)\
    aZone.attackDelta = cfxZones.getNumberFromZoneProperty(aZone, \"attackDelta\", 10) -- aZone.radius)\
    aZone.attackPhi = cfxZones.getNumberFromZoneProperty(aZone, \"attackPhi\", 0)\
    \
    aZone.paused = cfxZones.getBoolFromZoneProperty(aZone, \"paused\", false)\
    aZone.factoryOwner = aZone.owner -- copy so we can compare next round\
    \
    -- pause? and activate?\
    if cfxZones.hasProperty(aZone, \"pause?\") then \
        aZone.pauseFlag = cfxZones.getStringFromZoneProperty(aZone, \"pause?\", \"none\")\
        aZone.lastPauseValue = trigger.misc.getUserFlag(aZone.pauseFlag)\
    end\
    \
    if cfxZones.hasProperty(aZone, \"activate?\") then \
        aZone.activateFlag = cfxZones.getStringFromZoneProperty(aZone, \"activate?\", \"none\")\
        aZone.lastActivateValue = trigger.misc.getUserFlag(aZone.activateFlag)\
    end\
    \
    aZone.factoryTriggerMethod = cfxZones.getStringFromZoneProperty(aZone, \"triggerMethod\", \"change\")\
    if cfxZones.hasProperty(aZone, \"factoryTriggerMethod\") then \
        aZone.factoryTriggerMethod = cfxZones.getStringFromZoneProperty(aZone, \"factoryTriggerMethod\", \"change\")\
    end\
    \
    factoryZone.zones[aZone.name] = aZone \
    factoryZone.verifyZone(aZone)\
end\
\
function factoryZone.verifyZone(aZone)\
    -- do some sanity checks\
    if not cfxGroundTroops and (aZone.attackersRED ~= \"none\" or aZone.attackersBLUE ~= \"none\") then \
        trigger.action.outText(\"+++factZ: \" .. aZone.name .. \" attackers need cfxGroundTroops to function\", 30)\
    end\
    \
end\
\
--[[--\
function factoryZone.collectZones(mode)\
    if not mode then mode = \"OWNED\" end \
    -- Note: since cfxGroundTroops currently simply uses owner flag\
    -- we cannot migrate to a differentiation between factory and \
    -- owned. All produced attackers always attack owned zones.\
    \
    -- collect zones: all zones from DML, ownedZones, factory, owned&factory \
    -- controlled with config.targetZones parameter \
    -- CLASSIC = factory & target, ALL = all DML, FACTORY = factory zones only, OWNED = owned only.\
    if mode == \"ALL\" then \
        return cfxZones.zones\
        \
    elseif mode == \"FACTORY\" then\
        if cfxOwnedZones and cfxOwnedZones.zones then \
            return cfxOwnedZones.zones\
        end \
        if factoryZone.verbose then \
            trigger.action.outText(\"+++factZ: 'OWNED' targetZones attribute without cfxOwnedZones. Returning all zones.\", 30)\
        end\
        return cfxZones.zones\
        \
    elseif mode == \"FACTORY\" then\
        return factoryZone.zones\
\
    elseif mode == \"CLASSIC\" then\
        if not cfxOwnedZones and cfxOwnedZones.zones then \
            return factoryZone.zones \
        end\
        -- combine ownedZones and factoryZone\
        return dcsCommon.combineTables(cfxOwnedZones.zones, factoryZone.zones)\
    else \
        trigger.action.outText(\"+++factZ: illegal targetZones value <\" .. factoryZone.targetZones .. \">, using 'ALL'\", 30)\
        return cfxZones.zones \
    end\
end\
\
function factoryZone.getEnemyZonesFor(aCoalition) \
    -- when cfxOwnedZones is present, or it will return only those \
    -- else it scans all zones from cfxZones \
    local enemyZones = {}\
    local allZones = factoryZone.collectZones() --cfxZones.zones\
--    if cfxOwnedZones then \
--        allZones = cfxOwnedZones.zones\
--    end \
    local ourEnemy = dcsCommon.getEnemyCoalitionFor(aCoalition)\
    for zKey, aZone in pairs(allZones) do \
        if aZone.owner == ourEnemy then -- only check enemy owned zones\
            -- note: will include untargetable zones \
            table.insert(enemyZones, aZone)            \
        end\
    end\
    return enemyZones\
end\
\
function factoryZone.getNearestOwnedZoneToPoint(aPoint)\
    local shortestDist = math.huge\
    -- when cfxOwnedZones is present, or it will return only those \
    -- else it scans all zones from cfxZones \
    local closestZone = nil\
    local allZones = factoryZone.collectZones() --cfxZones.zones\
--    if cfxOwnedZones then \
--        allZones = cfxOwnedZones.zones\
--    end \
    for zKey, aZone in pairs(allZones) do \
        local zPoint = cfxZones.getPoint(aZone) \
        currDist = dcsCommon.dist(zPoint, aPoint)\
        if aZone.untargetable ~= true and \
           currDist < shortestDist then \
            shortestDist = currDist\
            closestZone = aZone\
        end\
    end\
    \
    return closestZone, shortestDist\
end\
\
function factoryZone.getNearestOwnedZone(theZone)\
    local shortestDist = math.huge\
    -- when cfxOwnedZones is present, or it will return only those \
    -- else it scans all zones from cfxZones \
    local closestZone = nil\
    local aPoint = cfxZones.getPoint(theZone)\
    local allZones = factoryZone.collectZones() --cfxZones.zones\
--    if cfxOwnedZones then \
--        allZones = cfxOwnedZones.zones\
--    end \
    for zKey, aZone in pairs(allZones) do\
        local zPoint = cfxZones.getPoint(aZone) \
        currDist = dcsCommon.dist(zPoint, aPoint)\
        if aZone.untargetable ~= true and currDist < shortestDist then \
            shortestDist = currDist\
            closestZone = aZone\
        end\
    end\
    \
    return closestZone, shortestDist\
end\
\
function factoryZone.getNearestEnemyOwnedZone(theZone, targetNeutral)\
    if not targetNeutral then targetNeutral = false else targetNeutral = true end\
    local shortestDist = math.huge\
    local closestZone = nil\
    -- when cfxOwnedZones is present, or it will return only those \
    -- else it scans all zones from cfxZones \
    local allZones = factoryZone.collectZones() --cfxZones.zones\
--    if cfxOwnedZones then \
--        allZones = cfxOwnedZones.zones\
--    end \
    local ourEnemy = dcsCommon.getEnemyCoalitionFor(theZone.owner)\
    if not ourEnemy then return nil end -- we called for a neutral zone. they have no enemies \
    local zPoint = cfxZones.getPoint(theZone)\
    \
    for zKey, aZone in pairs(allZones) do \
        if targetNeutral then \
            -- return all zones that do not belong to us\
            if aZone.owner ~= theZone.owner then \
                local aPoint = cfxZones.getPoint(aZone)\
                currDist = dcsCommon.dist(aPoint, zPoint)\
                if aZone.untargetable ~= true and currDist < shortestDist then \
                    shortestDist = currDist\
                    closestZone = aZone\
                end\
            end\
        else \
            -- return zones that are taken by the Enenmy\
            if aZone.owner == ourEnemy then -- only check own zones\
                local aPoint = cfxZones.getPoint(aZone)\
                currDist = dcsCommon.dist(zPoint, aPoint)\
                if aZone.untargetable ~= true and currDist < shortestDist then \
                    shortestDist = currDist\
                    closestZone = aZone\
                end\
            end\
        end \
    end\
    \
    return closestZone, shortestDist\
end\
\
function factoryZone.getNearestFriendlyZone(theZone, targetNeutral)\
    if not targetNeutral then targetNeutral = false else targetNeutral = true end\
    local shortestDist = math.huge\
    local closestZone = nil\
    local ourEnemy = dcsCommon.getEnemyCoalitionFor(theZone.owner)\
    if not ourEnemy then return nil end -- we called for a neutral zone. they have no enemies nor friends, all zones would be legal.\
    local zPoint = cfxZones.getPoint(theZone)\
    -- when cfxOwnedZones is present, or it will return only those \
    -- else it scans all zones from cfxZones \
    local allZones = factoryZone.collectZones() --cfxZones.zones\
--    if cfxOwnedZones then \
--        allZones = cfxOwnedZones.zones\
--    end\
    for zKey, aZone in pairs(allZones) do \
        if targetNeutral then \
            -- target all zones that do not belong to the enemy\
            if aZone.owner ~= ourEnemy then\
                local aPoint = cfxZones.getPoint(aZone)\
                currDist = dcsCommon.dist(zPoint, aPoint)\
                if aZone.untargetable ~= true and currDist < shortestDist then \
                    shortestDist = currDist\
                    closestZone = aZone\
                end\
            end\
        else \
            -- only target zones that are taken by us\
            if aZone.owner == theZone.owner then -- only check own zones\
                local aPoint = cfxZones.getPoint(aZone)\
                currDist = dcsCommon.dist(zPoint, aPoint)\
                if aZone.untargetable ~= true and currDist < shortestDist then \
                    shortestDist = currDist\
                    closestZone = aZone\
                end\
            end\
        end \
    end\
    \
    return closestZone, shortestDist\
end\
--]]--\
--[[--\
function factoryZone.enemiesRemaining(aZone)\
    if factoryZone.getNearestEnemyOwnedZone(aZone) then return true end\
    return false\
end\
--]]--\
\
function factoryZone.spawnAttackTroops(theTypes, aZone, aCoalition, aFormation)\
    local unitTypes = {} -- build type names\
    -- split theTypes into an array of types\
    unitTypes = dcsCommon.splitString(theTypes, \",\")\
    if #unitTypes < 1 then \
        table.insert(unitTypes, \"Soldier M4\") -- make it one m4 trooper as fallback\
        -- simply exit, no troops specified \
        if factoryZone.verbose then \
            trigger.action.outText(\"+++factZ: no attackers for \" .. aZone.name .. \". exiting\", 30)\
        end\
        return\
    end\
    \
    if factoryZone.verbose then \
        trigger.action.outText(\"+++factZ: spawning attackers for \" .. aZone.name, 30)\
    end\
            \
    local spawnPoint = {x = aZone.point.x, y = aZone.point.y, z = aZone.point.z} -- copy struct \
    \
    local rads = aZone.attackPhi * 0.01745\
    spawnPoint.x = spawnPoint.x + math.cos(aZone.attackPhi) * aZone.attackDelta\
    spawnPoint.y = spawnPoint.y + math.sin(aZone.attackPhi) * aZone.attackDelta \
    \
    local spawnZone = cfxZones.createSimpleZone(\"attkSpawnZone\", spawnPoint, aZone.attackRadius)\
    \
    local theGroup, theData = cfxZones.createGroundUnitsInZoneForCoalition (\
                aCoalition, -- theCountry,                            \
                aZone.name .. \" (A) \" .. dcsCommon.numberUUID(), -- must be unique \
                spawnZone,                                             \
                unitTypes,                                                     \
                aFormation, -- outward facing\
                0)\
    return theGroup, theData\
end\
\
function factoryZone.spawnDefensiveTroops(theTypes, aZone, aCoalition, aFormation)\
    local unitTypes = {} -- build type names\
    -- split theTypes into an array of types\
    unitTypes = dcsCommon.splitString(theTypes, \",\")\
    if #unitTypes < 1 then \
        table.insert(unitTypes, \"Soldier M4\") -- make it one m4 trooper as fallback\
        -- simply exit, no troops specified \
        if factoryZone.verbose then \
            trigger.action.outText(\"+++factZ: no defenders for \" .. aZone.name .. \". exiting\", 30)\
        end\
        return\
    end\
    \
    --local theCountry = dcsCommon.coalition2county(aCoalition) \
    local spawnZone = cfxZones.createSimpleZone(\"spawnZone\", aZone.point, aZone.spawnRadius)\
    local theGroup, theData = cfxZones.createGroundUnitsInZoneForCoalition (\
                aCoalition, --theCountry,                \
                aZone.name .. \" (D) \" .. dcsCommon.numberUUID(), -- must be unique \
                spawnZone,                                         unitTypes,\
                aFormation, -- outward facing\
                0)\
    return theGroup, theData\
end\
\
--\
-- U P D A T E \
--\
\
function factoryZone.sendOutAttackers(aZone)\
    -- sanity check: never done for neutral zones \
    if aZone.owner == 0 then \
        if aZone.verbose or factoryZone.verbose then \
            trigger.action.outText(\"+++factZ: SendAttackers invoked for NEUTRAL zone <\" .. aZone.name .. \">\", 30)\
        end\
        return \
    end\
    \
    -- only spawn if there are zones to attack\
    if not cfxOwnedZones.enemiesRemaining(aZone) then \
        if factoryZone.verbose then \
            trigger.action.outText(\"+++factZ - no enemies, resting \".. aZone.name, 30)\
        end\
        return \
    end\
\
    if factoryZone.verbose then \
        trigger.action.outText(\"+++factZ - attack cycle for \".. aZone.name, 30)\
    end\
\
    -- step one: get the attackers \
    local attackers = aZone.attackersRED;\
    if (aZone.owner == 2) then attackers = aZone.attackersBLUE end\
\
    if attackers == \"none\" then return end \
\
    local theGroup, theData = factoryZone.spawnAttackTroops(attackers, aZone, aZone.owner, aZone.attackFormation)\
    \
    local troopData = {}\
    troopData.groupData = theData\
    troopData.orders = \"attackOwnedZone\" -- lazy coding! \
    troopData.side = aZone.owner\
    factoryZone.spawnedAttackers[theData.name] = troopData \
    \
    -- submit them to ground troops handler as zoneseekers \
    -- and our groundTroops module will handle the rest \
    if cfxGroundTroops then \
        local troops = cfxGroundTroops.createGroundTroops(theGroup)\
        troops.orders = \"attackOwnedZone\"\
        troops.side = aZone.owner\
        cfxGroundTroops.addGroundTroopsToPool(troops) -- hand off to ground troops\
    else \
        if factoryZone.verbose then \
            trigger.action.outText(\"+++ Owned Zones: no ground troops module on send out attackers\", 30)\
        end \
    end\
end\
\
\
function factoryZone.repairDefenders(aZone)\
    -- sanity check: never done for non-neutral zones \
    if aZone.owner == 0 then \
        if aZone.verbose or factoryZone.verbose then \
            trigger.action.outText(\"+++factZ: repairDefenders invoked for NEUTRAL zone <\" .. aZone.name .. \">\", 30)\
        end\
        return \
    end\
    \
    -- find a unit that is missing from my typestring and replace it \
    -- one by one until we are back to full strength\
    -- step one: get the defenders and create a type array \
    local defenders = aZone.defendersRED;\
    if (aZone.owner == 2) then defenders = aZone.defendersBLUE end\
    local unitTypes = {} -- build type names\
    \
    -- if none, we are done\
    if defenders == \"none\" then return end \
\
    -- split theTypes into an array of types    \
    allTypes = dcsCommon.trimArray(\
            dcsCommon.splitString(defenders, \",\")\
        )\
    local livingTypes = {} -- init to emtpy, so we can add to it if none are alive\
    if (aZone.defenders) then \
        -- some remain. add one of the killed\
        livingTypes = dcsCommon.getGroupTypes(aZone.defenders)\
        -- we now iterate over the living types, and remove their \
        -- counterparts from the allTypes. We then take the first that \
        -- is left\
        \
        if #livingTypes > 0 then \
            for key, aType in pairs (livingTypes) do \
                if not dcsCommon.findAndRemoveFromTable(allTypes, aType) then \
                    trigger.action.outText(\"+++factZ WARNING: found unmatched type <\" .. aType .. \"> while trying to repair defenders for \".. aZone.name, 30)\
                else \
                    -- all good\
                end \
            end\
        end \
    end\
    \
    -- when we get here, allTypes is reduced to those that have been killed \
    if #allTypes < 1 then \
        trigger.action.outText(\"+++factZ: WARNING: all types exist when repairing defenders for \".. aZone.name, 30)\
    else \
        table.insert(livingTypes, allTypes[1]) -- we simply use the first that we find\
    end\
    -- remove the old defenders\
    if aZone.defenders then \
        aZone.defenders:destroy()\
    end\
    \
    -- now livingTypes holds the full array of units we need to spawn \
    local theCountry = dcsCommon.getACountryForCoalition(aZone.owner) \
    local spawnZone = cfxZones.createSimpleZone(\"spawnZone\", aZone.point, aZone.spawnRadius)\
    local theGroup, theData = cfxZones.createGroundUnitsInZoneForCoalition (\
                aZone.owner, -- was wrongly: theCountry        \
                aZone.name .. dcsCommon.numberUUID(), -- must be unique \
                spawnZone,                                             \
                livingTypes, \
                \
                aZone.formation, -- outward facing\
                0)\
    aZone.defenders = theGroup\
    aZone.lastDefenders = theGroup:getSize()\
end\
\
function factoryZone.inShock(aZone)\
    -- a unit was destroyed, everyone else is in shock, no rerpairs \
    -- group can re-shock when another unit is destroyed \
end\
\
function factoryZone.spawnDefenders(aZone)\
    -- sanity check: never done for non-neutral zones \
    if aZone.owner == 0 then \
        if aZone.verbose or factoryZone.verbose then \
            trigger.action.outText(\"+++factZ: spawnDefenders invoked for NEUTRAL zone <\" .. aZone.name .. \">\", 30)\
        end\
        return \
    end\
    \
    local defenders = aZone.defendersRED;\
    \
    if (aZone.owner == 2) then defenders = aZone.defendersBLUE end\
    -- before we spawn new defenders, remove the old ones\
    if aZone.defenders then \
        if aZone.defenders:isExist() then \
            aZone.defenders:destroy()\
        end\
        aZone.defenders = nil\
    end\
    \
    -- if 'none', simply exit\
    if defenders == \"none\" then return end\
    \
    local theGroup, theData = factoryZone.spawnDefensiveTroops(defenders, aZone, aZone.owner, aZone.formation)\
    -- the troops reamin, so no orders to move, no handing off to ground troop manager\
    aZone.defenders = theGroup\
    aZone.defenderData = theData -- used for persistence \
    if theGroup then \
        aZone.lastDefenders = theGroup:getInitialSize() \
    else \
        trigger.action.outText(\"+++factZ: WARNING: spawned no defenders for \".. aZone.name, 30)\
        aZone.defenderData = nil \
    end \
end\
\
--\
-- per-zone update, run down the FSM to determine what to do.\
-- FSM uses timeStamp since when state was set. Possible states are \
--    - init -- has just been inited for the first time. will usually immediately produce defenders, \
--    and then transition to defending \
--  - catured -- has just been captured. transition to defending \
--  - defending -- wait until timer has reached goal, then produce defending units and transition to attacking. \
--  - attacking -- wait until timer has reached goal, and then produce attacking units and send them to closest enemy zone.\
--                 state is interrupted as soon as a defensive unit is lost. state then goes to defending with timer starting\
--  - idle - do nothing, zone's actions are turned off \
--  - shocked -- a unit was destroyed. group is in shock for a time until it starts repairing. If another unit is \
--               destroyed during the shocked period, the timer resets to zero and repairs are delayed\
--  - repairing -- as long as we aren't at full strength, units get replaced one by one until at full strength\
--                 each time the timer counts down, another missing unit is replaced, and all other unit's health \
--                 is reset to 100%\
--  \
--  a Zone with the paused attribute set to true will cause it to not do anything \
--\
-- check if defenders are specified\
function factoryZone.usesDefenders(aZone) \
    if aZone.owner == 0 then return false end \
    local defenders = aZone.defendersRED;    \
    if (aZone.owner == 2) then defenders = aZone.defendersBLUE end\
    return defenders ~= \"none\"\
end\
\
function factoryZone.usesAttackers(aZone) \
    if aZone.owner == 0 then return false end \
    local attackers = aZone.attackersRED;    \
    if (aZone.owner == 2) then defenders = aZone.attackersBLUE end\
    return attackers ~= \"none\"\
end\
\
function factoryZone.updateZoneProduction(aZone)\
    -- a zone can be paused, causing it to not progress anything\
    -- even if zone status is still init, will NOT produce anything\
    -- if paused is on.\
    if aZone.paused then return end \
\
    nextState = aZone.state;\
    \
    -- first, check if my defenders have been attacked and one of them has been killed\
    -- if so, we immediately switch to 'shocked' \
    if factoryZone.usesDefenders(aZone) and \
       aZone.defenders then \
        -- we have defenders\
        if aZone.defenders:isExist() then\
            -- isee if group was damaged \
            if not aZone.lastDefenders then\
                -- fresh group, probably from persistence, needs init \
                aZone.lastDefenders = -1 \
            end \
            if aZone.defenders:getSize() < aZone.lastDefenders then \
                -- yes, at least one unit destroyed\
                aZone.timeStamp = timer.getTime()\
                aZone.lastDefenders = aZone.defenders:getSize()\
                if aZone.lastDefenders == 0 then \
                    aZone.defenders = nil\
                end\
                aZone.state = \"shocked\"\
\
                return \
            else \
                aZone.lastDefenders = aZone.defenders:getSize()\
            end\
            \
        else \
            -- group was destroyed. erase link, and go into shock for the last time \
            aZone.state = \"shocked\"\
            aZone.timeStamp = timer.getTime()\
            aZone.lastDefenders = 0\
            aZone.defenders = nil\
            return \
        end\
    end\
    \
    \
    if aZone.state == \"init\" then \
        -- during init we instantly create the defenders since \
        -- we assume the zone existed already \
        if aZone.owner > 0 then \
            factoryZone.spawnDefenders(aZone)\
            -- now drop into attacking mode to produce attackers\
            nextState = \"attacking\"\
        else \
            nextState = \"idle\"\
        end\
        aZone.timeStamp = timer.getTime()\
    \
    elseif aZone.state == \"idle\" then\
        -- nothing to do, zone is effectively switched off.\
        -- used for neutal zones or when forced to turn off\
        -- in some special cases \
        \
    elseif aZone.state == \"captured\" then \
        -- start the clock on defenders\
        nextState = \"defending\"\
        aZone.timeStamp = timer.getTime()\
        if factoryZone.verbose then \
            trigger.action.outText(\"+++factZ: State \" .. aZone.state .. \" to \" .. nextState .. \" for \" .. aZone.name, 30)\
        end \
    elseif aZone.state == \"defending\" then \
        if timer.getTime() > aZone.timeStamp + factoryZone.defendingTime then \
            factoryZone.spawnDefenders(aZone)\
            -- now drop into attacking mode to produce attackers\
            nextState = \"attacking\"\
            aZone.timeStamp = timer.getTime()\
            if factoryZone.verbose then \
                trigger.action.outText(\"+++factZ: State \" .. aZone.state .. \" to \" .. nextState .. \" for \" .. aZone.name, 30)\
            end\
        end\
\
    elseif aZone.state == \"repairing\" then \
        -- we are currently rebuilding defenders unit by unit \
        if timer.getTime() > aZone.timeStamp + factoryZone.repairTime then \
            aZone.timeStamp = timer.getTime()\
            -- wait's up, repair one defender, then check if full strength\
            factoryZone.repairDefenders(aZone)\
            -- see if we are full strenght and if so go to attack, else set timer to reair the next unit\
            if aZone.defenders and aZone.defenders:isExist() and aZone.defenders:getSize() >= aZone.defenders:getInitialSize() then\
                -- we are at max size, time to produce some attackers\
                -- progress to next state \
                nextState = \"attacking\"\
                aZone.timeStamp = timer.getTime()\
                if factoryZone.verbose then \
                    trigger.action.outText(\"+++factZ: State \" .. aZone.state .. \" to \" .. nextState .. \" for \" .. aZone.name, 30)\
                end\
            end\
\
        end\
        \
    elseif aZone.state == \"shocked\" then \
        -- we are currently rebuilding defenders unit by unit \
        if timer.getTime() > aZone.timeStamp + factoryZone.shockTime then \
            nextState = \"repairing\"\
            aZone.timeStamp = timer.getTime()\
            if factoryZone.verbose then \
                trigger.action.outText(\"+++factZ: State \" .. aZone.state .. \" to \" .. nextState .. \" for \" .. aZone.name, 30)\
            end\
        end\
        \
    elseif aZone.state == \"attacking\" then \
        if timer.getTime() > aZone.timeStamp + factoryZone.attackingTime then \
            factoryZone.sendOutAttackers(aZone)\
            -- reset timer\
            aZone.timeStamp = timer.getTime()\
            if factoryZone.verbose then \
                trigger.action.outText(\"+++factZ: State \" .. aZone.state .. \" reset for \" .. aZone.name, 30)\
            end\
        end\
    else \
        -- unknown zone state \
    end\
    aZone.state = nextState\
end\
\
function factoryZone.GC()\
    -- GC run. remove all my dead remembered troops\
    local before = #factoryZone.spawnedAttackers\
    local filteredAttackers = {}\
    for gName, gData in pairs (factoryZone.spawnedAttackers) do \
        -- all we need to do is get the group of that name\
        -- and if it still returns units we are fine \
        local gameGroup = Group.getByName(gName)\
        if gameGroup and gameGroup:isExist() and gameGroup:getSize() > 0 then \
            filteredAttackers[gName] = gData\
        end\
    end\
    factoryZone.spawnedAttackers = filteredAttackers\
    if factoryZone.verbose then \
        trigger.action.outText(\"owned zones GC ran: before <\" .. before .. \">, after <\" .. #factoryZone.spawnedAttackers .. \">\", 30)\
    end\
end\
\
function factoryZone.update()\
    factoryZone.updateSchedule = timer.scheduleFunction(factoryZone.update, {}, timer.getTime() + 1/factoryZone.ups)\
    -- iterate all zones to see if ownership has \
    -- changed \
\
    for idz, theZone in pairs(factoryZone.zones) do \
        local lastOwner = theZone.factoryOwner\
        local newOwner = theZone.owner \
        if (newOwner ~= lastOwner) then \
            theZone.state = \"captured\"\
            theZone.timeStamp = timer.getTime()\
            theZone.factoryOwner = theZone.owner \
            if theZone.verbose or factoryZone.verbose then \
                trigger.action.outText(\"+++factZ: detected factory <\" .. theZone.name .. \"> changed ownership from <\" .. lastOwner .. \"> to <\" .. theZone.owner .. \">\", 30)\
            end\
        end\
        \
        -- see if pause/unpause was issued\
        if theZone.pauseFlag and cfxZones.testZoneFlag(theZone, theZone.pauseFlag, theZone.factoryTriggerMethod, \"lastPauseValue\") then\
            theZone.paused = true \
        end\
        \
        if theZone.activateFlag and cfxZones.testZoneFlag(theZone, theZone.activateFlag, theZone.factoryTriggerMethod, \"lastActivateValue\") then\
            theZone.paused = false \
        end\
        -- do production for this zone \
        factoryZone.updateZoneProduction(theZone)\
    end -- iterating all zones \
end\
\
function factoryZone.houseKeeping()\
    timer.scheduleFunction(factoryZone.houseKeeping, {}, timer.getTime() + 5 * 60) -- every 5 minutes \
    factoryZone.GC()\
end\
\
\
--\
-- load / save data \
--\
\
function factoryZone.saveData()\
    -- this is called from persistence when it's time to \
    -- save data. returns a table with all my data \
    local theData = {}\
    local allZoneData = {}\
    -- iterate all my zones and create data \
    for idx, theZone in pairs(factoryZone.zones) do\
        local zoneData = {}\
        if theZone.defenderData then \
            zoneData.defenderData = dcsCommon.clone(theZone.defenderData)\
            dcsCommon.synchGroupData(zoneData.defenderData)\
        end \
        zoneData.owner = theZone.owner \
        zoneData.state = theZone.state -- will prevent immediate spawn\
            -- since new zones are spawned with 'init'\
        allZoneData[theZone.name] = zoneData\
    end\
    \
    -- now iterate all attack groups that we have spawned and that \
    -- (maybe) are still alive \
    factoryZone.GC() -- start with a GC run to remove all dead \
    local livingAttackers = {}\
    for gName, gData in pairs (factoryZone.spawnedAttackers) do \
        -- all we need to do is get the group of that name\
        -- and if it still returns units we are fine \
        -- spawnedAttackers is a [groupName] table with {.groupData, .orders, .side}\
        local gameGroup = Group.getByName(gName)\
        if gameGroup and gameGroup:isExist() then \
            if gameGroup:getSize() > 0 then \
                local sData = dcsCommon.clone(gData)\
                dcsCommon.synchGroupData(sData.groupData)\
                livingAttackers[gName] = sData\
            end\
        end\
    end\
    \
    -- now write the info for the flags that we output for #red, etc\
    local flagInfo = {} -- no longer used \
\
    -- assemble the data \
    theData.zoneData = allZoneData\
    theData.attackers = livingAttackers\
    theData.flagInfo = flagInfo\
    \
    -- return it \
    return theData\
end\
\
function factoryZone.loadData()\
    -- remember to draw in map with new owner \
    if not persistence then return end \
    local theData = persistence.getSavedDataForModule(\"factoryZone\")\
    if not theData then \
        if factoryZone.verbose then \
            trigger.action.outText(\"factZ: no save date received, skipping.\", 30)\
        end\
        return\
    end\
    -- theData contains the following tables:\
    --   zoneData: per-zone data \
    --   flagInfo: module-global flags \
    --   attackers: all spawned attackers that we feed to groundTroops\
    local allZoneData = theData.zoneData \
    for zName, zData in pairs(allZoneData) do \
        -- access zone \
        local theZone = factoryZone.getOwnedZoneByName(zName)\
        if theZone then \
            if zData.defenderData then \
                if theZone.defenders and theZone.defenders:isExist() then\
                    -- should not happen, but so be it\
                    theZone.defenders:destroy()\
                end\
                local gData = zData.defenderData\
                local cty = gData.cty \
                local cat = gData.cat \
                theZone.defenders = coalition.addGroup(cty, cat, gData)\
                theZone.defenderData = zData.defenderData\
            end\
            theZone.owner = zData.owner \
            theZone.factoryOwner = theZone.owner \
            theZone.state = zData.state \
\
        else \
            trigger.action.outText(\"factZ: load - data mismatch: cannot find zone <\" .. zName .. \">, skipping zone.\", 30)\
        end\
    end\
    \
    -- now process all attackers \
    local allAttackers = theData.attackers\
    for gName, gdTroop in pairs(allAttackers) do \
        -- table is {.groupData, .orders, .side}\
        local gData = gdTroop.groupData \
        local orders = gdTroop.orders \
        local side = gdTroop.side \
        local cty = gData.cty \
        local cat = gData.cat \
        -- add to my own attacker queue so we can save later \
        local dClone = dcsCommon.clone(gdTroop)\
        factoryZone.spawnedAttackers[gName] = dClone \
        local theGroup = coalition.addGroup(cty, cat, gData)\
        if cfxGroundTroops then \
            local troops = cfxGroundTroops.createGroundTroops(theGroup)\
            troops.orders = orders\
            troops.side = side\
            cfxGroundTroops.addGroundTroopsToPool(troops) -- hand off to ground troops\
        end \
    end\
    \
    -- now process module global flags \
    local flagInfo = theData.flagInfo\
    if flagInfo then \
    end\
end\
\
 \
--\
function factoryZone.readConfigZone(theZone)\
    if not theZone then theZone = cfxZones.createSimpleZone(\"factoryZoneConfig\") end \
    factoryZone.name = \"factoryZone\" -- just in case, so we can access with cfxZones \
    factoryZone.verbose = cfxZones.getBoolFromZoneProperty(theZone, \"verbose\", false)\
    factoryZone.defendingTime = cfxZones.getNumberFromZoneProperty(theZone, \"defendingTime\", 100)\
    factoryZone.attackingTime = cfxZones.getNumberFromZoneProperty(theZone, \"attackingTime\", 300)\
    factoryZone.shockTime = cfxZones.getNumberFromZoneProperty(theZone, \"shockTime\", 200)\
    factoryZone.repairTime = cfxZones.getNumberFromZoneProperty(theZone, \"repairTime\", 200)\
    factoryZone.targetZones = \"OWNED\"\
    --[[\
    factoryZone.targetZones = string.upper(cfxZones.getStringFromZoneProperty(theZone, \"targetZones\", \"owned\")) -- CLASSIC = factory & target, ALL = all DML, FACTORY = factory zones only, OWNED = owned only.\
    if factoryZone.targetZones ~= \"CLASSIC\" and factoryZone.targetZones ~= \"ALL\" and factoryZone.targetZones ~= \"FACTORY\" and factoryZone.targetZones ~= \"OWNED\" then \
        trigger.action.outText(\"+++factZ: illegal 'targetZones' attribute value <>, using 'classic' instead.\", 30)\
        factoryZone.targetZones = \"CLASSIC\" \
    end\
    --]]\
end\
\
function factoryZone.init()\
    -- check libs\
    if not dcsCommon.libCheck(\"cfx Factory Zones\", \
        factoryZone.requiredLibs) then\
        return false \
    end\
\
    -- read my config zone\
    local theZone = cfxZones.getZoneByName(\"factoryZoneConfig\") \
    factoryZone.readConfigZone(theZone)\
\
    -- collect all zones by their 'factory' property \
    -- start the process\
    local pZones = cfxZones.zonesWithProperty(\"factory\")\
    \
    -- now add all zones to my zones table, and convert the owner property into \
    -- a proper attribute \
    for k, aZone in pairs(pZones) do\
        factoryZone.addFactoryZone(aZone)\
    end\
    \
    if persistence then \
        -- sign up for persistence \
        callbacks = {}\
        callbacks.persistData = factoryZone.saveData\
        persistence.registerModule(\"factoryZone\", callbacks)\
        -- now load my data \
        factoryZone.loadData()\
    end\
    \
    initialized = true \
    factoryZone.updateSchedule = timer.scheduleFunction(factoryZone.update, {}, timer.getTime() + 1/factoryZone.ups)\
    \
    -- start housekeeping \
    factoryZone.houseKeeping()\
    \
    trigger.action.outText(\"cx/x factory zones v\".. factoryZone.version .. \" started\", 30)\
    \
    return true \
end\
\
if not factoryZone.init() then \
    trigger.action.outText(\"cf/x Factory Zones aborted: missing libraries\", 30)\
    factoryZone = nil \
end\
\
\
-- add property to factory attribute to restrict production to that side, \
-- eg factory blue will only work for blue, else will work for any side \
-- currently not needed since we have defendersRED/BLUE and productionRED/BLUE\
",
                    ["predicate"] = "a_do_script",
                }, -- end of [6]
            }, -- end of ["actions"]
        }, -- end of [1]
        [2] = 
        {
            ["rules"] = 
            {
                [1] = 
                {
                    ["coalitionlist"] = "red",
                    ["unitType"] = "ALL",
                    ["zone"] = 165,
                    ["flag"] = 10,
                    ["predicate"] = "c_flag_equals",
                    ["value"] = 1,
                }, -- end of [1]
            }, -- end of ["rules"]
            ["comment"] = "Got One Red",
            ["eventlist"] = "",
            ["actions"] = 
            {
                [1] = 
                {
                    ["seconds"] = 30,
                    ["start_delay"] = 0,
                    ["KeyDict_text"] = "DictKey_ActionText_6",
                    ["text"] = "DictKey_ActionText_6",
                    ["predicate"] = "a_out_text_delay",
                    ["clearview"] = false,
                }, -- end of [1]
            }, -- end of ["actions"]
            ["predicate"] = "triggerOnce",
        }, -- end of [2]
        [3] = 
        {
            ["rules"] = 
            {
                [1] = 
                {
                    ["coalitionlist"] = "red",
                    ["unitType"] = "ALL",
                    ["zone"] = 165,
                    ["flag"] = 10,
                    ["predicate"] = "c_flag_equals",
                    ["value"] = 2,
                }, -- end of [1]
            }, -- end of ["rules"]
            ["comment"] = "Got 2 Reds",
            ["eventlist"] = "",
            ["actions"] = 
            {
                [1] = 
                {
                    ["seconds"] = 30,
                    ["start_delay"] = 0,
                    ["KeyDict_text"] = "DictKey_ActionText_7",
                    ["text"] = "DictKey_ActionText_7",
                    ["predicate"] = "a_out_text_delay",
                    ["clearview"] = false,
                }, -- end of [1]
            }, -- end of ["actions"]
            ["predicate"] = "triggerOnce",
        }, -- end of [3]
    }, -- end of ["trigrules"]
    ["currentKey"] = 1631,
    ["failures"] = 
    {
    }, -- end of ["failures"]
    ["forcedOptions"] = 
    {
    }, -- end of ["forcedOptions"]
    ["start_time"] = 28800,
} -- end of mission
