--To create the flight plans in the mission file for all flights in the ATO
--Initiated by Main_NextMission.lua
------------------------------------------------------------------------------------------------------- 
-- Miguel Fichier Revision ATO_FP_Debug05
------------------------------------------------------------------------------------------------------- 

-- ATO_FP_Debug05 Escorte
-- ATO_FP_Debug04 Gun = 0 uniquement sur un Flight
-- mouvedOption_CM_01 : deplace les options de west callSign dans conf_mod
-- ATO_FP_Reglage01.b : emport, ne pas larguer les emports en cas d'urgence
-- ATO_Debug12 strike ASM B52 
-- ATO_FP_Debug03 Antiship strike
-- ATO_FP_Debug02 Interceptor error nb trigger
-- ATO_FP_Debug01.2 alti flight ai en multijoueur

-- miguel21 modification M37.k SuperCarrier (k: limite à 10 le nb d'avion au début de mission)
-- miguel21 modification M34 change freq EWR
-- Miguel21 modification M33.c 	Custom Briefing (onBoardNum)
-- Miguel21 modification M31 	Remove all static aircraft from the deck
-- Miguel21 modification M30.b 	Desactive TriggerStart
-- Miguel21 modification M27.b 	MovedBullseye
-- Miguel21 modification M24	Set Multiplayer 
-- Miguel21 modification M23	Désactive USN Mod 
-- Miguel21 modification M20	Pannes al�atoires en SingleMission et ForcedOption (external view etc..)
-- Miguel21 modification M17.e	Option F-14B
-- Miguel21 Modification M15.d info catapulte/pont dans briefing
-- Miguel21 modification M12.b 	: Skill
-- Miguel21 modification M11B. 	: Multiplayer--briefing	
-- Miguel21 modification M11.k 	: Multiplayer
-- Miguel21 modification M08	: hotstart  --||initialement ((départ de la piste + debug hotstart + intercepteur CVN))
-- Miguel21 modification M06.f : helicoptere playable
					-- Miguel21 modification M03.h : Parking assign� des AV8 sur LHA + CVN LHA et FARP Apparition d�cal� + Apparition retard�
					--INUTILE Miguel21 modification M02 : Ajout TACAN
-- Miguel21 modification M01 : ajout datalink
------------------------------------------------------------------------------------------------------- 		
		
-- Miguel21 modification M24	Set Multiplayer
if coopFlag01 then 

	
	mission_ini.PruneScript = true							-- reduce a mission by removing units (mod Tomsk M09) [MP: recommend: true]					PruneAggressiveness = 1.5,					-- How aggressive should the pruning be [0 to 2], larger numbers will remove more units, 0 = no pruning at all
	mission_ini.PruneStatic = true							-- Should ALL parked (static) aircraft be pruned [MP: recommend: true]
	-- mission_ini.ForcedPruneSam = true						-- PBO-CEF avait pr�vu de garder des SAM actif, cette option les d�sactives tout de m�me [MP: recommend: true]
	mission_ini.failure = false								-- (true or false) Miguel21 modification M20 [MP: recommend: false]
	-- mission_ini.ravitoByConvoy = false					-- [non encore fonctionnel] ravitaillement par convoy routier 
	mission_ini.Keep_USNdeckCrew = false					-- false = supprime US Navy deck crew dans la g�n�ration de mission. Miguel Modification M23
	mission_ini.CVN_CleanDeck = true 							-- true: Remove all static aircraft from the deck. ( M31 )
	
-- Force vos propres options plutot que ceux de base_ini.miz, qui correspondent � ceux de PBO-CEF ^^
	if not mission.forcedOptions then mission.forcedOptions = {} end
	mission.forcedOptions.accidental_failures =  false
	mission_forcedOptions.wakeTurbulence = false			-- False / true : turbulence  [MP: recommend: false]
	mission_forcedOptions.civTraffic = ""					-- Traffic civil routier : ( "" : OFF ) || ( "low" : BAS ) || ( "medium" : MOYEN )|| ( "high" : ELEVE )  [MP: recommend: ""]
	mission_forcedOptions.birds = 0							-- Collision volatile (probabilit�) ( 0 � 1000 )  [MP: recommend: 0]

	end
	
----- D�sactive USN Mod -----Miguel21 modification M23
	if not mission_ini.Keep_USNdeckCrew then
		mission.requiredModules = {
									['USN-Deckcrew'] = nil,
									}
	end
	
	
----- Ajoute les pannes al�atoires en SingleMission -----Miguel21 modification M20
	for option, value  in pairs(mission_forcedOptions) do								-- ajoute les options du jeux
		if not mission.forcedOptions then mission.forcedOptions = {} end
		mission.forcedOptions[option] =  value
	end
		
	if mission_ini.failure then										-- not multiplayer --	if mission_ini.failure and not coopFlag01 then	
		-- ajoute accidental_failures = true � forcedOptions
		if not mission.forcedOptions then mission.forcedOptions = {} end
		mission.forcedOptions.accidental_failures =  true
		

		local n= 1	
		for _id, failure in pairs(mission.failures) do
			n = n+1
		end
		
		for f = 1, mission_ini.failureNbMax do
				
			local hh = math.random(0, 1)
			local mm = math.random(1, 59)
			local prob = math.random(1, mission_ini.failureProbMax)
			local mmint = math.random(1, 59)
			local id_failed = math.random(1, n-1)
						
			local m = 1
			for _id, failure in pairs(mission.failures) do
			
				if id_failed == m then 
					if not mission.failures[_id] then print("NotFailureId") end
					if not mission.failures[_id]['hh'] then print("NotFailureHh") end
					mission.failures[_id]['hh'] = hh
					mission.failures[_id]['mm'] = mm
					mission.failures[_id]['prob'] = prob
					mission.failures[_id]['enable'] = true
					mission.failures[_id]['mmint'] = mmint
					if Debug.AfficheFailure then print("PossibleFailure ".._id.." "..hh.."H"..mm.." ".." Duration "..mmint.." Probability: "..prob) end				
				end
				m = m+1
			end
		end
	end
	
----- function to create callsigns for aircraft in ATO -----
local callsign_west = {
	generic = {
		[1] = "Enfield",
		[2] = "Springfield",
		[3] = "Uzi",
		[4] = "Colt",
		[5] = "Dodge",
		[6] = "Ford",
		[7] = "Chevy",
		[8] = "Pontiac",
	},
	AWACS = {
		[1] = "Overlord",
		[2] = "Magic",
		[3] = "Wizard",
		[4] = "Focus",
		[5] = "Darkstar",
	},
	tanker = {
		[1] = "Texaco",
		[2] = "Arco",
		[3] = "Shell",
	}
}

local callsign_west_counter = {
	generic = math.random(0, #callsign_west.generic - 1),
	AWACS = math.random(0, #callsign_west.AWACS - 1),
	tanker = math.random(0, #callsign_west.tanker - 1),
}
local callsign_east_counter = 0

local function GetCallsign(country, flight_n, aircraft_n, task)
	local style
	
	-- mouvedOption_CM_01 : deplace les options de west callSign dans conf_mod
	style = "east"
	
	if not campMod.WestCallsign then 
		if country == "Belgium" or country == "UK" or country == "Georgia" or country == "Denmark" or country == "Israel" or country == "Spain" or country == "Canada" or country == "Norway" or country == "USA" or country == "Turkey" or country == "France" or country == "The Netherlands" or country == "Italy" or country == "Australia" or country == "South Korea" or country == "Croatia" or country == "USAF Aggressors" or country == "Sweden" or country == "Iran" then
			style = "west"
		end
	elseif  campMod.WestCallsign[country] == "west" then
		style = "west"
	end
	
	local callsign
	if style == "west" then
		local category
		if task == "AWACS" then
			category = "AWACS"
		elseif task == "Refueling" then
			category = "tanker"
		else
			category = "generic"
		end
	
		if flight_n == 1 and aircraft_n == 1 then
			callsign_west_counter[category] = callsign_west_counter[category] + 1
			if callsign_west_counter[category] > #callsign_west[category] then
				callsign_west_counter[category] = 1
			end
			callsign_flight = math.random(0, 8)
		end
		
		if aircraft_n == 1 then
			callsign_flight = callsign_flight + 1
			if callsign_flight > 9 then
				callsign_flight = 1
			end
		end
		
		callsign = {
			name = callsign_west[category][callsign_west_counter[category]] .. callsign_flight .. aircraft_n
		}

		_name = callsign_west[category][callsign_west_counter[category]] .. callsign_flight .. aircraft_n
		 
			callsign = {
				[1] = callsign_west_counter[category],
				[2] =  callsign_flight,
				[3] =  aircraft_n,
				name = _name
			}


	elseif style == "east" then
		if aircraft_n == 1 then
			callsign_east_counter = callsign_east_counter + 1
		end
		callsign = 90 + callsign_east_counter * 10 + aircraft_n
	end
	
	return callsign
end


---- function to get sidenumbers -----
local sidenumbers = {}

function GetSidenumber(squadron, lower, upper)									--not local, also used in DC_StaticAircraft
	if sidenumbers[squadron] == nil then										--sidenumber squadron entry does not exist
		sidenumbers[squadron] = {}												--create sidenumber squadron entry
	end
		
	local s																		--new sidenumber
	local counter = 0
	repeat
		counter = counter + 1
		s = math.random(tonumber(lower), tonumber(upper))						--find random sidenumber
	until sidenumbers[squadron][s] == nil or counter == 100						--repeat until a sidenumber is found that is not yet in squadron use or stop after 100 tries
	sidenumbers[squadron][s] = true												--mark sidenumber in use for squadron
	
	local lNew = string.len(s)													--lenght of new sidenumber
	local lOld = string.len(lower)												--lenght of given lower end of sidenumbers
	for n = lNew, lOld - 1 do													--for each character that new sidenumber is smaller than given lower ranger
		s = "0" .. s															--add a zero in front
	end
	
	return tostring(s)															--return sidenumber as string
end

---- function to assign A-A TACAN channels ----
tanker_tacan = {}																--table to store tanker TACAN channels
-- https://forums.eagle.ru/showpost.php?p=3821502&postcount=139
-- 37-67  ??.?
local function GetTankerTACAN()
	local channel
	repeat
		channel = math.random(37, 67)											--find random TACAN channel
	until tanker_tacan[channel] == nil											--repeat until channel is found that is not in use yet
	
	tanker_tacan[channel] = true												--mark channel in use
	return channel																--return channel
end

--Mod M27.b Randomly moves the 2 BullsEye
function fct_MovedBullseye(side, NameTheatre)
	
	local tempArrayBulls = {}
	for name, base in pairs(db_airbases) do 
		if base.x then
			if GetDistance(campMod.MovedBullseye[NameTheatre].pos, base) <= (campMod.MovedBullseye[NameTheatre].rayon * 1000) then 
				db_airbases[name]["name"] = name
				table.insert(tempArrayBulls, db_airbases[name])
			end
		end
	end
	
	local i = table.getn(tempArrayBulls)
	
	if i >= 1 then
		j = math.random(1, i)
		mission.coalition[side].bullseye.x = tempArrayBulls[j].x
		mission.coalition[side].bullseye.y = tempArrayBulls[j].y
		
		if not brief then brief = {} end
		if not brief[side] then brief[side] = {} end
		if not brief[side].bullseye then brief[side].bullseye = {} end
		brief[side].bullseye.name = tempArrayBulls[j].name
		brief[side].bullseye.x = tempArrayBulls[j].x
		brief[side].bullseye.y = tempArrayBulls[j].y
		
		if tempArrayBulls[j].gps then 
			brief[side].bullseye.gps = tempArrayBulls[j].gps	
		end
	end

end

-- miguel21 modification M37.i SuperCarrier (i: option deck air catapult)
--Spawn OnDeck, OnCatapult or OnAir
function SpawnOn(spawn, waypoints, group, Pn)
-- print("ATO_FP spawn "..spawn)
	spawn = string.lower(spawn)
	if  spawn == "air" then						
		waypoints[1]["action"] = "Turning Point"
		waypoints[1]["type"] = "Turning Point"
		waypoints[1]["alt"] = waypoints[1]["alt"] + (Pn * 500)
		waypoints[1]["speed"] = 140
	
		-- ATO_FP_Debug01
		for	n = 1 , #group.units do
			group.units[n].x = ((Pn-1) * 1000) + group.units[n].x + (150 * n)
			group.units[n].y = ((Pn-1) * 1000) + group.units[n].y + (150 * n)
		end
	elseif spawn == "catapult" then
		waypoints[1]["action"] = "From Runway"
		waypoints[1]["type"] = "TakeOff"
		
		waypoints[1]["alt"] = 0
		
		group.uncontrolled = false											-- sur cata, les F14 IA bloquent
	end
	
end

placePA = {}
local NbFlightPackage = 0													-- calcul le nombre de flight dans un Package, en comptant ceux des Roles
local NbFlightPlayer = 2 													-- nb d'avion dans le flight du joueur			
			
---- table to store departure altitudes and times and all airbases to deconflict spawns and orbits ----
local DepartureOrbitAlt = {}	


-- Cherche le nb d'avion dans le package joueur
for side, pack in pairs(ATO) do	
	for p = 1, #pack do															--iterate through packages in sides
		for role,flight in pairs(pack[p]) do									--iterate through roles in package (main, SEAD, escort)		
			for f = 1, #flight do												--iterate through flights in roles
			
				if camp.player and camp.player.side == side and camp.player.pack_n == p then				--for flights in player's package and package does not cover a station and flight[f].task ~= "CAP"
					for role2,flight2 in pairs(pack[p]) do													-- calcul le nombre de flight dans un Package, en comptant ceux des Roles										
						NbFlightPackage = NbFlightPackage + #flight2 										
						
						for x = 1, #flight2 do
							if flight2[x].player then
								NbFlightPlayer = #flight2
							end
						end
					end
				end
			end
		end
	end
end

local NbFlightDeck = NbFlightPackage														-- nb d'avion total sur le CVN

if NbFlightPackage > mission_ini.SC_NbPlaneSpawn then										-- on ne dépasse pas le nb max de spawn sur le CVN 
	NbFlightPackage = mission_ini.SC_NbPlaneSpawn 
end
				
----- create flight plans in mission file for all flights in ATO -----
for side, pack in pairs(ATO) do													--iterate through sides in ATO
	
	--M27 Randomly moves the 2 BullsEye
	local NameTheatre =  string.lower(mission.theatre)
	if campMod.MovedBullseye[NameTheatre] then	fct_MovedBullseye(side, NameTheatre) end
	
	for p = 1, #pack do															--iterate through packages in sides
		
		local Pn = 0															--variable to count flights in package
		
		for role,flight in pairs(pack[p]) do									--iterate through roles in package (main, SEAD, escort)		
			for f = 1, #flight do												--iterate through flights in roles

				-- flight[f].multi2 = false                      --variable Miguel21 modification M11 multijoueur
				NavTargetPoints = {}
				flagPoints = {}
				index = 0
				removeWptF14 = {}
				
				local activG_spawn_time = 0
				local aiStart_spawn_time = 0
				
				-- miguel21 modification M37 SuperCarrier
				local SuperCarrier = false
				if db_airbases[flight[f].base].unitname and mission_ini.SC_FullPlaneOnDeck then			
					for coal_name,coal in pairs(oob_ground) do												--go through sides(red/blue)	
						for country_n,country in ipairs(coal) do											--go through countries
							if country.ship then															--country has ships
								for group_n,group in ipairs(country.ship.group) do							--go through groups
									for n = 1, #group.units do												--ship group found
										if db_airbases[flight[f].base].unitname == group.units[n].name and
											(group.units[n].type == "CVN_71" or group.units[n].type == "CVN_72" or group.units[n].type == "CVN_73" ) then
											SuperCarrier = true
										end
									end
								end
							end
						end
					end
				end
				
				
				Pn = Pn + 1														--count flights in package
				
				local weaponType = 1073741822																			--Weapon types to use (default auto)
				if flight[f].loadout.weaponType == "Cannon" then
					weaponType = 805306368																				--Use cannon only
				elseif flight[f].loadout.weaponType == "Rockets" then
					weaponType = 30720																					--Use rockets only
				elseif flight[f].loadout.weaponType == "Bombs" then
					weaponType = 2032																					--Use unguided bombs only
				elseif flight[f].loadout.weaponType == "Guided bombs" then
					weaponType = 14																						--Use guided bombs only
				elseif flight[f].loadout.weaponType == "ASM" then
					weaponType = 4161536																				--Use ASM only
				end
				
				----- define waypoints -----
				local egress_wp													--local variable to store the Egress WP
				local target_wp_remove											--local variable for the target waypoint to be potentially removed for standoff ground attacks
				local spawn_time												--local variable to store spawn time
				local departure_time											--local variable to store departure time
				local waypoints = {}											--define waypoints of flight
				
				for w = 1, #flight[f].route do
					waypoints[w] = {
						["name"] = flight[f].route[w].id,
						["briefing_name"] = flight[f].route[w].id,				--not needed for actual mission creation, but added for navigation overview in briefing
						["alt"] = flight[f].route[w].alt,
						["type"] = "Turning Point",
						["action"] = "Turning Point",
						["alt_type"] = "BARO",
						["formation_template"] = "",
						["properties"] = 
						{
							["vnav"] = 1,
							["scale"] = 0,
							["angle"] = 0,
							["vangle"] = 0,
							["steer"] = 2,
						},
						["ETA"] = flight[f].route[w].eta,
						["y"] = flight[f].route[w].y,
						["x"] = flight[f].route[w].x,
						["speed"] = pack[p].main[1].loadout.vCruise,
						["ETA_locked"] = true,
						["task"] = 
						{
							["id"] = "ComboTask",
							["params"] = 
							{
								["tasks"] = {}
							},
						},
						["speed_locked"] = false,
					}
					
					
					-- Miguel21 modification M17.e
					if flight[f].type == "F-14B" and ( flight[f].player or flight[f].multi2 ) and TargetPointF14 then
						if  flight[f].route[w].id == "Target" or flight[f].route[w].id == "Attack" and not flagPoints["ST"] then
							index = index +1
							if not NavTargetPoints[index] then NavTargetPoints[index] = {} end
							NavTargetPoints[index]["text_comment"]  = "ST"
							NavTargetPoints[index]["x"] = flight[f].route[w].x
							NavTargetPoints[index]["y"] = flight[f].route[w].y
							NavTargetPoints[index]["index"] = index
							flagPoints["ST"] = true
							table.insert(removeWptF14, w)
						
						elseif flight[f].route[w].id == "IP" and not flagPoints["IP"] then
							index = index +1
							if not NavTargetPoints[index] then NavTargetPoints[index] = {} end
							NavTargetPoints[index]["text_comment"]  = "IP"
							NavTargetPoints[index]["x"] = flight[f].route[w].x
							NavTargetPoints[index]["y"] = flight[f].route[w].y
							NavTargetPoints[index]["index"] = index
							flagPoints["IP"] = true
							table.insert(removeWptF14, w)
							
						 elseif flight[f].route[w].id == "Station"  then --and not flagPoints["DP"]
							index = index +1
							if not NavTargetPoints[index] then NavTargetPoints[index] = {} end
							NavTargetPoints[index]["text_comment"]  = "DP"
							NavTargetPoints[index]["x"] = flight[f].route[w].x
							NavTargetPoints[index]["y"] = flight[f].route[w].y
							NavTargetPoints[index]["index"] = index
							-- flagPoints["DP"] = true
							table.insert(removeWptF14, w)
						end
						
						if TargetPointF14_BullsToFP and not flagPoints["FP"] then 
							index = index +1
							if not NavTargetPoints[index] then NavTargetPoints[index] = {} end
							NavTargetPoints[index]["text_comment"]  = "FP"
							NavTargetPoints[index]["x"] = mission.coalition[side].bullseye.x
							NavTargetPoints[index]["y"] = mission.coalition[side].bullseye.y
							NavTargetPoints[index]["index"] = index
							flagPoints["FP"] = true
						end

					end
					
					--store spawn and departure time for flight
					if flight[f].route[w].id == "Taxi" or flight[f].route[w].id == "Spawn" then
						spawn_time = flight[f].route[w].eta
					elseif flight[f].route[w].id == "Departure" then
						departure_time = flight[f].route[w].eta
					end
					
					--alter departure alt (spawn and orbit) to prevent collisions of multiple packages
					if flight[f].route[w].id == "Departure" and flight[f].route[w - 1] and flight[f].route[w].id == "Spawn" then							--for departure waypoints that come after spwn waypoints
						waypoints[w]["alt"] = waypoints[w - 1]["alt"]																						--use same altitude as departure as for spawn
					elseif flight[f].route[w].id == "Departure" or (flight[f].route[w].id == "Spawn" and flight[f].route[w + 1].id == "Departure") then		--for departure waypoint or spawn before departure waypoint
						local alt = 609.6														--initial departure alt to try: 2'000 ft
						if db_airbases[flight[f].base].elevation then							--airbase has defined elevation
							alt = alt + db_airbases[flight[f].base].elevation					--make alt above base
						end
						if DepartureOrbitAlt[flight[f].base] == nil then						--airbase has no departure altitute entries yet
							DepartureOrbitAlt[flight[f].base] = {								--make base table
								[alt] = {														--make altitude table
									[1] = waypoints[w]["ETA"],									--store time of departure
								}
							}
							waypoints[w]["alt"] = alt											--set departure altitude
						else																	--airbase has departure altitute entries
							local DepartureAlt
							repeat
								if DepartureOrbitAlt[flight[f].base][alt] == nil then			--no altitude entries yet			
									DepartureOrbitAlt[flight[f].base][alt] = {					--make altitude table
										[1] = waypoints[w]["ETA"],								--store time of departure
									}
									DepartureAlt = alt											--set departure altitude
								else															--there are already altitude entries for this airbase
									for a = 1, #DepartureOrbitAlt[flight[f].base][alt] do		--iterate through all entries of that alt
										if waypoints[w]["ETA"] > DepartureOrbitAlt[flight[f].base][alt][a] - 600 and waypoints[w]["ETA"] < DepartureOrbitAlt[flight[f].base][alt][a] + 600 then		--waypoint ETA is within 10 minutes of stored ETA 
											alt = alt + 304.8									--increase alt by 1'000 ft any try again for this next alt
											break												--break and continue with higher altitude
										end
										if a == #DepartureOrbitAlt[flight[f].base][alt] then	--if all stored ETAs have been checked
											table.insert(DepartureOrbitAlt[flight[f].base][alt], waypoints[w]["ETA"])	--insert new ETA for that altitude
											DepartureAlt = alt									--set this departure altitude
										end
									end
								end
							until DepartureAlt													--repeat until a departure altitude has been found
							waypoints[w]["alt"] = DepartureAlt									--set departure altitude
						end
					end
					
					--set attack speed for attack, target and egress waypoints
					if waypoints[w]["name"] == "Attack" or waypoints[w]["name"] == "Target" or waypoints[w]["name"] == "Egress" then
						waypoints[w]["ETA_locked"] = false
						waypoints[w]["speed_locked"] = true
						waypoints[w]["speed"] = pack[p].main[1].loadout.vAttack
					elseif waypoints[w]["name"] == "Join" or waypoints[w]["name"] == "Departure" and not flight[f].helicopter then		-- M06.e not flight[f].helicopter
						waypoints[w]["speed"] = pack[p].main[1].loadout.vCruise / 4 * 3													--speed to Join Point is 3/4 cruise speed
					elseif (waypoints[w]["name"] == "Join" or waypoints[w]["name"] == "Departure") and flight[f].helicopter then
						waypoints[w]["speed"] = pack[p].main[1].loadout.vCruise                          								 --3/4 not helicopter	
					end
					
					--attack waypoint is a fly over point
					if waypoints[w]["name"] == "Attack" then
						waypoints[w]["action"] = "Fly Over Point"
					end
					
					--fighter escorts fly with cruise speed to egress
					if waypoints[w]["name"] == "Egress" and flight[f].task == "Escort" then
						waypoints[w]["speed"] = pack[p].main[1].loadout.vCruise
					end
					
					---- ATO_FP_Debug05 Escorte
					-- --set speed locked for all WP after Egress or Station
					-- if flight[f].route[w].id == "Egress" or flight[f].route[w].id == "Station" and egress_wp == nil then	--find Egress or first Station WP
						-- egress_wp = w																						--store tgt wp number
					-- end
					-- if egress_wp and w > egress_wp then																		--for all WP after target or first station WP
						-- waypoints[w]["ETA_locked"] = false
						-- waypoints[w]["speed_locked"] = true
					-- end
					
					-- --set speed locked for all WPs after Join. TOT would be better for waypoints to coordinate flights in package, but when AI is unable to meet TOT due to delays it continues at stall speed. Due to this bug, folllowing workaround is required
					-- if flight[f].route[w].id ~= "Taxi" and flight[f].route[w].id ~= "Departure" and flight[f].route[w].id ~= "Join" and flight[f].route[w].id ~= "Spawn" then
						-- waypoints[w]["ETA_locked"] = false
						-- waypoints[w]["speed_locked"] = true
					-- end
					-- --end workaround
					
					--player flight WP ETA
					if flight[f].player then
						if waypoints[w]["name"] == "Target" or waypoints[w]["name"] == "Station" then
							waypoints[w]["ETA_locked"] = true
							waypoints[w]["speed_locked"] = false
						elseif waypoints[w]["name"] == "Join" then															--ETA of join should be unlocked (so it is no target point for Viggen), but speed needs to be reduced to allow time for start up and take off
							waypoints[w]["ETA_locked"] = false
							waypoints[w]["speed_locked"] = true
							waypoints[w]["speed"] = GetDistance(waypoints[w - 1], waypoints[w]) / waypoints[w]["ETA"]		--exact speed to rach join at required ETA
						else
							waypoints[w]["ETA_locked"] = false
							waypoints[w]["speed_locked"] = true
						end
					end
					
					-- modification M06.b bug helico reste statique s'il demarre en horaire décalé
					-- M06.e
					if flight[f].helicopter == true   and flight[f].route[w].id ~= "Departure" then	 --and flight[f].task == "Transport"	
							waypoints[w]["ETA_locked"] = false
							waypoints[w]["speed_locked"] = true
					end
					
					--altitudes below 1000m are AGL instead of MSL
					if waypoints[w]["alt"] <= 1000 then
						waypoints[w]["alt_type"] = "RADIO"
					end
					
					--take off and landing
					if flight[f].route[w].id == "Taxi" or flight[f].route[w].id == "Intercept" then
						waypoints[w]["type"] = "TakeOffParking"
						waypoints[w]["action"] = "From Parking Area"
						if db_airbases[flight[f].base].unitname then									--airbase is a carrier
							waypoints[w]["linkUnit"] = flight[f].airdromeId
							waypoints[w]["helipadId"] = flight[f].airdromeId
							if flight[f].player ~= true and flight[f].client2 ~= true and not SuperCarrier then				--non player flights from carrier take of from runway -- and not SuperCarrier?f -- miguel21 modification M37 SuperCarrier		
								waypoints[w]["type"] = "TakeOff"
								waypoints[w]["action"] = "From Runway"
							end
						else
							waypoints[w]["airdromeId"] = flight[f].airdromeId
						end
						
						--if defined in conf_mod, player flight starts with engines running
						if flight[f].player == true and mission_ini.parking_hotstart then											--if flight[f].player == true and camp.hotstart then
							waypoints[w]["action"] = "From Parking Area Hot"
							waypoints[w]["type"] = "TakeOffParkingHot"
						--if defined in conf_mod, task intercept player flight starts with engines running							-- Miguel21 modification M08	: hotstart
						elseif flight[f].player == true and mission_ini.intercept_hotstart and flight[f].task == "Intercept" then	--if flight[f].player == true and camp.hotstart then
							waypoints[w]["action"] = "From Parking Area Hot"
							waypoints[w]["type"] = "TakeOffParkingHot"
						end
						
					elseif flight[f].route[w].id == "Land" then
						waypoints[w]["type"] = "Land"
						waypoints[w]["action"] = "Landing"
						if db_airbases[flight[f].base].unitname then
							waypoints[w]["linkUnit"] = flight[f].airdromeId
							waypoints[w]["helipadId"] = flight[f].airdromeId
						else
							waypoints[w]["airdromeId"] = flight[f].airdromeId
							if flight[f].task == "Nothing" then
								waypoints[w]["airdromeId"] = db_airbases[flight[f].target.destination].airdromeId
							end
						end
					end
					
					--target WP to be removed for non-player A-G attacks
					if flight[f].route[w].id == "Target" then											--WP is target WP
						if flight[f].task ~= "Reconnaissance" and flight[f].task ~= "Laser Illumination" then		--target WP is removed for all A-G tasks except recon or laser illumination
							if flight[f].player ~= true and flight[f].client2 ~= true then											--not the player flight (player always gets a target WP)
								target_wp_remove = w
							end
						end
					end
					
					--formations
					if flight[f].route[w].id == "Departure" or flight[f].route[w].id == "Spawn" then
						local task_entry = {															--Spread Four Close
							["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
							["auto"] = false,
							["id"] = "WrappedAction",
							["enabled"] = true,
							["params"] = 
							{
								["action"] = 
								{
									["id"] = "Option",
									["params"] = 
									{
										["variantIndex"] = 1,
										["name"] = 5,
										["formationIndex"] = 7,
										["value"] = 458753,
									},
								},
							},
						}
						table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
					end
					
					--ATO_FP_Reglage01 : emport, ne pas larguer les emports en cas d'urgence
					-- if flight[f].route[w].id == "Departure" or flight[f].route[w].id == "Spawn" then
						-- local task_entry = {
							-- ["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
							-- ["enabled"] = true,
							-- ["auto"] = false,
							-- ["id"] = "WrappedAction",
							-- ["params"] = 
							-- {
								-- ["action"] = 
								-- {
									-- ["id"] = "Option",
									-- ["params"] = 
									-- {
										-- ["value"] = true,
										-- ["name"] = 15,
									-- }, -- end of ["params"]
								-- }, -- end of ["action"]
							-- }, -- end of ["params"],
						-- }
						-- table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
					-- end


					-- modif Miguel M01 : ajout datalink EPLRS Capacity
					if (flight[f].route[w].id == "Departure"  or flight[f].route[w].id == "Spawn") and camp.date.year >= 1996 then
						if flight[f].type == "E-2C" or flight[f].type == "E-3A" or flight[f].type == "F-15C" or flight[f].type == "F-15E" or flight[f].type == "F-16C bl.52d"or flight[f].type == "FA-18C_hornet" or flight[f].type == "F/A-18C" then
							local task_entry = {
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["auto"] = true,
								["id"] = "WrappedAction",
								["enabled"] = true,
								["params"] =
								{
									["action"] =
									{
										["id"] = "EPLRS",
										["params"] =
										{
											["value"] = true,
											["groupId"] = 1,
										}, -- end of ["params"]
									}, -- end of ["action"]
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							end
						end
					
					--attack tasks
					if (flight[f].player == true and flight[f].route[w].id == "IP") or flight[f].route[w].id == "Attack" then	--Attack waypoint for AI or IP for player
						if flight[f].task == "Strike" and flight[f].target.class == nil then									--Tasks against scenery objects with multiple target sub-elements
							
							local target_element = {}																			--table to hold the target element number to be struck
							for e = 1, #flight[f].target.elements do															--iterate trough all target elements
								if flight[f].target.elements[e].dead ~= true then												--pick only elements that are not dead
									table.insert(target_element, e)																--add to target element table
								end
							end
							for n = 1, (f - 1) * 4 do																			--shift the order of target elements for subsequent flights in package, so that each flights starts attacking different elements (flight 1: element 1-4, flight 2: element 5-8, etc)
								table.insert(target_element, target_element[1])													--shift element order, copy first element to back
								table.remove(target_element, 1)																	--delete first element
							end
							
							--this is only to display attack markers in mission editor, task will be replaced in game by CustomMapObjectAttack
							-----------------------------------------------------------------------
							for n,e in ipairs(target_element) do
								local task_entry = {
									["enabled"] = false,
									["auto"] = false,
									["id"] = "AttackMapObject",
									["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
									["params"] = {
										["x"] = flight[f].target.elements[e].x,
										["y"] = flight[f].target.elements[e].y,
										["weaponType"] = weaponType,
										["expend"] = flight[f].loadout.expend,
										["direction"] = 0,
										["attackQtyLimit"] = false,
										["attackQty"] = 1,
										["directionEnabled"] = false,
										["groupAttack"] = true,
										["altitude"] = 2000,
										["altitudeEnabled"] = false,
									},
								}
								table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							end
							-----------------------------------------------------------------------
							
							local grpname = "Pack " .. p .. " - " .. flight[f].name .. " - " .. flight[f].task .. " " .. f
							local expend = flight[f].loadout.expend
							local attackType = flight[f].loadout.attackType or "nil"
							local attackAlt = flight[f].loadout.attackAlt or flight[f].loadout.hAttack
							local tgtlist = ""																					--list of of names of all target elements
							for n,e in ipairs(target_element) do
								tgtlist = tgtlist .. '{ x = ' .. flight[f].target.elements[e].x .. ', y = ' .. flight[f].target.elements[e].y .. '}, '
							end
							
							local task_entry = {																				--task is a command to run LUA code
								["enabled"] = true,
								["auto"] = false,
								["id"] = "WrappedAction",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Script",
										["params"] = 
										{
											["command"] = 'CustomMapObjectAttack("' .. grpname .. '", {' .. tgtlist .. '}, "' .. expend .. '", "' .. weaponType .. '", "' .. attackType .. '", ' .. attackAlt .. ')',	--this is a custom written task to allow all aircraft in flight to attack multiple static objects simultenously
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							
						elseif flight[f].task == "Strike" and flight[f].target.class == "vehicle" then
							
							--this is only to display attack markers in mission editor, task will be replaced in game by CustomGroupAttack
							-----------------------------------------------------------------------
							local task_entry = {
								["enabled"] = false,
								["auto"] = false,
								["id"] = "AttackGroup",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["groupId"] = flight[f].target.groupId,
									["weaponType"] = weaponType,
									["expend"] = flight[f].loadout.expend,
									["attackType"] = flight[f].loadout.attackType,
								}
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							-----------------------------------------------------------------------
							
							local grpname = "Pack " .. p .. " - " .. flight[f].name .. " - " .. flight[f].task .. " " .. f
							local expend = flight[f].loadout.expend
							local attackType = flight[f].loadout.attackType or "nil"
							local attackAlt = flight[f].loadout.attackAlt or flight[f].loadout.hAttack
							
							local task_entry = {																				--task is a command to run LUA code
								["enabled"] = true,
								["auto"] = false,
								["id"] = "WrappedAction",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Script",
										["params"] = 
										{
											["command"] = 'CustomGroupAttack("' .. grpname .. '", "' .. flight[f].target.name .. '", "' .. expend .. '", "' .. weaponType .. '", "' .. attackType .. '", ' .. attackAlt .. ')',
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							
						elseif flight[f].task == "Strike" and flight[f].target.class == "static" then
							
							local target_element = {}																			--table to hold the target element number to be struck
							for e = 1, #flight[f].target.elements do															--iterate trough all target elements
								if flight[f].target.elements[e].dead ~= true then												--pick only elements that are not dead
									table.insert(target_element, e)																--add to target element table
								end
							end
							for n = 1, (f - 1) * 4 do																			--shift the order of target elements for subsequent flights in package, so that each flights starts attacking different elements (flight 1: element 1-4, flight 2: element 5-8, etc)
								table.insert(target_element, target_element[1])													--shift element order, copy first element to back
								table.remove(target_element, 1)																	--delete first element
							end
							
							--this is only to display attack markers in mission editor, task will be replaced in game by CustomStaticAttack
							-----------------------------------------------------------------------
							for n,e in ipairs(target_element) do
								local task_entry = {
									["enabled"] = false,
									["auto"] = false,
									["id"] = "AttackGroup",
									["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
									["params"] = {
										["groupId"] = flight[f].target.elements[e].groupId,
										["weaponType"] = weaponType,
										["expend"] = flight[f].loadout.expend,
									},
								}
								table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							end
							-----------------------------------------------------------------------
						
							local grpname = "Pack " .. p .. " - " .. flight[f].name .. " - " .. flight[f].task .. " " .. f
							local expend = flight[f].loadout.expend
							local attackType = flight[f].loadout.attackType or "nil"
							local attackAlt = flight[f].loadout.attackAlt or flight[f].loadout.hAttack
							local tgtlist = ""																					--list of of names of all target elements
							for n,e in ipairs(target_element) do
								tgtlist = tgtlist .. '"' .. flight[f].target.elements[e].name .. '", '
							end
							
							local task_entry = {																				--task is a command to run LUA code
								["enabled"] = true,
								["auto"] = false,
								["id"] = "WrappedAction",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Script",
										["params"] = 
										{
											["command"] = 'CustomStaticAttack("' .. grpname .. '", {' .. tgtlist .. '}, "' .. expend .. '", "' .. weaponType .. '", "' .. attackType .. '", ' .. attackAlt .. ')',	--this is a custom written task to allow all aircraft in flight to attack multiple static objects simultenously
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							
						elseif flight[f].task == "Strike" and flight[f].target.class == "airbase" then							
							local grpname = "Pack " .. p .. " - " .. flight[f].name .. " - " .. flight[f].task .. " " .. f
							local expend = flight[f].loadout.expend
							local attackType = flight[f].loadout.attackType or "nil"
							local attackAlt = flight[f].loadout.attackAlt or flight[f].loadout.hAttack
							
							local task_entry = {																				--task is a command to run LUA code
								["enabled"] = true,
								["auto"] = false,
								["id"] = "WrappedAction",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Script",
										["params"] = 
										{
											["command"] = 'CustomAirbaseAttack("' .. grpname .. '", {x = ' .. flight[f].target.x .. ', y = ' .. flight[f].target.y .. '}, "' .. expend .. '", "' .. weaponType .. '", "' .. attackType .. '", ' .. attackAlt .. ')',
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							
						elseif flight[f].task == "Anti-ship Strike" then
							
							-- + ATO_FP_Debug03 Antiship strik
							-- --this is only to display attack markers in mission editor, task will be replaced in game by CustomGroupAttack
							-- -----------------------------------------------------------------------
							-- local task_entry = {
								-- ["enabled"] = false,
								-- ["auto"] = false,
								-- ["id"] = "AttackGroup",
								-- ["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								-- ["params"] = 
								-- {
									-- ["groupId"] = flight[f].target.groupId,
									-- ["weaponType"] = weaponType,
									-- ["expend"] = flight[f].loadout.expend,
									-- ["attackType"] = flight[f].loadout.attackType,
								-- }
							-- }
							-- table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							-- -----------------------------------------------------------------------
							
							-- local grpname = "Pack " .. p .. " - " .. flight[f].name .. " - " .. flight[f].task .. " " .. f
							-- local expend = flight[f].loadout.expend
							-- local attackType = flight[f].loadout.attackType or "nil"
							-- local attackAlt = flight[f].loadout.attackAlt or flight[f].loadout.hAttack
							
							-- local task_entry = {																				--task is a command to run LUA code
								-- ["enabled"] = true,
								-- ["auto"] = false,
								-- ["id"] = "WrappedAction",
								-- ["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								-- ["params"] = 
								-- {
									-- ["action"] = 
									-- {
										-- ["id"] = "Script",
										-- ["params"] = 
										-- {
											-- ["command"] = 'CustomGroupAttack("' .. grpname .. '", "' .. flight[f].target.name .. '", "' .. expend .. '", "' .. weaponType .. '", "' .. attackType .. '", ' .. attackAlt .. ')',
										-- },
									-- },
								-- },
							-- }
					
					
						-- + ATO_FP_Debug03 Antiship strike

							local task_entry = {															--Spread Four Close
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["enabled"] = true,
								["key"] = "AntiShip",
								["id"] = "EngageTargets",
								["auto"] = true,
								["params"] = 
								{
									["targetTypes"] = 
									{
										[1] = "Ships",
									}, -- end of ["targetTypes"]
									["priority"] = 0,
								}, -- end of ["params"]

							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)

							-- + ATO_FP_Debug03 Antiship strike
							local task_entry = {
								["enabled"] = true,
								["auto"] = false,
								["id"] = "AttackGroup",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["groupId"] = flight[f].target.groupId,
									["weaponType"] = weaponType,
									["expend"] = flight[f].loadout.expend,
									["attackType"] = flight[f].loadout.attackType,
								}
							}
							
							
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							
						elseif flight[f].task == "Flare Illumination" then
							
							--this is only to display attack markers in mission editor, task will be replaced in game by CustomFlareAttack
							-----------------------------------------------------------------------
							local task_entry = {
								["enabled"] = false,
								["auto"] = false,
								["id"] = "Bombing",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = {
									["x"] = flight[f].target.x,
									["y"] = flight[f].target.y,
									["direction"] = 0,
									["attackQtyLimit"] = false,
									["attackQty"] = 1,
									["expend"] = flight[f].loadout.expend,
									["altitude"] = 1524,
									["directionEnabled"] = false,
									["groupAttack"] = true,
									["altitudeEdited"] = true,
									["altitudeEnabled"] = true,
									["weaponType"] = weaponType,
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							-----------------------------------------------------------------------
						
							local grpname = "Pack " .. p .. " - " .. flight[f].name .. " - " .. flight[f].task .. " " .. f
							local expend = flight[f].loadout.expend
							local attackType = flight[f].loadout.attackType or "nil"
							local attackAlt = flight[f].loadout.attackAlt or flight[f].loadout.hAttack
							local tgtx = "n/a"																					--target coordinate n/a, custom attach script will determine latest target position at time of attack during the misssion
							local tgty = "n/a"																					--target coordinate n/a, custom attach script will determine latest target position at time of attack during the misssion
							if flight[f].target.class ~= "vehicle" then															--if target is not a vehicle or ship, then known target coordinates are used
								tgtx = flight[f].target.x																		--use known target coordinates
								tgty = flight[f].target.y																		--use known target coordinates
							end
							
							local task_entry = {																				--task is a command to run LUA code
								["enabled"] = true,
								["auto"] = false,
								["id"] = "WrappedAction",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Script",
										["params"] = 
										{
											["command"] = 'CustomFlareAttack("' .. grpname .. '", "' .. tgtx .. '", "' .. tgty .. '", "' .. flight[f].target.name .. '", "' .. expend .. '", "' .. weaponType .. '", "' .. attackType .. '", ' .. attackAlt .. ')',	--this is a custom written task to allow coordinates bombing of target poistion at time of attack
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						
						elseif flight[f].task == "Laser Illumination" then
							local grpname = "Pack " .. p .. " - " .. flight[f].name .. " - " .. flight[f].task .. " " .. f
							local LaserCode1 = math.random(1,8)
							local LaserCode2 = math.random(1,8)
							local LaserCode3 = math.random(1,8)
							flight[f].target.LaserCode = tonumber("1" .. LaserCode1 .. LaserCode2 .. LaserCode3)				--store laser code for flight target
							for ff = 1, #pack[p].main do																		--iterate through all main body flights
								pack[p].main[ff].target.LaserCode = tonumber("1" .. LaserCode1 .. LaserCode2 .. LaserCode3)		--store laser code in all main body flights
							end
							
							local tgt = ""
							local class
							if flight[f].target.class == "static" then
								class = "static"
								for e = 1, #flight[f].target.elements do
									tgt = tgt .. '"' .. flight[f].target.elements[e].name .. '", '
								end
							elseif flight[f].target.class == "vehicle" then
								class = "vehicle"
								tgt = flight[f].target.name
							elseif flight[f].target.class == "airbase" then
							
							else
								class = "scenery"
								for e = 1, #flight[f].target.elements do
									tgt = tgt .. '{ x = ' .. flight[f].target.elements[e].x .. ', y = ' .. flight[f].target.elements[e].y .. '}, '
								end
							end
							
							local task_entry = {																				--task is a command to run LUA code
								["enabled"] = true,
								["auto"] = false,
								["id"] = "WrappedAction",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Script",
										["params"] = 
										{
											["command"] = 'CustomLaserDesignation("' .. grpname .. '", "' .. tgt .. '", "' .. class .. '", "' .. flight[f].target.LaserCode .. '")',	--this is a custom written task to allow coordinates bombing of target poistion at time of attack
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						
						end
					end
					
					--SEAD engage tasks for each route segment
					if flight[f].task == "SEAD" then
						if flight[f].route[w].SEAD_radius then
							local task_entry = {
								["enabled"] = true,
								["auto"] = false,
								["id"] = "ControlledTask",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["task"] = 
									{
										["id"] = "EngageTargets",
										["params"] = 
										{
											["targetTypes"] = 
											{
												[1] = "SAM TR",
											},
											["maxDistEnabled"] = true,
											["priority"] = 0,
											["maxDist"] = flight[f].route[w].SEAD_radius,
											["weaponType"] = weaponType,
											["expend"] = flight[f].loadout.expend,
											["attackType"] = flight[f].loadout.attackType,
											["altitudeEdited"] = true,
											["altitudeEnabled"] = true,
											["altitude"] = flight[f].loadout.attackAlt or flight[f].loadout.hAttack,
										},
									},
									["stopCondition"] = 
									{
										["lastWaypoint"] = w + 1,
									},
								}
							}
							if flight[f].loadout.weaponType == nil then							--if no specific weapon type defined in loadout
								task_entry.params.task.params.weaponType = 268402702			--use Anti-Radar Missile
							end
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						end
					end
					
					--Escort and Fighter Sweep Custom Search and Engage Task
					if flight[f].task == "Fighter Sweep" then
						if flight[f].route[w].id == "Join" or (flight[f].route[w].id == "Spawn" and (flight[f].route[w + 1].id ~= "Join" and flight[f].route[w + 1].id ~= "Departure")) then
							local grpname = "Pack " .. p .. " - " .. flight[f].name .. " - " .. flight[f].task .. " " .. f
							local task_entry = {	
								["enabled"] = true,
								["auto"] = false,
								["id"] = "WrappedAction",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Script",
										["params"] = 
										{
											["command"] = 'CustomSearchThenEngage("' .. grpname .. '", ' .. flight[f].loadout.standoff .. ', "Air")',
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)	
						end
					elseif flight[f].task == "Escort" then
						if flight[f].route[w].id == "Join" or (flight[f].route[w].id == "Spawn" and (flight[f].route[w + 1].id ~= "Join" and flight[f].route[w + 1].id ~= "Departure")) then
							local target = "Battle airplanes"
							if  flight[f].helicopter == true then															-- modif Miguel21 M06 : helicoptere playable
								target = "Helicopters"
							end
							
							local grpname = "Pack " .. p .. " - " .. flight[f].name .. " - " .. flight[f].task .. " " .. f
							local task_entry = {	
								["enabled"] = true,
								["auto"] = false,
								["id"] = "WrappedAction",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Script",
										["params"] = 
										{
											["command"] = 'CustomSearchThenEngage("' .. grpname .. '", ' .. flight[f].loadout.standoff .. ', "'..target..'")',
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						end
					end
					
					--station tasks
					if flight[f].route[w].id == "Station" and flight[f].route[w + 1].id == "Station" then
						if flight[f].task == "CAP" then
							local task_entry = {
								["enabled"] = true,
								["auto"] = false,
								["id"] = "ControlledTask",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["task"] = 
									{
										["id"] = "EngageTargetsInZone",
										["params"] = 
										{
											["targetTypes"] = 
											{
												[1] = "Air",
												[2] = "Cruise missiles",
											},
											["x"] = flight[f].target.x,
											["y"] = flight[f].target.y,
											["value"] = "Air;Cruise missiles;",
											["priority"] = 0,
											["zoneRadius"] = flight[f].target.radius,
										},
									},
									["stopCondition"] = 
									{
										["lastWaypoint"] = w + 1,
									},
								}
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)							
						elseif flight[f].task == "AWACS" then
							local task_entry = {
								["enabled"] = true,
								["auto"] = false,
								["id"] = "ControlledTask",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["task"] = 
									{
										["id"] = "AWACS",
										["params"] = {},
									},
									["stopCondition"] = 
									{
										["lastWaypoint"] = w + 1,
									},
								}
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						elseif flight[f].task == "Refueling" then
							local task_entry = {
								["enabled"] = true,
								["auto"] = false,
								["id"] = "ControlledTask",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["task"] = 
									{
										["id"] = "Tanker",
										["params"] = {},
									},
									["stopCondition"] = 
									{
										["lastWaypoint"] = w + 1,
									},
								}
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						end
					end
					
					--orbit on departure
					if flight[f].route[w].id == "Departure" then
						if flight[f].number > 1 or (#flight > 1 and flight[f].loadout.tStation == nil) or flight[f].target.firepower.packmax then		--orbit on departure only for flights larger than 1-ship, flights that are part of a package (but no on-station tasks) or multi-packages
							local grpname = "Pack " .. p .. " - " .. flight[f].name .. " - " .. flight[f].task .. " " .. f
							local task_entry = {	
								["enabled"] = true,
								["auto"] = false,
								["id"] = "WrappedAction",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Script",
										["params"] = 
										{
											["command"] = 'OrbitPosition("' .. grpname .. '", ' .. waypoints[w]["alt"] .. ', ' .. pack[p].main[1].loadout.vCruise / 3 * 2 .. ', ' .. departure_time .. ')',
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						end
					end
					
					--A-A TACAN for tankers, activate TACAN on first orbit WP
					if flight[f].route[w].id == "Station" and flight[f].route[w + 1].id == "Station" then
						if flight[f].task == "Refueling" then
							if flight[f].type == "KC-135" or flight[f].type == "KC130" or flight[f].type == "KC135BDA" or flight[f].type == "S-3B Tanker" or flight[f].type == "KC135MPRS" then	--only specific tanker types have air-air TACAN
								if flight[1].tacan == nil then
									flight[1].tacan = GetTankerTACAN()															--get new channel for first flight in pack only, all other flights will use same channel
								end
								local task_entry = {
									["enabled"] = true,
									["auto"] = true,
									["id"] = "WrappedAction",
									["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
									["params"] = 
									{
										["action"] = 
										{
											["id"] = "ActivateBeacon",
											["params"] = 
											{
												["type"] = 4,
												["AA"] = true,
												["unitId"] = id_counter,
												["modeChannel"] = "Y",
												["name"] = "",
												["channel"] = flight[1].tacan,
												["callsign"] = "TKR",
												["system"] = 4,
												["bearing"] = true,
												["frequency"] = 1087000000 + flight[1].tacan * 1000000,
											},
										},
									},
								}
								if task_entry.params.action.params.frequency > 1150000000 then
									task_entry.params.action.params.frequency = task_entry.params.action.params.frequency - 126000000
								end
								table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							end
						end
					end
					
					--A-A TACAN for tankers, deactivate beacon on second orbit WP
					if flight[f].route[w].id == "Station" and flight[f].route[w - 1].id == "Station" then
						if flight[f].task == "Refueling" then
							if flight[f].type == "KC-135" or flight[f].type == "KC130" or flight[f].type == "KC135BDA" or flight[f].type == "S-3B Tanker" then	--only specific tanker types have air-air TACAN			
								local task_entry = {
									["enabled"] = true,
									["auto"] = false,
									["id"] = "WrappedAction",
									["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
									["params"] = 
									{
										["action"] = 
										{
											["id"] = "DeactivateBeacon",
											["params"] = 
											{
											},
										},
									},
								}
								table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							end
						end
					end
					
					--orbit on station
					if flight[f].route[w].id == "Station" and flight[f].route[w + 1].id == "Station" then
						local task_entry = {
							["enabled"] = true,
							["auto"] = false,
							["id"] = "ControlledTask",
							["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
							["params"] = 
							{
								["task"] = 
								{
									["id"] = "Orbit",
									["params"] = 
									{
										["altitude"] = flight[f].loadout.hAttack,
										["pattern"] = "Race-Track",
										["speed"] = flight[f].loadout.vAttack,
									},
								},
								["stopCondition"] = 
								{
									["time"] = flight[f].route[w + 1].eta
								}
							}
						}
						table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
					end
					
					--SEAD switch from IP to egress
					if flight[f].route[w].id == "IP" and flight[f].task == "SEAD" then
						local task_entry = {
							["enabled"] = true,
							["auto"] = false,
							["id"] = "WrappedAction",
							["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
							["params"] = {
								["action"] = {
									["id"] = "SwitchWaypoint",
									["params"] = {				
										["fromWaypointIndex"] = w,						--from IP
										["goToWaypointIndex"] = w + 2,					--directly to egress
									},
								},
							},
						}
						table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						
						local task_entry2 = {
							["enabled"] = true,
							["auto"] = false,
							["id"] = "ControlledTask",
							["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
							["params"] = {
								["task"] = {
									["id"] = "Orbit",
									["params"] = {
										["altitude"] = waypoints[w]["alt"],
										["pattern"] = "Race-Track",
										["speed"] = pack[p].main[1].loadout.vCruise,
										["speedEdited"] = true,
									},
								}, 
								["stopCondition"] = {
									["time"] = flight[f].route[w + 2].eta,
								},
							},
						}
						table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry2)
					end
					
					--orbit on egress
					if flight[f].route[w].id == "Egress" and flight[f].task == "Escort" then
						local task_entry = {
							["enabled"] = true,
							["auto"] = false,
							["id"] = "ControlledTask",
							["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
							["params"] = 
							{
								["task"] = 
								{
									["id"] = "Orbit",
									["params"] = 
									{
										["altitude"] = waypoints[w]["alt"],
										["pattern"] = "Circle",
										["speed"] = pack[p].main[1].loadout.vCruise,
									},
								},
								["stopCondition"] = 
								{
									["time"] = flight[f].route[w].eta
								}
							}
						}
						table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
					end
					
					--rejoin flight on egress
					if (flight[f].task == "Strike" or flight[f].task == "Anti-ship Strike" ) and flight[f].route[w].id == "Egress" then					
						local grpname = "Pack " .. p .. " - " .. flight[f].name .. " - " .. flight[f].task .. " " .. f
						local task_entry = {																				--task is a command to run LUA code
							["enabled"] = true,
							["auto"] = false,
							["id"] = "WrappedAction",
							["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
							["params"] = 
							{
								["action"] = 
								{
									["id"] = "Script",
									["params"] = 
									{
										["command"] = 'CustomRejoin("' .. grpname .. '")',
									},
								},
							},
						}
						table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
					end
					
					--restrict RTB on winchester from IP on
					--[[if flight[f].route[w].id == "IP" and (flight[f].task == "SEAD" or flight[f].task == "Strike" or flight[f].task == "Anti-ship Strike" or flight[f].task == "Flare Illumination" or flight[f].task == "Laser Illumination") then
						if flight[f].player ~= true then
							local task_entry = {
								["enabled"] = true,
								["auto"] = false,
								["id"] = "WrappedAction",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Option",
										["params"] = 
										{
											["value"] = 0,
											["name"] = 10,
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						end
					end]]--
					
					--restrict weapon jettison from IP on
					--[[if flight[f].route[w].id == "IP" and (flight[f].task == "Strike" or flight[f].task == "Anti-ship Strike" or flight[f].task == "Flare Illumination" or flight[f].task == "Laser Illumination") then
						if flight[f].player ~= true then	
							local task_entry = {
								["enabled"] = true,
								["auto"] = false,
								["id"] = "WrappedAction",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Option",
										["params"] = 
										{
											["value"] = true,
											["name"] = 15,
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						end
					end]]--
					
					--allow weapon jettison from egress on
					if flight[f].route[w].id == "Egress" and (flight[f].task == "SEAD" or flight[f].task == "Strike" or flight[f].task == "Anti-ship Strike" or flight[f].task == "Flare Illumination" or flight[f].task == "Laser Illumination") then
						if flight[f].player ~= true and flight[f].client2 ~= true then	
							local task_entry = {
								["enabled"] = true,
								["auto"] = false,
								["id"] = "WrappedAction",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Option",
										["params"] = 
										{
											["value"] = false,
											["name"] = 15,
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						end
					end
					
					--IP/egress reaction on threat for recon
					if flight[f].task == "Reconnaissance" and flight[f].route[w].id == "IP" then
						if flight[f].player ~= true and flight[f].client2 ~= true then	
							local task_entry = {
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["auto"] = false,
								["id"] = "WrappedAction",
								["enabled"] = true,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Option",
										["params"] = 
										{
											["value"] = 1,
											["name"] = 1,
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						end
					elseif flight[f].task == "Reconnaissance" and flight[f].route[w].id == "Egress" then
						if flight[f].player ~= true and flight[f].client2 ~= true then	
							local task_entry = {
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["auto"] = false,
								["id"] = "WrappedAction",
								["enabled"] = true,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Option",
										["params"] = 
										{
											["value"] = 2,
											["name"] = 1,
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						end
					end
					
					--navigation information on waypoint name for player flight
					if flight[f].player or flight[f].client2 then																				--flight is player flight
						if waypoints[w - 1] then																			--previous waypoint exists
							local distance = GetDistance(waypoints[w - 1], waypoints[w])									--distance between waypoints
							if waypoints[w].name == "Target" then
								distance = GetDistance(waypoints[w - 2], waypoints[w])										--for target waypoint measure distance from IP, since attack point is removed for player flight
							end
							if distance > 0 then																			--distance is not zero
								local heading = math.floor(GetHeading(waypoints[w - 1], waypoints[w]))						--heading between waypoints
								heading = heading - camp.variation															--adjust heading (true heading) with variation of map to get magnetix heading
								if heading < 0 then
									heading = heading + 360
								elseif heading > 359 then
									heading = heading - 360
								end
								if heading < 10 then
									heading = "00" .. heading
								elseif heading < 100 then
									heading = "0" .. heading
								end
								if camp.units == "metric" then
									distance = math.ceil(distance / 1000) .. "KM"
								else
									distance = math.ceil(distance / 1000 * 0.539957) .. "NM"
								end
								-- Miguel21 modification M17
								if flight[f].type == "F-14B" and NavTargetPoints[1] then
									if waypoints[w].name == "Target" or waypoints[w].name == "Attack" then  waypoints[w].name = "ST" end
									if waypoints[w].name == "Station"  then  waypoints[w].name = "DP" end
								end
								waypoints[w]["name"] = waypoints[w]["name"] .. ": " .. heading .. "/" .. distance			--add heading and distance to waypoint name
							end
						end
					end
				end	-- Fin de Route
				
				--lock ETA and speed of first waypoint
				waypoints[1]["ETA_locked"] = true
				waypoints[1]["speed_locked"] = true
				if waypoints[1]["speed"] == nil then
					waypoints[1]["speed"] = 1
				end
				
				--remove attack WP for player flight
				if flight[f].player == true or flight[f].client2 == true then
					for w = 1, #waypoints do
						if waypoints[w].briefing_name == "Attack" then
							table.remove(waypoints, w)
							camp.player.tgt_wp = camp.player.tgt_wp - 1
							break
						end
					end
				end
				
				--store player waypoints for briefing creation
				if flight[f].player == true then
					camp.player.waypoints = deepcopy(waypoints)
					if camp.player.waypoints[2] then
						camp.player.waypoints[2].speed = 0
						camp.player.waypoints[2].alt = 0
					end
					if camp.player.waypoints[3] then
						camp.player.waypoints[3].speed = pack[p].main[1].loadout.vCruise / 4 * 3
					end
				end
				
				if flight[f].client2 == true then
					camp.player2.waypoints = deepcopy(waypoints)
				end
					
				
				--remove target WP for certain flights
				if target_wp_remove then
					table.remove(waypoints, target_wp_remove)
					
					for w = target_wp_remove, #waypoints do												--adjust stop condition WPs
						if waypoints[w]["task"]["params"]["tasks"] then									--WP has tasks
							for task_n,task in ipairs(waypoints[w]["task"]["params"]["tasks"]) do		--go through tasks
								if task["params"]["stopCondition"] and task["params"]["stopCondition"]["lastWaypoint"] then					--task has a last waypoint stop condition
									task["params"]["stopCondition"]["lastWaypoint"] = task["params"]["stopCondition"]["lastWaypoint"] - 1	--decreas last WP number by one to account for the removed WP
								end
								if task["params"]["action"] and task["params"]["action"]["id"] == "SwitchWaypoint" then						--task is a switch WP
									task["params"]["action"]["params"]["fromWaypointIndex"] = task["params"]["action"]["params"]["fromWaypointIndex"] - 1
									task["params"]["action"]["params"]["goToWaypointIndex"] = task["params"]["action"]["params"]["goToWaypointIndex"] - 1
								end
							end
						end
					end
				end
				
				--remove taxi waypoint
				if waypoints[1].name == "Taxi" then
					waypoints[2]["airdromeId"] = waypoints[1]["airdromeId"]
					waypoints[2]["linkUnit"] = waypoints[1]["linkUnit"]
					waypoints[2]["helipadId"] = waypoints[1]["helipadId"]
					waypoints[2]["action"] = waypoints[1]["action"]
					waypoints[2]["type"] = waypoints[1]["type"]
					table.remove(waypoints, 1)
					waypoints[1]["ETA"] = spawn_time
					waypoints[1]["ETA_locked"] = true
					waypoints[1]["speed_locked"] = true
					if waypoints[1]["speed"] == nil then
						waypoints[1]["speed"] = 1
					end
					
					for w = 1, #waypoints do															--adjust stop condition WPs
						if waypoints[w]["task"]["params"]["tasks"] then									--WP has tasks
							for task_n,task in ipairs(waypoints[w]["task"]["params"]["tasks"]) do		--go through tasks
								if task["params"]["stopCondition"] and task["params"]["stopCondition"]["lastWaypoint"] then					--task has a last waypoint stop condition
									task["params"]["stopCondition"]["lastWaypoint"] = task["params"]["stopCondition"]["lastWaypoint"] - 1	--decreas last WP number by one to account for the removed WP
								end
								if task["params"]["action"] and task["params"]["action"]["id"] == "SwitchWaypoint" then						--task is a switch WP
									task["params"]["action"]["params"]["fromWaypointIndex"] = task["params"]["action"]["params"]["fromWaypointIndex"] - 1
									task["params"]["action"]["params"]["goToWaypointIndex"] = task["params"]["action"]["params"]["goToWaypointIndex"] - 1
								end
							end
						end
					end
				end
				
				--add descend waypoint
				if flight[f].player ~= true and flight[f].client2 ~= true then																--for AI flights only
					for w = 3, #waypoints do
						if waypoints[w].alt < waypoints[w - 1].alt and waypoints[w]["type"] ~= "Land" then		--for any descend waypoint that is not the landing waypoint
							local extraWP = deepcopy(waypoints[w])												--make a copy of the descend waypoint
							extraWP.x = (waypoints[w].x + waypoints[w + -1].x) / 2								--position half-way between descend waypoint and previous waypoint
							extraWP.y = (waypoints[w].y + waypoints[w + -1].y) / 2								--position half-way between descend waypoint and previous waypoint
							extraWP.ETA = (waypoints[w].ETA + waypoints[w + -1].ETA) / 2						--ETA half-way between descend waypoint and previous waypoint
							extraWP.task.params.tasks = {}
							extraWP.name = "AI Descend Helper"
							table.insert(waypoints, w, extraWP)
							
							--adjust stop condition and switch WPs
							for w2 = w, #waypoints do															--go through waypoints from inserted WP to end
								if waypoints[w2]["task"]["params"]["tasks"] then								--WP has tasks
									for task_n,task in ipairs(waypoints[w2]["task"]["params"]["tasks"]) do		--go through tasks
										if task["params"]["stopCondition"] and task["params"]["stopCondition"]["lastWaypoint"] then					--task has a last waypoint stop condition
											task["params"]["stopCondition"]["lastWaypoint"] = task["params"]["stopCondition"]["lastWaypoint"] + 1	--increase last WP number by one to account for the inserted WP
										end
										if task["params"]["action"] and task["params"]["action"]["id"] == "SwitchWaypoint" then						--task is a switch WP
											task["params"]["action"]["params"]["fromWaypointIndex"] = task["params"]["action"]["params"]["fromWaypointIndex"] + 1
											task["params"]["action"]["params"]["goToWaypointIndex"] = task["params"]["action"]["params"]["goToWaypointIndex"] + 1
										end
									end
								end
							end
						end
					end
				end
				
				--first waypoint RTB on winchester
				--disabled due to AI problems (AI will ignore all threats once in RTB mode)
				--[[if flight[f].task == "SEAD" or flight[f].task == "CAS" or flight[f].task == "Ground Attack" or flight[f].task == "Pinpoint Strike" or flight[f].task == "Runway Attack" or flight[f].task == "Anti-ship Strike" then
					if flight[f].player ~= true then
						local task_entry = {
							["enabled"] = true,
							["auto"] = false,
							["id"] = "WrappedAction",
							["number"] = #waypoints[1]["task"]["params"]["tasks"] + 1,
							["params"] = 
							{
								["action"] = 
								{
									["id"] = "Option",
									["params"] = 
									{
										["value"] = weaponType,
										["name"] = 10,
									},
								},
							},
						}
						table.insert(waypoints[1]["task"]["params"]["tasks"], task_entry)
					end
				]]--end
				
				--first waypoint reaction to threat
				local task_entry = {
					["number"] = #waypoints[1]["task"]["params"]["tasks"] + 1,
					["auto"] = false,
					["id"] = "WrappedAction",
					["enabled"] = true,
					["params"] = 
					{
						["action"] = 
						{
							["id"] = "Option",
							["params"] = 
							{
								["value"] = 2,
								["name"] = 1,
							},
						},
					},
				}
				table.insert(waypoints[1]["task"]["params"]["tasks"], task_entry)
				
				--ATO_FP_Reglage01 : emport, ne pas larguer les emports en cas d'urgence pour les Strike
				--first waypoint restrict jettison for SEAD
				if flight[f].task == "SEAD" or flight[f].task == "Strike" or flight[f].task == "Anti-ship Strike" or flight[f].task == "Flare Illumination" or flight[f].task == "Laser Illumination" then
					local task_entry = {
						["enabled"] = true,
						["auto"] = false,
						["id"] = "WrappedAction",
						["number"] = #waypoints[1]["task"]["params"]["tasks"] + 1,
						["params"] = 
						{
							["action"] = 
							{
								["id"] = "Option",
								["params"] = 
								{
									["value"] = true,
									["name"] = 15,
								},
							},
						},
					}
					table.insert(waypoints[1]["task"]["params"]["tasks"], task_entry)
				end
				
				--first waypoint restrict air-air
				if flight[f].loadout.restrict_aa then
					local task_entry = {
						["enabled"] = true,
						["auto"] = false,
						["id"] = "WrappedAction",
						["number"] = #waypoints[1]["task"]["params"]["tasks"] + 1,
						["params"] = 
						{
							["action"] = 
							{
								["id"] = "Option",
								["params"] = 
								{
									["value"] = true,
									["name"] = 14,
								},
							},
						},
					}
					table.insert(waypoints[1]["task"]["params"]["tasks"], task_entry)
				end
				
				--first waypoint no RTB on bingo
				if flight[f].airdromeId == nil then
					local task_entry = {
						["enabled"] = true,
						["auto"] = false,
						["id"] = "WrappedAction",
						["number"] = #waypoints[1]["task"]["params"]["tasks"] + 1,
						["params"] = 
						{
							["action"] = 
							{
								["id"] = "Option",
								["params"] = 
								{
									["value"] = false,
									["name"] = 6,
								},
							},
						},
					}
					table.insert(waypoints[1]["task"]["params"]["tasks"], task_entry)
				end
												
				
				----- define units -----
				
				-- Miguel21 modification Multijoueur M11.k
				if ( coopFlag01  and flight[f].player  and flight[f].type == type_flight_01 and not SuperCarrier ) then					-- M37
					if flight[f].number >= 2 and coop <=2 then																			-- on ne veut pas d'avionIA au dela de 2
						flight[f].number = 2
					else
						flight[f].number = coop
					end	
					flight[f].multi1 = true						
				elseif ( coopFlag02  and   flight[f].client2   and flight[f].type == type_flight_02  and not SuperCarrier  ) then		-- si le type d'avion N�2 ET s'il d�colle avant 15mn
					if flight[f].number >= 2 and  coop_flight2 <=2 then
						flight[f].number = 2
					else
						flight[f].number = coop_flight2
					end	
					-- flight[f].multi2 = true
				end
				
				local units = {}
				for n = 1, flight[f].number do
					-- Miguel21 modification M12.b : Skill
					-- le niveau est s�par� en 4 (25% de 100)
					--Average (0 � 25)
					--Good (25� 50)
					--High (50 � 75)
					--Excellent (75 � 100)
					
					if flight[f].skill == "high" then
						calcWish = 62
					else 
						calcWish = skillWish[side]
					end
					
					if n == 1 or ( flight[f].player and n == 2 )then 
						mSkill =  math.random(calcWish-20, calcWish+18) / 25 		-- 75-62 = 13 (13 + 5 = 18 )5 % de chance d'avoir excellent
					else
						mSkill =  math.random(calcWish-50, calcWish+10) / 25
					end

		
					mSkill = math.floor(mSkill) + 1
					
					if mSkill < 1 then mSkill = 1
					elseif mSkill > 4 then mSkill = 4
					else mSkill = mSkill
					end	
					
					
					units[n] = {
						["alt"] = waypoints[1].alt,
						["heading"] = 0,
						["callsign"] = GetCallsign(flight[f].country, f, n, flight[f].task),
						["psi"] = 0,
						["livery_id"] = flight[f].livery,
						["type"] = flight[f].type,
						["y"] = waypoints[1]["y"] + ((n - 1) * 100) +  ((Pn - 1) * 1000), --ATO_FP_Debug01
						["x"] = waypoints[1]["x"] + ((n - 1) * 100) +  ((Pn - 1) * 1000), -- ATO_FP_Debug01
						["name"] = "Pack " .. p .. " - " .. flight[f].name .. " - " .. flight[f].task .. " " .. f .. "-" .. n,
						-- ["payload"] = flight[f].loadout.stores,
						["payload"] = {
							["pylons"] = flight[f].loadout.stores.pylons,
							["fuel"] = flight[f].loadout.stores.fuel,
							["flare"] = flight[f].loadout.stores.flare,
							["chaff"] = flight[f].loadout.stores.chaff,
							["gun"] =  flight[f].loadout.stores.gun,										-- ATO_FP_Debug04 Gun = 0 uniquement sur un Flight
						},
						["AddPropAircraft"] = flight[f].loadout.AddPropAircraft,
						["speed"] = waypoints[1].speed,
						["unitId"] = GenerateID(),
						["alt_type"] = waypoints[1].alt_type,
						["skill"] = skillTab[mSkill],
						["hardpoint_racks"] = true,

					}
					
					if not SuperCarrier then
						units[n]["parking"] = tostring(n)
						units[n]["parking_id"] = tostring(n)
					end
					if flight[f].sidenumber and flight[f].sidenumber[1] and flight[f].sidenumber[2] then		--squadron has sidenumbers defined
						units[n]["onboard_num"] = GetSidenumber(flight[f].name, flight[f].sidenumber[1], flight[f].sidenumber[2])	--get new sidenumber
					else																						--squadron has no sidenumbers defined
						units[n]["onboard_num"] = "0" .. math.random(1, 99)										--us a random number
					end
					
					--multiple skins for aircraft
					if type(units[n]["livery_id"]) == "table" then												--if skin is a table
						units[n]["livery_id"] = units[n]["livery_id"][math.random(1, #units[n]["livery_id"])]	--chose a random skin from table
					end
					
					-- modification Miguel M17
					if flight[f].type == "F-14B" and ( flight[f].player or flight[f].multi2 ) and AddPropAircraft then
						 units[n]["AddPropAircraft"] = AddPropAircraft 
					end
					
					--remove gun ammunition from AI escorts to prevent them from strafing aircraft on the ground at hostile air bases
					-- if (flight[f].task == "Escort" and not flight[f].player ) and (flight[f].task == "Escort" and not flight[f].client2 ) then	--if fligh is taskes as escort and is not player flight
					if flight[f].task == "Anti-ship Strike" and not (flight[f].player or flight[f].client2 ) then
						if units[n].payload.gun and units[n].payload.gun == 100 then								--if loadout has full gun ammo
							units[n].payload.gun = 0																--remove all gun ammo
						end
					end
				end
				
				----- define group -----
				local group = {				
					['frequency'] = GetFrequency(side, flight[f].target_name, flight[f].task, flight[f].type, flight[f].helicopter),				-- M06
					['taskSelected'] = true,
					['modulation'] = 0,
					['groupId'] = GenerateID(),
					['tasks'] = {
					},
					['route'] = {
						['points'] = waypoints,
					},
					['hidden'] = true,
					['units'] = units,
					['radioSet'] = true,
					["name"] = "Pack " .. p .. " - " .. flight[f].name .. " - " .. flight[f].task .. " " .. f,
					['communication'] = true,
					['x'] = waypoints[1]["x"],
					['y'] = waypoints[1]["y"],
					['start_time'] = 1,
					['task'] = flight[f].task,
					['uncontrolled'] = false,
				}
				
				-- ATO_FP_Debug01
				-- decale les apparitions en vol pour eviter les collisions en vol
				if waypoints[1]["type"] == "Spawn" then
					for	n = 1 , #group.units do
						group.units[n].x = ((Pn-1) * 1000) + group.units[n].x
						group.units[n].y = ((Pn-1) * 1000) + group.units[n].y
					end
				end
				
				-- modif M17
				if flight[f].type == "F-14B" and NavTargetPoints[1] then
					 group["NavTargetPoints"]= NavTargetPoints 
				end
				
				if flight[f].task == "Strike" then												--Strike is a generic A-G task that needs to be replaced by the respective DCS task
					if flight[f].loadout.weaponType == "ASM"  then						-- + ATO_Debug12 strike ASM B52
						group['task'] = "Pinpoint Strike"
					elseif flight[f].target.class == nil then
						group['task'] = "Ground Attack"
					elseif flight[f].target.class == "vehicle" then
						group['task'] = "CAS"
					elseif flight[f].target.class == "static" then
						group['task'] = "CAS"
					elseif flight[f].target.class == "airbase" then
						group['task'] = "CAS"
					end
				elseif flight[f].task == "Escort Jammer" then									--Escort Jammer task does not exitsts in DCS and needs to be replaced
					group['task'] = "Ground Attack"
				elseif flight[f].task == "Flare Illumination" then								--Flare illumination task does not exist in DCS and needs to be replaced
					group['task'] = "Ground Attack"
				elseif flight[f].task == "Laser Illumination" then								--Laser illumination task does not exist in DCS and needs to be replaced
					group['task'] = "AFAC"
				elseif flight[f].task == "Anti-ship Strike" then 
					group['task'] = "Antiship Strike"											-- Miguel debugB 
				end
				
				if camp.player and camp.player.side == side and camp.player.pack_n == p and camp.player.EWR_freq then		--player package and player has an EWR frequency (site that detected targets to intercept)
					if #camp.radio == 1 then													--if the player aircraft has only one radio
						group['frequency'] = tonumber(camp.player.EWR_freq)						--put player package on EWR frequency	
					end
				end
				
				---- unhide player package -----
				if camp.debug then																--debug is on
					group.hidden = false														--unhide all groups
				elseif camp.player and camp.player.side == side then							--player side										
					group.hidden = false														--unhide group
					--if camp.player.pack_n == p then											--package is player package
						--group.hidden = false													--unhide group
					--elseif flight[f].task == "AWACS" then										--flight is an AWACS on player side
						--group.hidden = false													--unhide group
					--elseif flight[f].task == "Refueling" then									--flight is a tanker on player side
						--group.hidden = false													--unhide group
					--end
				elseif camp.player2 and camp.player2.side == side then							--player side										
					group.hidden = false														--unhide group
				end
				
				
				-- modification Miguel M11.k + M37
				-- en multijoueur, limite à 2 F14 pour le spawn || contre le bug 2.5.6. (sauf le SuperCarrier)
				if coopFlag01 and flight[f].type == 'F-14B'   and (flight[f].player == true or flight[f].client2) and flight[f].number > 2  and string.find(flight[f].base,"CVN")  and not SuperCarrier then		-- M37
					for nb = flight[f].number ,2 +1, -1 do
						table.remove(units, nb)
					end

					flight[f].number = 2
					coop = 2
				end
				
				-- Miguel21 modification M31 	Remove all static aircraft from the deck
				if  mission_ini.CVN_CleanDeck == true and string.find(flight[f].base,"CVN") then
					deleteStaticOnCVN(flight[f].base)
				end	
				
				-- if flight[f].client2   then														-- Multijoueur : si le type d'avion N�2 
					-- -- waypoints[1].ETA = 0
					-- spawn_time = 0
				-- end
				
				local TimingCata
				if SuperCarrier and db_airbases[flight[f].base].unitname and  ( flight[f].player or flight[f].client2 ) then
					TimingCata = true
				end
				
				if not mission_ini.SC_SpawnOn[flight[f].type] then  mission_ini.SC_SpawnOn[flight[f].type] = "deck" end
	
				local SpawnDeck = true
				local SpawnAir = false
				if SuperCarrier and db_airbases[flight[f].base].unitname and not ( flight[f].player or flight[f].client2 ) then
					if  mission_ini.SC_SpawnOn[flight[f].type] == "catapult" then 
						SpawnDeck = false
						SpawnCata = true
					elseif  mission_ini.SC_SpawnOn[flight[f].type] == "air" then 
						SpawnDeck = false
						SpawnAir = true
					end
				end

				----- late groups spawn uncontrolled at mission start -----
				if (group['route']['points'][1]["ETA"] > 0 and flight[f].task ~= "Intercept") or TimingCata then		--group launches after mission start																	-- calcul le nombre de flight dans un Package, en comptant ceux des Roles
					if  SuperCarrier or (flight[f].player ~= true and flight[f].client2 ~= true ) then				--for non-player groups
						if db_airbases[flight[f].base].unitname  then												--for groups on aircraft carriers -- miguel21 modification M37.e SuperCarrier   and ((not SuperCarrier ) or (SuperCarrier and spawn_time>600))
							if camp.player and camp.player.side == side and camp.player.pack_n == p and flight[f].task ~= "AWACS" and flight[f].task ~= "Refueling" then	--for flights in player's package and package does not cover a station and flight[f].task ~= "CAP"
								
								local seq = 2																		--launch sequence seconde of flight in package
								local seqT = NbFlightPlayer																		--lauch sequence number
								for role2,flight2 in pairs(pack[p]) do												--iterate through roles in package (main, SEAD, escort)			
									for x = 1, #flight2 do															--iterate through flights in roles
										--seq = mission_ini.startup_time_player - ((NbFlightPackage - seqT) *200)-200
										seq = mission_ini.startup_time_player - ((NbFlightPackage - seqT) * mission_ini.CVN_TimeBtwPlane)-(NbFlightPlayer * mission_ini.CVN_TimeBtwPlane)	--decremente de 150s en gardant le premier creneau pour le joueur
										
										if role2 == role and f == x then																					--lorsqu'on trouve l'unite correspondante
											spawn_time = seq																								--H planning cata ou H active 
											activG_spawn_time = seqT																						--active le groupe
											if seqT >= mission_ini.SC_NbPlaneSpawn and not flight2[x].player then											-- si le nb de spawn depasse la limite, il spawn onAir
												SpawnOn( "air", waypoints, group, Pn)
											end
										end 
										-- seqT = seqT + 1
										seqT = seqT + flight2[x].number
									end
								end

								if flight[f].player or flight[f].client2  then																				-- reserve le creneau H-150s au package du joueur
									spawn_time = mission_ini.startup_time_player - (NbFlightPlayer * mission_ini.CVN_TimeBtwPlane)							-- reserve le creneau H-150s au package du joueur --spawn_time = mission_ini.startup_time_player -150
									activG_spawn_time = 1																									-- le joueur spawn en premier (group active)
								end
								
								--les Planes qui genent le taxiing spawn selon conf_mod
								if not SpawnDeck then 
									SpawnOn( mission_ini.SC_SpawnOn[flight[f].type], waypoints, group, Pn)
								end
							
							elseif group['route']['points'][1]["ETA"] <= mission_ini.startup_time_player + 600 then											-- Gère le spawn des groupes au début de mission
								NbFlightDeck = NbFlightDeck + flight[f].number
								if NbFlightDeck >= mission_ini.SC_NbPlaneSpawn and flight[f].player ~= true and flight[f].client2 ~= true  then				-- on ne dépasse pas le nb max de spawn sur le CVN 
									SpawnOn( "air", waypoints, group, Pn)
								end
							
							end
							
							group['lateActivation'] = true										--make group late activation

							if SuperCarrier then 
								group['uncontrolled'] = true
								if( flight[f].player or flight[f].client2 ) then				-- spawn le/s joueurs en Uncontrolled puis apres les activeIA
									aiStart_spawn_time = activG_spawn_time + 1					-- spawn par increment de 1s via seqT
									-- group['uncontrolled'] = true								-- spawn le joueur en uncontrolled pour que les IA démarrent avant lui
								elseif activG_spawn_time == 0 then								-- TOUs les autres IA autres que le package du joueur
									activG_spawn_time = spawn_time								
									aiStart_spawn_time = spawn_time
								else 
									aiStart_spawn_time = spawn_time								-- Pour les AI du Package du Joueur
								end
							else 																-- si on désactive les options du SC, retrouver l'ancien spawn de Mbot, notamment sur Stennis
								activG_spawn_time = spawn_time
								aiStart_spawn_time = spawn_time
							end
							
							--les Planes qui genent le taxiing spawn selon conf_mod
							if not SpawnDeck then 
								SpawnOn( mission_ini.SC_SpawnOn[flight[f].type], waypoints, group, Pn)
							end

							--late activate trigger
							local trig_n = #mission.trig.func + #mission.trig.funcStartup + 1										--next available trigger number
							local func_n = #mission.trig.func + 1 
							mission.trig.func[func_n] = "if mission.trig.conditions[" .. trig_n .. "]() then mission.trig.actions[" .. trig_n .. "]() end"
							mission.trig.flag[trig_n] = true
							mission.trig.conditions[trig_n] = "return(c_time_after(" .. activG_spawn_time .. ") )"
							mission.trig.actions[trig_n] = "a_activate_group(" .. group.groupId .. "); mission.trig.func[" .. trig_n .. "]=nil;"	-- ATO_FP_Debug02 Interceptor error nb trigger
							mission.trigrules[trig_n] = {
								['rules'] = {
									[1] = {
										["seconds"] = activG_spawn_time,
										["coalitionlist"] = "red",
										["predicate"] = "c_time_after",
										["zone"] = "",
									},
								},
								['eventlist'] = '',
								['comment'] = 'Trigger ' .. trig_n,
								['predicate'] = 'triggerOnce',
								['actions'] = {
									[1] = {
										["group"] = group.groupId,
										["predicate"] = "a_activate_group",
										["ai_task"] = 
										{
											[1] = "",
											[2] = "",
										},
									},
								}
							}
							
							
							--triggered action to start uncontrolled group
							group['tasks'] = {
								[1] = {
									["number"] = 1,
									["name"] = group.name,
									["id"] = "WrappedAction",
									["auto"] = false,
									["enabled"] = true,
									["params"] = {
										["action"] = {
											["id"] = "Start",
											["params"] = {},
										},
									},
								},
							}
							
							-- ajoute un trigger start sur les Avion du SC pour qu'ils démarrent vraiment à l'heure, ne concerne que les avions du Pack du joueur
							--mission trigger to initiate triggered action
							local trig_n = #mission.trig.func + #mission.trig.funcStartup + 1										--next available trigger number
							local func_n = #mission.trig.func + 1 
							mission.trig.func[func_n] = "if mission.trig.conditions[" .. trig_n .. "]() then mission.trig.actions[" .. trig_n .. "]() end"
							mission.trig.flag[trig_n] = true
							mission.trig.conditions[trig_n] = "return(c_time_after(" .. aiStart_spawn_time .. ") )"
							mission.trig.actions[trig_n] = "a_set_ai_task(" .. group.groupId .. ", 1); mission.trig.func[" .. trig_n .. "]=nil;"				-- ATO_FP_Debug02 Interceptor error nb trigger
							mission.trigrules[trig_n] = {
								['rules'] = {
									[1] = {
										["seconds"] = aiStart_spawn_time,
										["coalitionlist"] = "red",
										["predicate"] = "c_time_after",
										["zone"] = "",
									},
								},
								['eventlist'] = '',
								['comment'] = 'Trigger ' .. trig_n,
								['predicate'] = 'triggerOnce',
								['actions'] = {
									[1] = {
										["ai_task"] = {
											[1] = "",
											[2] = "",
										},
										["predicate"] = "a_set_ai_task",
										["set_ai_task"] = {
											[1] = group.groupId,
											[2] = 1,
										}
									},
								},
							}
							

						elseif mission_ini.TriggerStart == true  then							--for groups on airbases -- Miguel21 modification M30 	Desactive TriggerStart
							group['uncontrolled'] = true										--make group uncontrolled
							
							waypoints[1].ETA = 0
							
							--triggered action to start uncontrolled group
							group['tasks'] = {
								[1] = {
									["number"] = 1,
									["name"] = group.name,
									["id"] = "WrappedAction",
									["auto"] = false,
									["enabled"] = true,
									["params"] = {
										["action"] = {
											["id"] = "Start",
											["params"] = {},
										},
									},
								},
							}
							
							--mission trigger to initiate triggered action
							local trig_n = #mission.trig.func + #mission.trig.funcStartup + 1										--next available trigger number
							local func_n = #mission.trig.func + 1 
							mission.trig.func[func_n] = "if mission.trig.conditions[" .. trig_n .. "]() then mission.trig.actions[" .. trig_n .. "]() end"
							mission.trig.flag[trig_n] = true
							mission.trig.conditions[trig_n] = "return(c_time_after(" .. spawn_time .. ") )"
							mission.trig.actions[trig_n] = "a_set_ai_task(" .. group.groupId .. ", 1); mission.trig.func[" .. trig_n .. "]=nil;"				-- ATO_FP_Debug02 Interceptor error nb trigger
							mission.trigrules[trig_n] = {
								['rules'] = {
									[1] = {
										["seconds"] = spawn_time,
										["coalitionlist"] = "red",
										["predicate"] = "c_time_after",
										["zone"] = "",
									},
								},
								['eventlist'] = '',
								['comment'] = 'Trigger ' .. trig_n,
								['predicate'] = 'triggerOnce',
								['actions'] = {
									[1] = {
										["ai_task"] = {
											[1] = "",
											[2] = "",
										},
										["predicate"] = "a_set_ai_task",
										["set_ai_task"] = {
											[1] = group.groupId,
											[2] = 1,
										}
									},
								},
							}
						elseif mission_ini.TriggerStart	== false then							--for groups on airbases -- Miguel21 modification M30.b 	Desactive TriggerStart
							
							group.start_time = spawn_time -1
							waypoints[1].ETA = spawn_time
							
							
						end
					end
				
					group['route']['points'][1]["ETA"] = 0										--first waypoint ETA is 0 for uncontrolled group to spawn at mission start
				
				end

				----- provisions for interceptors/GCI/AWACS -----
				if flight[f].task == "Intercept" and flight[f].player ~= true  then				--and flight[f].client2 ~= true
					
					GCI.Flag = GCI.Flag + 1														--go to next trigger flag number
					
					if flight[f].client2 ~= true then											-- M11 PVP ne copie pas de trigger retardé START pour les clients/joueurs	
						if db_airbases[flight[f].base].unitname then								--for groups on aircraft carriers
							group['lateActivation'] = true											--make group late activation
							
							--les Planes qui genent le taxiing spawn selon conf_mod
							SpawnOn("air", waypoints, group, Pn)
						end																		--for groups on airbases
							group['uncontrolled'] = true											--make interceptor groups uncontrolled at mission start

							--triggered action to start uncontrolled group
							group['tasks'] = {
								[1] = {
									["number"] = 1,
									["name"] = group.name,
									["id"] = "WrappedAction",
									["auto"] = false,
									["enabled"] = true,
									["params"] = {
										["action"] = {
											["id"] = "Start",
											["params"] = {},
										},
									},
								},
							}
						
						--mission trigger to initiate triggered action
						local trig_n = #mission.trig.func + #mission.trig.funcStartup + 1										--next available trigger number
						local func_n = #mission.trig.func + 1 
						mission.trig.func[func_n] = "if mission.trig.conditions[" .. trig_n .. "]() then mission.trig.actions[" .. trig_n .. "]() end"
						mission.trig.flag[trig_n] = true
						mission.trig.conditions[trig_n] = "return(c_flag_is_true(" .. GCI.Flag .. ") )"
						mission.trig.actions[trig_n] = "a_set_ai_task(" .. group.groupId .. ", 1); mission.trig.func[" .. trig_n .. "]=nil;"
						mission.trigrules[trig_n] = {
							['rules'] = {
								[1] = {
									["flag"] = GCI.Flag,
									["coalitionlist"] = "red",
									["predicate"] = "c_flag_is_true",
									["zone"] = "",
								},
							},
							['eventlist'] = '',
							['comment'] = 'Trigger ' .. trig_n,
							['predicate'] = 'triggerOnce',
							['actions'] = {
								[1] = {
									["ai_task"] = {
										[1] = "",
										[2] = "",
									},
									["predicate"] = "a_set_ai_task",
									["set_ai_task"] = {
										[1] = group.groupId,
										[2] = 1,
									}
								},
							},
						}
						if db_airbases[flight[f].base].unitname then							--if the group is on a carrier, it gets late activation instead of uncontrolled. An activate trigger is needed instead of AI task trigger.
							mission.trig.actions[trig_n] = "a_activate_group(" .. group.groupId .. "); mission.trig.func[" .. trig_n .. "]=nil;"
							mission.trigrules[trig_n]['actions'][1] = {
								["group"] = group.groupId,
								["predicate"] = "a_activate_group",
								["ai_task"] = 
								{
									[1] = "",
									[2] = "",
								},
							}
						end
					end
					
					
					
					--build Interceptor table
					local t = {
						name = group.name,
						number = #group.units,
						range = flight[f].target.radius,
						x = group.x,
						y = group.y,
						flag = GCI.Flag,
						tot_from = flight[f].tot_from,
						tot_to = flight[f].tot_to,
						airdromeId = flight[f].airdromeId,
						time = -900
					}
					
					if GCI.Interceptor[side].base[flight[f].base] == nil then
						GCI.Interceptor[side].base[flight[f].base] = {
							ready30 = {},
							ready15 = {},
							ready15_n = 0,
							ready = {},
							ready_n = 0,
						}
					end
					
					if flight[f].player == true or flight[f].client2 == true then										-- M11 multiplayer, les joueurs sont ajouté dans la base ready pour ne pas attendre 
						table.insert(GCI.Interceptor[side].base[flight[f].base].ready, t)
						GCI.Interceptor[side].base[flight[f].base].ready_n = GCI.Interceptor[side].base[flight[f].base].ready_n + 1
					elseif #GCI.Interceptor[side].base[flight[f].base].ready == #GCI.Interceptor[side].base[flight[f].base].ready15 and #GCI.Interceptor[side].base[flight[f].base].ready == #GCI.Interceptor[side].base[flight[f].base].ready30 then
						table.insert(GCI.Interceptor[side].base[flight[f].base].ready, t)
						GCI.Interceptor[side].base[flight[f].base].ready_n = GCI.Interceptor[side].base[flight[f].base].ready_n + 1
					elseif #GCI.Interceptor[side].base[flight[f].base].ready15 == #GCI.Interceptor[side].base[flight[f].base].ready30 then
						table.insert(GCI.Interceptor[side].base[flight[f].base].ready15, t)
						GCI.Interceptor[side].base[flight[f].base].ready15_n = GCI.Interceptor[side].base[flight[f].base].ready15_n + 1
					else
						table.insert(GCI.Interceptor[side].base[flight[f].base].ready30, t)
					end
					
					
				elseif flight[f].task == "AWACS" then
					GCI.EWR[side][units[1].name] = true											--add AWACS to EWR table
				end
				

				-- si multijoueur, les Flight AI commencent en vol + M11.j
				-- M37 si E3 et A6 aussi, meme en singlePlay
				if ((flight[f].type == 'F-14B' or flight[f].type == 'FA-18C_hornet') 	and coopFlag01	and flight[f].player ~= true and flight[f].client2 ~= true 
				and string.find(flight[f].base,"CVN") and flight[f].task ~= "Intercept") then
					
					if  waypoints[1]["type"] ~= "Turning Point" then 					-- si le vol � d�j� �t� "d�plac�" pour un commencement en vol, on ne recommence pas le d�calage lat�ral
						SpawnOn("air", waypoints, group, Pn)
					end
				elseif (flight[f].type == 'F-14B' or flight[f].type == 'FA-18C_hornet') 	and flight[f].client2 == true 
					and string.find(flight[f].base,"CVN") and flight[f].task ~= "Intercept" then
					
					if not waypoints[1]['linkUnit'] then waypoints[1]['linkUnit'] = waypoints[#waypoints]['linkUnit'] end
					if not waypoints[1]['helipadId'] then waypoints[1]['helipadId'] = waypoints[#waypoints]['helipadId'] end
					
				end

				-- modification Miguel M17
				-- Player Flight : SinglePlayer, si 4 F-14, on le force � moins de 4 pour �viter les collisions
				if flight[f].type == 'F-14B'  and flight[f].player == true and flight[f].number > limiteNbF14CVN  and string.find(flight[f].base,"CVN") then
					for nb = flight[f].number ,limiteNbF14CVN +1, -1 do
						table.remove(units, nb)
					end
					flight[f].number = limiteNbF14CVN
				end


						
				if db_airbases[flight[f].base].unitname and waypoints[1]["type"] ~= "Turning Point" then	-- and waypoints[1]["type"] ~= "Turning Point"
					-- initie et place dans la table placePA les horaires "esperées" de catapultage
					if not placePA[side] then placePA[side] = {} end
					if not placePA[side][flight[f].base] then placePA[side][flight[f].base] = {} end
					local EPlayer = "."
					if	flight[f].player == true then EPlayer = " - Player" end
					local etiquette = "Pack " .. p .. " - "..flight[f].number.." "..flight[f].type.. " - " .. flight[f].name .." - " .. flight[f].task .." ".. f.. EPlayer
					
					local testST =  spawn_time
					if not testST then testST = 0 end
					
					--todo fini l'ordre de décollage sur cata
					repeat
						testST = testST + 60 
					until not placePA[side][flight[f].base][testST] 
					
					placePA[side][flight[f].base][testST] = etiquette
				end
				


				if flight[f].player == true  then												--if this is the player flight
					if coop == 1 then
						units[1]["skill"] = "Player"											--make first aircraft in flight the player aircraft
						packagePlayer = p
						if coopFlag01 then
							units[1]["skill"] = "Client"
							MultiPlayerFlight1 = true
							packagePlayer = p
						end
					elseif coop == 2 then
						units[1]["skill"] = "Client"
						units[2]["skill"] = "Client"
						MultiPlayerFlight1 = true
						packagePlayer = p
					elseif coop == 3 then
						units[1]["skill"] = "Client"
						units[2]["skill"] = "Client"
						units[3]["skill"] = "Client"
						MultiPlayerFlight1 = true
						packagePlayer = p
					elseif coop == 4 then
						units[1]["skill"] = "Client"
						units[2]["skill"] = "Client"
						units[3]["skill"] = "Client"
						units[4]["skill"] = "Client"
						MultiPlayerFlight1 = true
						packagePlayer = p
					end
				-- Miguel21 modification M11 : Multiplayer
				elseif flight[f].client2   then													-- si le type d'avion N�2 
					MultiPlayerFlight2 = true
						-- waypoints[1].ETA = 0													-- Place l'heure d'apparition au lancement de mission, pour avoir plus de temps...^^	
						waypoints[1]["type"] = "TakeOffParking"
						waypoints[1]["action"] = "From Parking Area"
					if coop_flight2 == 1 then
						units[1]["skill"] = "Client"
					elseif coop_flight2 == 2 then
						units[1]["skill"] = "Client"
						units[2]["skill"] = "Client"
					elseif coop_flight2 == 3 then
						units[1]["skill"] = "Client"
						units[2]["skill"] = "Client"
						units[3]["skill"] = "Client"
					elseif coop_flight2 == 4 then
						units[1]["skill"] = "Client"
						units[2]["skill"] = "Client"
						units[3]["skill"] = "Client"
						units[4]["skill"] = "Client"
					end
				end
				
				if type(units[1].callsign) == "number" then										--Russian style
					ATO[side][p][role][f].callsign = units[1].callsign							--store flight callsign in ATO
				else																			--NATO style
					ATO[side][p][role][f].callsign = units[1].callsign.name						--store flight callsign in ATO									
				end
				
				ATO[side][p][role][f].frequency = group.frequency								--store package frequency in ATO
				
				------ add group to mission -----
				for c = 1, #mission.coalition[side].country do
					if mission.coalition[side].country[c].name == flight[f].country then
						if flight[f].helicopter ~= true then
							if mission.coalition[side].country[c].plane == nil then
								mission.coalition[side].country[c].plane = {
									group = {}
								}
							end
							table.insert(mission.coalition[side].country[c].plane.group, group)
							if flight[f].player == true then										
								camp.player.group = mission.coalition[side].country[c].plane.group[#mission.coalition[side].country[c].plane.group]		--store a link to the player group in mission
							-- Miguel21 modification M11B. : Multiplayer--briefing	
							elseif flight[f].client2 == true then										
								camp.player2.group = mission.coalition[side].country[c].plane.group[#mission.coalition[side].country[c].plane.group]		--store a link to the player group in mission
							end
						else
							if mission.coalition[side].country[c].helicopter == nil then
								mission.coalition[side].country[c].helicopter = {
									group = {}
								}
							end
							table.insert(mission.coalition[side].country[c].helicopter.group, group)
							if flight[f].player == true then										
								camp.player.group = mission.coalition[side].country[c].helicopter.group[#mission.coalition[side].country[c].helicopter.group]		--store a link to the player group in mission
							end
						end
					end
				end

				if Debug.AfficheFlight then 
					idSol = "SolRIEN"
					local ETA = -1
					local NbEta = "ETA "
					local WT = ""

					if spawn_time ~= nil then
						ETA = spawn_time
					end
					
					local info01 = ""
					if waypoints[1].action then
						info01 = "info01 "..waypoints[1].alt
					end
					
					if flight[f].loadout.weaponType then
						WT = flight[f].loadout.weaponType
					end
					

				  io.write("Pack: "..p.." Nb "
						.."  "..flight[f].number
						.."  "..flight[f].type
						.."  "..group.name
						.."  "..WT
						.."  "..flight[f].target_name					
						.."  "..NbEta.. math.floor(ETA)
						.."  ".." // "..units[1].skill
						-- .."  ".." // "..group.frequency
						
						-- .." UAlt ".." // "..units[1].alt
						-- .." WAlt ".." // "..info01
						
						-- .."  ".." TSpawn "..tostring(activG_spawn_time)
						
						-- .."  ".." TaiStart "..tostring(aiStart_spawn_time)
						)
						
					-- for nn = 2 , #units do
						-- if units[nn].payload.gun  then								
							-- _gun = units[nn].payload.gun
						-- end
						-- io.write(" / ".. units[nn].skill.." /Gun ".._gun )
					-- end
					
					io.write("  "..waypoints[1].action)
					
					io.write("\n")
				end
			end
		end
	end
end

-- affiche  le timing des avions sur le pont/catapulte pour prévenir le/les joueurs que des IA seront dessus
-- _affiche(placePA, "PAsse03")
local tabNam = {}	
print("\n")
if placePA and camp.player then
	for side , pPA in pairs(placePA) do	
		if camp.player.side == side then
			for base , Tmn in pairs(pPA) do	
				print(tostring(base).." Takeoff time on the platform at ...")
				for s, name in pairsByKeys(Tmn) do
					
					if tabNam[name] ~= true then
						catTime = camp.time + s
						io.write(" "..FormatTime(catTime, "hh:mm").. " - "..tostring(name).."\n")
						tabNam[name] = true
					end
				end
			end
		end
	end
end

----- make a copy of player package for easy reference in briefing -----
local breakloop = false
if camp.player then
	camp.player.pack = deepcopy(ATO[camp.player.side][camp.player.pack_n])
	
	--for multi-package strikes, add flights from other packages with the same target to player package to enrich the briefiing
	for p = 1, #ATO[camp.player.side] do										--iterate through packages in player side	
		for role,flight in pairs(ATO[camp.player.side][p]) do					--iterate through roles in package (main, SEAD, escort)		
			for f = 1, #flight do												--iterate through flights in roles
				
				if flight[f].target_name == camp.player.target.TitleName and camp.player.pack_n ~= p then	--flights that have the same target as player but are not in the player package
					table.insert(camp.player.pack[role], deepcopy(flight[f]))							--insert flight into player package to list it in player briefing
				end	
				if flight[f].player or flight[f].client2 then
					-- Miguel21 modification M33.b 	Custom Briefing (onBoardNum)
					if flight[f].target_name == camp.player.target.TitleName and camp.player.pack_n == p and not breakloop then
						for _side,side in pairs(mission.coalition) do	
							for _country,country in pairs(side.country) do
								if country.plane and _side == camp.player.side then
									for Ngroup,group in pairs(country.plane.group) do
										if group.units and ( group.units[1].skill == "Player" or group.units[1].skill == "Client" ) then
											camp.player.pack[role][f].units = group.units
											breakloop = true
										end
									end
								end
							end
						end
					end
				end
			
			end
		end
	end
end


-- Miguel21 modification M11B. : Multiplayer--briefing	
if camp.player2 then
	camp.player2.pack = deepcopy(ATO[camp.player2.side][camp.player2.pack_n])
end