--To create the Air Tasking Order
--Initiated by Main_NextMission.lua
------------------------------------------------------------------------------------------------------- 
-- last modification:  adjustment_s
if not versionDCE then versionDCE = {} end
versionDCE["ATO_Generator.lua"] = "1.18.111"
------------------------------------------------------------------------------------------------------- 
-- cleanCode_c
-- adjustment_t							(minscore)(s tasks table)(op ne donne pas tout en CAP)(o info loadout)(N ne donne pas tout en CAP)(lM: MP) (ghi:donne une alti aléatoire) (f:altitude en fonction diff entre role)(e: random loadout temp)(cd:support équitable entre escadron)(b: TASK Coef)(a: escort mandatory or not)
-- Debug_k								(k too tanker&Awacs)(jk number entre 0 et1)(i info2000)(h:reecriture loadout_eligible) (f:interdit l'escorte avion/helico)(de:correction targetName)(c: mauvaise insertion dans la base)(b: haut score)(a: Fin de campagne)
-- Miguel21 modification M61_a			SAR
-- miguel21 modification M56_b			AssignCallnameSquad (b: callsignId)
-- miguel21 modification M49_c			big central db_loadout (c: loadout statistics)
-- miguel21 modification M43			assignation des numeros de parking du type C08 
-- miguel21 modification M42			liveryModex
-- miguel21 modification M38_t			Check and Help CampaignMaker (t debug/debugGenerator)(r +)(o _affiche) (e: loadout Task?)
-- Miguel21 modification M16_b			SpawnAir B1b & B-52 need BaseAirStart = true in db_aibase
-- Modif Miguel21 M13_e					Performance Scripting
-- Miguel21 modification M11A_bj		Multiplayer	(bj same target)(bi bug CAP)(bb: rapport entre escorte et cap)(wxy: force same package)(z: debug MP avec 1 Plane)(y: interdit l'escorte avion/helico) (x: EscorteTot-max) (w: choix EscorteMax) (v: interdit Strike sans escorte)(u: reserve avion Escorte) (t: different Type possible/task)
-- Miguel21 modification M06			helicopter playable
------------------------------------------------------------------------------------------------------- 	

local _debugGlobal = false

altiHelicoMap = {}
local denom_NeDonnePasTOUT = 2		--nb, coef, dénominateur pour ne pas donner tous les chasseurs à l'escorte, en garder pour les intercepteur/cap
--plus le chiffre est petit, plus il y a d'intercepteur (exemple: 2)

-- ne donne pas tout aux Strike:
local testCode = false	-- false: petite campagne comme Tchad/ true: grande campagne

if not debuGenTxt or debuGenTxt == nil or debuGenTxt =="" then
	debuGenTxt =""
end
for mapName, map in pairs(altiHelico) do	
	if mapName == "caucasus" then
		for PolyN = 1, #map do

			-- ["mapY"] = 772022.39729703
			-- ["mapX"] = 772022.39729703

			for pointN, point in ipairs(map[PolyN].points) do
				
				-- if not altiHelicoMap["caucasus"] then altiHelicoMap["caucasus"] = {} end
				if not altiHelicoMap[PolyN] then altiHelicoMap[PolyN] = {} end

				altiHelicoMap[PolyN][pointN] = {
					x = point.x + map[PolyN].mapX,
					y = point.y + map[PolyN].mapY,
				}


			end
		end
	end
end

-- local camp_str = "altiHelicoMap = " .. TableSerialization(altiHelicoMap, 0)						--make a string
-- local campFile = io.open("Debug/altiHelicoMap_AtoG.lua", "w")										--open targetlist file
-- campFile:write(camp_str)																		--save new data
-- campFile:close()

totalPlanePerTask = {
	red = {},
	blue = {},
	neutral = {},
}

require("Debug/db_loadouts_archive")
local error = 0
for side, unit in pairs(oob_air) do																								--iterate through all sides	
-- db_loadouts = {
	-- ["AV8BNA"] = {
		-- ["Anti-ship Strike"] = {

	for n = 1, #unit do	
		if type(unit[n].tasks) == "table" then		
			for task,task_bool in pairs(unit[n].tasks) do			
				if task_bool then			
					if db_loadouts[unit[n].type] then	
										
						if db_loadouts[unit[n].type][task] then
							--creation table du nombre d'avion dispo pour une task
							if   unit[n].roster and unit[n].roster.ready then
								if not totalPlanePerTask[side][task] then totalPlanePerTask[side][task] = 0 end	
								totalPlanePerTask[side][task] = totalPlanePerTask[side][task] +	unit[n].roster.ready	
							end		
						else
							print("AtoG error: "..unit[n].type.." "..task.." not found in db_loadouts")
							os.execute 'pause'
							error = error + 1
						end
						
					else
						print("AtoG error: "..unit[n].type.." not found in db_loadouts")
						os.execute 'pause'
						error = error + 1
					end
				end
			end
		end
	end
end

if error > 5 then
	if string.lower(mission_ini.SelectLoadout) == "init" then

	else
		print()
		print("================================================ATTENTION====================================================")
		print("AtoG error: ".." With so many errors using the Central loadout, there may be a custom loadout in the /Init folder \n "
		.."To do this, set the \"SelectLoadout\" variable to \"init\" in the conf_mod")
		os.execute 'pause'
	end
end

-- local camp_str = "db_loadouts = " .. TableSerialization(db_loadouts, 0)						--make a string
-- local campFile = io.open("Debug/AtoG_db_loadouts.lua", "w")								--open targetlist file
-- campFile:write(camp_str)															--save new data
-- campFile:close()

function round(num)
local dec = 2
  local mult = 10^(dec or 0)
  return math.floor(num * mult + 0.5) / mult
end

--status report counters
local status_counter_sorties = 0
local status_counter_escorts = 0
local status_counter_ATO = 0


--to track what caused lack of playable sortie for the player
playability_criterium = {}
function TrackPlayability(player_unit, criterium)																				--function that tracks whether a playability criterium has been met
	if player_unit == true then																									--unit in question is playable by player
		playability_criterium[criterium] = true																					--set playability criterium to be met
	end
end

--table to hold availability of aircraft
if camp.aircraft_availability == nil then
	camp.aircraft_availability = {}
end
aircraft_availability = camp.aircraft_availability																				--link to table for easier reference

--table to store draft sorties (all valid unit/task/loadout/target combinations)
draft_sorties = {
	blue = {},
	red = {}
}

-- if not multiPlaneSet then
	multiPlaneSet = {}

	for k=1, Multi.NbGroup do
		--TODO beurk, à refaire ça propre
		if not multiPlaneSet[Multi.Group[k].side] then multiPlaneSet[Multi.Group[k].side] = {} end
		if not multiPlaneSet[Multi.Group[k].side][Multi.Group[k].PlaneType] then multiPlaneSet[Multi.Group[k].side][Multi.Group[k].PlaneType] = {} end	
		-- multiPlaneSet[Multi.Group[k].PlaneType][Multi.Group[k].task] = true
		
		if not multiPlaneSet[Multi.Group[k].side][Multi.Group[k].PlaneType][Multi.Group[k].task] then multiPlaneSet[Multi.Group[k].side][Multi.Group[k].PlaneType][Multi.Group[k].task] = {} end
		if not multiPlaneSet[Multi.Group[k].side][Multi.Group[k].PlaneType][Multi.Group[k].task]["NbPlane"] then multiPlaneSet[Multi.Group[k].side][Multi.Group[k].PlaneType][Multi.Group[k].task]["NbPlane"] = 0 end
		
		multiPlaneSet[Multi.Group[k].side][Multi.Group[k].PlaneType][Multi.Group[k].task].NbPlane = Multi.Group[k].NbPlane + multiPlaneSet[Multi.Group[k].side][Multi.Group[k].PlaneType][Multi.Group[k].task].NbPlane
		multiPlaneSet[Multi.Group[k].side][Multi.Group[k].PlaneType][Multi.Group[k].task].InitNbPlaneByTask =  multiPlaneSet[Multi.Group[k].side][Multi.Group[k].PlaneType][Multi.Group[k].task].NbPlane
		
		if not multiPlaneSet[Multi.Group[k].side][Multi.Group[k].PlaneType].InitNbPlane then multiPlaneSet[Multi.Group[k].side][Multi.Group[k].PlaneType].InitNbPlane = 0 end
			   multiPlaneSet[Multi.Group[k].side][Multi.Group[k].PlaneType].InitNbPlane = multiPlaneSet[Multi.Group[k].side][Multi.Group[k].PlaneType].InitNbPlane + Multi.Group[k].NbPlane
	end
-- end

if Debug.Generator.affiche then
	_affiche(Multi, "ATO_G Multi")
	_affiche(multiPlaneSet, "ATO_G multiPlaneSet B")
	-- os.execute 'pause'
end


--creat draft sorties
for side,unit in pairs(oob_air) do																								--iterate through all sides
	
	--determine enemy side
	local enemy																													--determine enemy side (opposite of unit side)
	if side == "blue" then
		enemy = "red"
	else
		enemy = "blue"
	end
	local draftId = 1
	if Debug.Generator.affiche then
		debuGenTxt = debuGenTxt.."\n\n"..("AtoG passe A_0 chapter: "..Debug.Generator.chapter.." SpySquad:  "..Debug.Generator.SpySquad.." SpyTask: "..Debug.Generator.SpyTask) 
		if Debug.Generator.SpyTarget then
			debuGenTxt = debuGenTxt.."\n\n"..Debug.Generator.SpyTarget
		end
	end

	for n = 1, #unit do																											--iterate through all units
		if unit[n].inactive ~= true then																						--if unit is active
			-- print("AtoG "..n.." unit of "..#unit)
			local ClientPlayer = false
			if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
			and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  
			or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
			then
				debuGenTxt = debuGenTxt.."\n\n"..("AtoG passe A_00 "..unit[n].type.." Befor Airbase Condition  ")  
			end			

			TrackPlayability(unit[n].player, "active_unit")																		--track playabilty criterium has been met

			if db_airbases[unit[n].base] and db_airbases[unit[n].base].inactive ~= true and db_airbases[unit[n].base].x and db_airbases[unit[n].base].y then	--base exists and is active and has a position value (carrier that exists)
				if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
				and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  
				or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
				then
					debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_01 "..unit[n].type.." Befor roster.ready Condition  ") 
				end
				TrackPlayability(unit[n].player, "base")																		--track playabilty criterium has been met
				
				
				local overRideReady = false
				if multiPlaneSet and  multiPlaneSet[side] and  multiPlaneSet[side][unit[n].type] then
					if unit[n].roster.ready < multiPlaneSet[side][unit[n].type].InitNbPlane then
						unit[n].roster.ready = multiPlaneSet[side][unit[n].type].InitNbPlane + 1
					end
					overRideReady = true
				end

				if Multi.NbGroup == 0 then
					ClientPlayer = unit[n].player
					-- if ClientPlayer then			print("AtoG passe Ia  ClientPlayer "..tostring(ClientPlayer)) end
				end
				-- if overRideReady or unit[n].roster.ready > 0 then																				--has ready aircraft
				if unit[n].roster.ready > 0 then
					if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
					and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  
					or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
					then
						debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_02 "..unit[n].type.." Befor aircraft_available Condition")  
					end
					
					if Multi and Multi.Group then
						for k=1, #Multi.Group do
							if Multi.Group[k].PlaneType == unit[n].type then
								print("AtoG type: "..unit[n].type.." rosterReady: "..unit[n].roster.ready)
							end 
						end
					end

					TrackPlayability(unit[n].player, "ready_aircraft")															--track playabilty criterium has been met
					
					if aircraft_availability[unit[n].name] == nil then															--unit has no aircraft availability entry yet
						aircraft_availability[unit[n].name] = {}																--make an aircraft availability entry for this unit
					end
					
					if aircraft_availability[unit[n].name].unavailable == nil then												--unit has no unavailable table yet
						if unit[n].unavailable then																				--there are preset unavailabilities in oob_air
							aircraft_availability[unit[n].name].unavailable = unit[n].unavailable								--use this as initial unavailability
						else
							aircraft_availability[unit[n].name].unavailable = {}												--create an empty unavailable table
						end
					end

						
					--serviceable aircraft
					local aircraft_serviceable = 0																				--serviceable aircraft of unit
					local serviceability = 0.8																					--defaults unit serviceability rating
					if unit[n].serviceability then																				--if serviceability for unit is defined
						serviceability = unit[n].serviceability																	--use it instead
					end
					for s = 1, unit[n].roster.ready do																			--iterate through ready aircraft
						if math.random(1, 100) <= serviceability * 100 then														--default 80% chance that it is mission ready
							aircraft_serviceable = aircraft_serviceable + 1														--sum serviceable aircraft
						end
					end
					aircraft_availability[unit[n].name].ready = unit[n].roster.ready											--store ready aircraft un availability table
					aircraft_availability[unit[n].name].serviceable = aircraft_serviceable										--store serviceable aircraft in availability table
		
					--unavailable aircraft
					local current_time = (camp.day - 1) * 86400 + camp.time														--current absolute campaign time
					local u_entry = 0
					for u = #aircraft_availability[unit[n].name].unavailable, 1, -1 do											--iterate backwards through unavailable aircraft from this unit
						u_entry = u_entry + 1
						if u_entry <= unit[n].roster.ready then																	--for each unavailable entry that is within the amounty of ready aircraft of unit
							if current_time > aircraft_availability[unit[n].name].unavailable[u] then							--check absolute campaign time is past unvailable time for this entry
								table.remove(aircraft_availability[unit[n].name].unavailable, u)								--remove this entry
							end
						else																									--for each unavailable entry that is beyond the amount of ready aircraft of unit (due to losses in last mission)
							table.remove(aircraft_availability[unit[n].name].unavailable, u)									--remove this entry
						end
					end
		
					local aircraft_available = unit[n].roster.ready - #aircraft_availability[unit[n].name].unavailable			--number of available aircraft
					if aircraft_serviceable < aircraft_available then
						aircraft_available = aircraft_serviceable
					end
					aircraft_availability[unit[n].name].available = aircraft_available											--store available aircraft in availability table
					aircraft_availability[unit[n].name].assigned = 0
					aircraft_availability[unit[n].name].unassigned = aircraft_available											--store unassigned aircraft in availability table

					
					if aircraft_available > 0 then																				--unit has available aircraft
						if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
						and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  
						or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
						then
							debuGenTxt = debuGenTxt.."\n\n"..("AtoG passe A_03 ".." Befor tasks Boucle")  
						end
						TrackPlayability(unit[n].player, "available_aircraft")													--track playabilty criterium has been met
						
						for task,task_bool in pairs(unit[n].tasks) do																		--iterate through all tasks of unit		
							-- local ClientPlayer = false
							if task_bool and task ~= "SEAD" and task ~= "Escort" and task ~= "Escort Jammer" and task ~= "Flare Illumination" and task ~= "Laser Illumination" then		--task is true and is no support task
								
								-- print("     AtoG "..unit[n].type.." task "..task)

								if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
								and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
								or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
								then
									debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_04 "..unit[n].type.." Befor task Condition") 
								end
								--get possible loadouts
								local unit_loadouts = {}																					--table to hold all loadouts for this aircraft type and task
								
								if db_loadouts[unit[n].type][task] then																		--db_loadouts table has loadouts for this task
									
									for loadout_name, ltable in pairs(db_loadouts[unit[n].type][task]) do									--iterate through all loadouts for the aircraft type and task
										if ltable.country == nil or ltable.country == unit[n].country then									--loadout is country unspecific or applies to unit country
											ltable.name = loadout_name																		--store loadout name
											-- table.insert(unit_loadouts, ltable)																--add loadout to local table
											
											ltable["hCruiseREF"] = ltable.hCruise
											ltable["hAttackREF"] = ltable.hAttack
											
											--ceci est un anti PBO_Corse66 ^^
											-- donne une alti aléatoire pour éviter de connaitre le type d'avion pas l'altitude habituellement utilisée
											if ltable.hCruise and ltable.hCruise > 2000 then
												local altiRandom = 0
												local RandomChance = math.random(0,100)
												
												if RandomChance < 50 then										--20% de chance d'avoir une alti de 1000 à 2000m de difference 
													altiRandom = math.random(100 ,200)
													
												elseif RandomChance < 70 then									--30% de chance d'avoir une alti de 1000m de difference
													altiRandom = math.random(0,100)
												end																--50% de chance d'avoir une alti de 0 de difference
												
												altiRandom = altiRandom *10 * (math.random(0, 1)*2-1)			--choisi si c'est une diff positive ou negative												
												ltable.hCruise = ltable.hCruise + altiRandom												
												if ltable.hCruise < 300 then 
													ltable.hCruise = 300													
												end												
												
												
												if ltable.hAttack then
													ltable.hAttack = ltable.hAttack + (altiRandom /2) 
													if ltable.hAttack < 300 then 
														ltable.hAttack = 300														
													end
												end
											end


											--ajoute une task obligatoire en fonction du learning des missions précédentes
											if camp.newTaskRequest then
												for rSide, rSides in pairs(camp.newTaskRequest) do
													if rSide == side then
														for rTypeName, rTypes in pairs(rSides) do
															if rTypeName == unit[n].type then
																for rTaskEnCours, rNewTasks in pairs(rTypes) do
																	if rTaskEnCours == task then
																		for rNewTask, value in pairs(rNewTasks) do
																			if value then
																				if not ltable.support then ltable.support = {} end
																				ltable.support[rNewTask] = true

																				-- print("AtoG passe Integration newTaskRequest "..rTypeName.." "..rTaskEnCours)
																				-- _affiche(ltable, "ltable")

																			end
																		end
																	end
																end
															end
														end
													end
												end
											end
	

											unit_loadouts[#unit_loadouts+1] = ltable 										
											unit_loadouts[#unit_loadouts]["loadout_name"] = loadout_name											
										end
									end
								end
								
								-- ATO_G_adjustment.e (e: random loadout temp)
								--mix the list of available loadouts so that you don't always have the same ones 
								--https://programming-idioms.org/idiom/10/shuffle-a-list/1313/lua
								for i = #unit_loadouts, 2, -1 do
									local j = math.random(i)
									unit_loadouts[i], unit_loadouts[j] = unit_loadouts[j], unit_loadouts[i]
								end
								
								for l = 1, #unit_loadouts do																				--iterate through all available loadouts				
									
									-- print("          AtoG Nloadout: "..l.." of ".. #unit_loadouts)
									
									if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
									and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
									or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
									then
										debuGenTxt = debuGenTxt.."\n\n"..("AtoG passe A_05 "..unit[n].type.." "..unit_loadouts[l].loadout_name.." Befor Loadouts Day/Night Condition") 
									end
									--get possible Time on Target
									local tot_from = 0																						--earliest Time on Target for this loadout
									local tot_to = 0																						--latest Time on target for this loadout
									-- local tot_to =camp.mission_duration
									if unit_loadouts[l].day and unit_loadouts[l].night then													--loadout is day and night capable
										tot_from = 0																						--from mission start
										tot_to = camp.mission_duration																		--to mission end
										if task == "Intercept" or task == "SAR" then																			--for interceptors, tot_to is not limitted by mission duration
											tot_to = 999999
										end
									elseif unit_loadouts[l].day then																		--loadout is day capable
										if daytime == "night-day" then
											tot_from = camp.dawn - camp.time																--from dawn
											tot_to = camp.mission_duration																	--to mission end
											if task == "Intercept" or task == "SAR" then																		--for interceptors, tot_to is not limitted by mission duration
												tot_to = camp.dusk - camp.time
											end
										elseif daytime == "day" then
											tot_from = 0																					--from missiom start
											tot_to = camp.mission_duration																	--to mission end
											if task == "Intercept" or task == "SAR" then																		--for interceptors, tot_to is not limitted by mission duration
												tot_to = camp.dusk - camp.time
											end
										elseif daytime == "day-night" then
											tot_from = 0																					--from mission start
											tot_to = camp.dusk - camp.time																	--to dusk
										end
									elseif unit_loadouts[l].night then																		--loadout is night capable
										if daytime == "day-night" then
											tot_from = camp.dusk - camp.time																--from dusk
											tot_to = camp.mission_duration																	--to mission end
											if task == "Intercept" or task == "SAR" then																		--for interceptors, tot_to is not limitted by mission duration
												tot_to = camp.dawn - camp.time
											end
										elseif daytime == "night" then
											tot_from = 0																					--from mission start
											tot_to = camp.mission_duration																	--to mission end
											if task == "Intercept"  or task == "SAR" then																		--for interceptors, tot_to is not limitted by mission duration
												tot_to = camp.dawn - camp.time
											end
										elseif daytime == "night-day" then
											tot_from = 0																					--from mission start
											tot_to = camp.dawn - camp.time																	--to dawn
										end
									end
									
									if tot_to < 0 then
										tot_to = tot_to + 86400
									end
									if tot_from < 0 then
										tot_from = tot_from + 86400
									end
		
									if tot_from ~= 0 or tot_to ~= 0 then																	--loadout has an eligible time on target
										if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
										and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
										or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
										then
											debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_06 ".." Befor targetlist Boucle")
										 end
										
										if tot_from == 0 then																				--player is only allowed to start at mission start
											TrackPlayability(unit[n].player, "tot")															--track playabilty criterium has been met
										end

										i_timmer01 = 0
										for target_side_name, target_side in pairs(targetlist) do											--iterate through sides in targetlist				
											i_timmer01 = i_timmer01 +1
											if side == target_side_name then																--if the target is hostile
												
												local totalTarget = 0
												for target_name, target in pairs(target_side) do
													totalTarget = totalTarget + 1
												end

												local iTarget = 0
												for target_name, target in pairs(target_side) do											--iterate through all hostile targets
													iTarget = iTarget + 1
													-- print("               AtoG Ntarget: "..iTarget.." of "..totalTarget )
													
													if target.inactive ~= true and target.ATO then											--if target is active and should be added to ATO
														if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
														and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
														or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
														then
															debuGenTxt = debuGenTxt.."\n\n"..("AtoG passe A_07 :"..unit[n].type.." "..target_name.." Befor task Condition: "..target.task .." ==? task? "..task.." || "..target_name)
														end

														if target.task == task then															--if target is valid for aircaft-loadout															
															
															--ajoute la task au loadout du main pour que cette task/support devienne obligatoire
															
															-- print("AtoG newTaskPerTarget type"..unit[n].type)
															if camp.newTaskPerTarget then
																for tableTargetName, targetTask in pairs(camp.newTaskPerTarget) do
																	if tableTargetName == target_name and targetTask.tasks then
																		-- print("AtoG tableTargetName"..tableTargetName)

																		for task, value in pairs(targetTask.tasks) do
																			-- print("    AtoG "..task)

																			if not unit_loadouts[l].support then unit_loadouts[l].support = {} end
																			unit_loadouts[l].support[task] = true
																		end
																	end
																end
															end
															
															
															--check target/loadout attributes
															local loadout_eligible = true																					--boolean if loadout matches any target attributes (default true, because target might have no attributes)
															if target.attributes and target.attributes[1] and target.attributes[1] ~= "" then																					--target has attributes
																loadout_eligible = false													
																for target_attribute_number, target_attribute in ipairs(target.attributes) do								--Iterate through target attributes																
																	for loadout_attribute_number, loadout_attribute in ipairs(unit_loadouts[l].attributes) do				--Iterate through loadout attributes												
																		
																		if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
																		and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																		or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
																		then
																			debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_10b Befor loadout_eligible: target_attribute?: "..tostring(target_attribute).." loadout_attribute: "..tostring(loadout_attribute).." || "..target_name)
																		end
																		
																		if target_attribute == loadout_attribute then														--if match is found													
																			loadout_eligible = true																			--set variable true
																			break																							--break the loadout attributes iteration
																		end
																	end
																end
															end
															
															if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
															and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
															or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
															then
																debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_10c Befor Condition loadout_eligible?: "..tostring(loadout_eligible).." || "..target_name)
															end

															if loadout_eligible then	
															--continue if loadout is eligible
																
																if ( (task == "Intercept" and target.base == unit[n].base) or (task == "SAR" and target.base == unit[n].base) ) or (task == "Transport" and target.base == unit[n].base) or (task == "Nothing" and target.base == unit[n].base) or (task ~= "Intercept" and task ~= "Transport" and task ~= "Nothing" and task ~= "SAR") then	--intercept and transport missions are only assigned to units of a certain base as per targetlist	
																	TrackPlayability(unit[n].player, "target")																							--track playabilty criterium has been met
																	if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
																	and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																	or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
																	then
																		debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_11 MultiPlayerOveRide? "..tostring(MultiPlayerOveRide).." Befor firepower Condition".." || "..target_name
																		.." "..unit[n].type
																		.." firepower.min? "..target.firepower.min
																		.." <= aircraft_available: ".. aircraft_available 
																		.." * firepower "..unit_loadouts[l].firepower
																		)
																	end
																	
																	if target.firepower.min <= aircraft_available * unit_loadouts[l].firepower or MultiPlayerOveRide then				--enough aircraft are available to satisfy minimum firepower requirement of target	
																		if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
																		and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																		or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
																		then
																			debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_12  Befor weather Condition || overRideReady: "..tostring(overRideReady).." || "..target_name) 
																		end
																		
																		TrackPlayability(unit[n].player, "target_firepower")																			--track playabilty criterium has been met
																		--check weather
																		local weather_eligible = true
																		if mission.weather["clouds"]["density"] > 8 then																				--overcast clouds
																			if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
																			and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																			or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
																			then
																				debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_13 "..unit_loadouts[l].loadout_name.." After weather Condition "..target_name)
																			 end
																			
																			local cloud_base = mission.weather["clouds"]["base"]
																			local cloud_top = mission.weather["clouds"]["base"] + mission.weather["clouds"]["thickness"]
																			if db_airbases[unit[n].base].elevation + 333 > cloud_base then																--cloud base is less than 1000 ft above airbase elevation
																				if unit_loadouts[l].adverseWeather == false then																		--loadout is not adverse weather capable
																					weather_eligible = false																							--not eligible for this weather
																				end
																			else
																				if unit_loadouts[l].hCruise and unit_loadouts[l].hCruise > cloud_base and unit_loadouts[l].hCruise < cloud_top then			--cruise alt is in the clouds
																					if unit_loadouts[l].adverseWeather == false then																	--loadout is not adverse weather capable
																						weather_eligible = false																						--not eligible for this weather
																					end
																				elseif unit_loadouts[l].hAttack and unit_loadouts[l].hAttack > cloud_base and unit_loadouts[l].hAttack < cloud_top then		--attack alt is in the clouds
																					if unit_loadouts[l].adverseWeather == false then																	--loadout is not adverse weather capable
																						weather_eligible = false																						--not eligible for this weather
																					end
																				end
																				
																				if task == "Strike" or task == "Anti-ship Strike" or task == "Reconnaissance" then										--extra requirement for A-G tasks
																					if unit_loadouts[l].hAttack > cloud_base then																		--attack alt is above cloud base
																						if unit_loadouts[l].adverseWeather == false then																--loadout is not adverse weather capable
																							weather_eligible = false																					--not eligible for this weather
																						end
																					end
																				end	
																			end
																		end
																		if mission.weather["enable_fog"] == true then															--fog
																			if db_airbases[unit[n].base].elevation < mission.weather["fog"]["thickness"] then					--base elevation in fog
																				if mission.weather["fog"]["visibility"] < 5000 then												--less than 5000m visibility
																					if unit_loadouts[l].adverseWeather == false then											--loadout is not adverse weather capable
																						weather_eligible = false																--not eligible for this weather
																					end
																				end
																			end
																		end

																		--selectionne une escadrille CSAR la plus proche de l'EjectedPilot
																		local proxiCSAR = true
																		if task == "CSAR" and target.selectedUnitSAR ~= "" then
																			if unit[n].name ~= target.selectedUnitSAR then
																				proxiCSAR = false
																				if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
																				and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																				or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
																				then
																					debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_13 ".." proxiCSAR "..tostring(proxiCSAR).." ".. unit[n].name.." selectedUnitSAR: "..target.selectedUnitSAR)
																				end
																			end
																		end


																		
																		if (weather_eligible and proxiCSAR) or overRideReady then																				--continue of this loadout is eligible for weather
																			if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
																			and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																			or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
																			then
																				debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_14 ".." After weather_eligible Condition "..target_name)
																			end
																			
																			TrackPlayability(unit[n].player, "weather")															--track playabilty criterium has been met
																			
																			--get airbase position
																			local airbasePoint = {																				--get the x-y coordinates of the airbase where the unit is located
																				x = db_airbases[unit[n].base].x,
																				y = db_airbases[unit[n].base].y,
																				h = db_airbases[unit[n].base].elevation,
																				BaseAirStart = db_airbases[unit[n].base].BaseAirStart
																			}
																			
																			local multipack = 1
																			if target.firepower.packmax and unit_loadouts[l].MaxAttackOffset then								--target has a requirement for multiple packages and loadout is multipack capable (defined maximum attack offset)
																				multipack = target.firepower.packmax															--create draft sorties for this target for the requested amount of packages
																			end
																			
																			for r = 1, multipack do																				--repeat draft sortie generation for the requirement amount of packages (may create different routes each time)
																				if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
																				and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																				or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
																				then
																					debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_15 multipack "..tostring(multipack).." FOR multipack Boucle "..target_name) 
																				end
																				
																				--determine route variants depending on daytime
																				local variant
																				if daytime == "day" then
																					variant = 1
																				elseif daytime == "night" then
																					variant = 2
																				elseif daytime == "night-day" then
																					variant = 3
																				elseif daytime == "day-night" then
																					variant = 4
																				end
																				
																				if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
																				and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																				or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
																				then
																					debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_16 "..tostring(variant).." "..tostring(daytime).." Befor variant Condition "..target_name) 
																				end
																				
																				while variant > 0 do
																					draftId = draftId + 1
																					if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
																					and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																					or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
																					then
																						debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_28 ".." After variant Condition "..target_name) 
																					end
																					
																					i_timmer01 = i_timmer01 +1
																					if i_timmer01 >= 10  then io.write(".") i_timmer01 = 0 end
																					--determine route
																					status_counter_sorties = status_counter_sorties + 1													--status report
																					local route = {}
																					if task == "Intercept" then																			--intercept task only get a stub route
																						route = {
																							[1] = {
																								['y'] = airbasePoint.y,
																								['x'] = airbasePoint.x,
																								['alt'] = 0,
																								['id'] = 'Intercept',
																							},
																							threats = {
																								SEAD_offset = 0,
																								ground_total = 0.5,
																								air_total = 0.5
																							},
																							['lenght'] = target.radius * 2,																--interception task radius *2 because below it is compared with range *2
																						}
																					elseif task == "SAR" then																			--intercept task only get a stub route
																						route = {
																							[1] = {
																								['y'] = airbasePoint.y,
																								['x'] = airbasePoint.x,
																								['alt'] = 0,
																								['id'] = 'SAR',
																							},
																							threats = {
																								SEAD_offset = 0,
																								ground_total = 0.5,
																								air_total = 0.5
																							},
																							['lenght'] = target.radius * 2,																--interception task radius *2 because below it is compared with range *2
																						}
																					else																								--all other tasks than intercept
																						if not airbasePoint.x then print("AtoG No Airbase position "..tostring(unit[n].base)) os.execute 'pause' end
																						if not target.x then print("AtoG No target position "..tostring(target_name)) os.execute 'pause' end
																						local ToTarget = GetDistance(airbasePoint, target)												--direct distance to target
																						
																						if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
																						and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																						or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
																						then
																							debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_28b "..tostring(ToTarget).." || LoadoutUnitRange: "..tostring(unit_loadouts[l].range).." "..tostring(unit_loadouts[l].name))
																							debuGenTxt = debuGenTxt.."\n"..("______________ToTarget "..tostring(ToTarget).." <=? "..tostring(unit_loadouts[l].range))
																							debuGenTxt = debuGenTxt.."\n"..("______________minrange? "..tostring(unit_loadouts[l].minrange))
																							debuGenTxt = debuGenTxt.."\n"..("______________ToTarget * 1.5 "..tostring(ToTarget * 1.5).." >? "..tostring(unit_loadouts[l].minrange))
																							_debugGlobal = true
																						end
																						
																						
																						if ToTarget <= unit_loadouts[l].range and (unit_loadouts[l].minrange == nil or ToTarget * 1.5 > unit_loadouts[l].minrange) then	--basic feasibility check of range before performance intensive route calculations are done
																							if variant == 1 or variant == 4 then
																								-- print("                    AtoG _1_4_route" )
																								route = GetRoute(airbasePoint, target, unit_loadouts[l], enemy, task, "day", r, multipack, unit[n], draftId)			--get the best route to this target at day-- Miguel21 modification M06 : helicopter playable(ajout variable helico pour generer une route )
																								-- print("                    AtoG      route_1_4_" )
																							elseif variant == 2 or variant == 3 then																
																								-- print("                    AtoG _2_3_route" )
																								route = GetRoute(airbasePoint, target, unit_loadouts[l], enemy, task, "night", r, multipack, unit[n])		--get the best route to this target at night-- Miguel21 modification M06 : helicopter playable
																								-- print("                    AtoG      route_2_3_" )
																							end
																						end

																						_debugGlobal = false
																					end
																					
																						
																					local altiPass = true
																					if 	unit_loadouts[l].hHover and target.z and target.z > unit_loadouts[l].hHover 	then
																						altiPass = false
																					end
																					

																					if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
																					and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																					or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
																					then
																						debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_28d ")
																						debuGenTxt = debuGenTxt.."\n"..("______________route.lenght "..tostring(route.lenght).." <=? "..tostring(unit_loadouts[l].range * 2))
																						debuGenTxt = debuGenTxt.."\n"..("______________minrange? "..tostring(unit_loadouts[l].minrange))
																						debuGenTxt = debuGenTxt.."\n"..("______________route.lenght "..tostring(route.lenght).." >? "..tostring(unit_loadouts[l].minrange).." *2")
																						debuGenTxt = debuGenTxt.."\n"..("altiPass? "..tostring(altiPass))
																						debuGenTxt = debuGenTxt.."\n"..("altiPass? target.z "..tostring(target.z).." >? hHover "..tostring(unit_loadouts[l].hHover))
																					end
																			
																					if route and route.lenght and route.lenght <= unit_loadouts[l].range * 2 and (unit_loadouts[l].minrange == nil or route.lenght > unit_loadouts[l].minrange * 2) and altiPass then		--if sortie route lenght is within range of aircraft-loadout
																						if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
																						and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																						or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
																						then
																							debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_29 ".." After Range Condition") 
																						end
																						
																						TrackPlayability(unit[n].player, "target_range")												--track playabilty criterium has been met
																						
																						--determine number of aircraft needed for sortie
																						local aircraft_requested = target.firepower.max / unit_loadouts[l].firepower					--how many aircraft are needed to satisfy the maximum firepower requirement of the target
																						
																						-- if MultiPlayerOveRide and aircraft_requested <  multiPlaneSet[unit[n].type][task].NbPlane then
																							-- aircraft_requested =  multiPlaneSet[unit[n].type][task].NbPlane
																							-- if aircraft_requested > 4 then aircraft_requested = 4 end
																						-- end
																						
																						local flights_requested	
																						if task == "CAP" or task == "AWACS" or task == "Refueling" then									--multiple flights are required to continously cover a station for the duration of the mission
																							flights_requested = math.ceil((tot_to - tot_from) / unit_loadouts[l].tStation) + 1			--how many flights are needed to keep continous coverage of station, plus 1 for on station before mission start
																							aircraft_requested = aircraft_requested * flights_requested									--total number of requested aircraft is number of aircraft needed to statisfy firepower requirement of station * number of flights needed for continous coverage
																						end
																						if task == "AWACS" or task == "Refueling" or task == "Transport" or task == "Nothing" or task == "Reconnaissance" then
																							aircraft_requested = math.ceil(aircraft_requested)											--round up
																						elseif unit[n].type == "S-3B" or unit[n].type == "F-117A" or unit[n].type == "B-1B" or unit[n].type == "B-52H" or unit[n].type == "Tu-22M3" or unit[n].type == "Tu-95MS" or unit[n].type == "Tu-142" or unit[n].type == "Tu-160" or unit[n].type == "MiG-25RBT" then
																							aircraft_requested = math.ceil(aircraft_requested)											--round up
																						else
																							--aircraft_requested = math.ceil(aircraft_requested / 2) * 2								--round up to an even number
																							aircraft_requested = math.ceil(aircraft_requested)											--round up
																						end
																						local aircraft_assign
																						if aircraft_requested > aircraft_available then													--if more aircraft are requested than are available from this unit
																							aircraft_assign = math.floor(aircraft_available)														--assign all available aircraft
																						else																							--enough available aircraft to satisfy requested aircraft
																							aircraft_assign = math.floor(aircraft_requested)														--assign all requested aicraft
																						end

																						local debugMulti = ""
																						MultiPlayerOveRide = false
																						-- miguel21 modification M11.o multiplayer
																						if multiPlaneSet then
																							debugMulti = debugMulti.."\n"..("AtoG passe A_AAb "..tostring(task).." "..unit[n].type.." aircraft_assign:"..tostring(aircraft_assign))
																							if multiPlaneSet[side] and multiPlaneSet[side][unit[n].type]  and multiPlaneSet[side][unit[n].type][task] and task_bool then																							
																								if Multi.Target and Multi.Target[side] then
																									debugMulti = debugMulti.."\n"..("AtoG passe A_AAe Multi.Target[side] "..tostring(Multi.Target[side]) .. " ==? target_name? " .. tostring(target_name))
																									if Multi.Target[side] == target_name  then
																										debugMulti = debugMulti.."\n"..("AtoG passe A_AAf Multi.Target[side] "..tostring(Multi.Target[side]) .. " ==? target_name? " .. tostring(target_name).." "..unit[n].type.." "..tostring(task)) 
																										MultiPlayerOveRide = true
																									end
																								else 
																									debugMulti = debugMulti.."\n"..("AtoG passe A_AAg  " .. " ==? target_name? " .. tostring(target_name).." "..unit[n].type.." "..tostring(task)) 
																									
																									Multi.Target = {}
																									Multi.Target[side] = target_name
																									MultiPlayerOveRide = true
																								end
																								
																								--TODO a regarder si c'etait utile
																								-- if aircraft_assign > 4 and ( task == "CAP" or task == "Intercept") then
																									-- aircraft_assign = 4
																								-- end
																								
																								--M11.z
																								if MultiPlayerOveRide and aircraft_assign < multiPlaneSet[side][unit[n].type][task].NbPlane then
																									aircraft_assign = multiPlaneSet[side][unit[n].type][task].NbPlane
																									debugMulti = debugMulti.."\n"..("AtoG passe A_AAh "..unit[n].type.." aircraft_assign: "..tostring(aircraft_assign))
																								end
																								ClientPlayer = true											
																							end
																						end
																						
																						if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A") 
																						and  Debug.Generator.SpySquad and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																						or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name )) 
																						then
																							debuGenTxt = debuGenTxt.."\n"..debugMulti
																						end


																						--self escort
																						if unit_loadouts[l].self_escort then															--if the loadout is capable of self-escort
																							route.threats.air_total = route.threats.air_total / 2										--reduce the fighter threat by half
																							if route.threats.air_total < 0.5 then
																								route.threats.air_total = 0.5
																							end
																						end

																						--build sortie entry
																						repeat																							--for tasks with station repeat to make entries for lesser amount of aircraft, repeat once for everything else
																							local idTemp = "id"..#draft_sorties[side]+1

																							if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
																							and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																							or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
																							then
																								debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_30a ClientPlayer: "..tostring(ClientPlayer) .. " MultiPlayerOveRide: " .. tostring(MultiPlayerOveRide).." idTemp: "..tostring(idTemp)) 
																							end
																							
																							local draft_sorties_entry = {
																								name = unit[n].name,
																								playable = ClientPlayer, 					--unit[n].player,
																								type = unit[n].type,
																								callsign = unit[n].callsign,
																								callsignId = unit[n].callsignId,
																								helicopter = unit[n].helicopter,
																								number = aircraft_assign,
																								flights = flights_requested,
																								country = unit[n].country,
																								livery = unit[n].livery,
																								sidenumber = unit[n].sidenumber,
																								liveryModex = unit[n].liveryModex,
																								base = unit[n].base,
																								airdromeId = db_airbases[unit[n].base].airdromeId,
																								parking_id = unit[n].parking_id,
																								skill = unit[n].skill,
																								task = task,
																								tasks = unit[n].tasks,
																								loadout = unit_loadouts[l],
																								target = deepcopy(target),
																								target_name = target_name,
																								route = route,
																								tot_from = tot_from,
																								tot_to = tot_to,
																								support = {
																									["Escort"] = {},
																									["SEAD"] = {},
																									["Escort Jammer"] = {},
																									["Flare Illumination"] = {},
																									["Laser Illumination"] = {},
																									["Strike"] = {},
																									},
																								multipack = multipack,
																								threatsGround = route.threats.ground_total,
																								threatsAir = route.threats.air_total,
																								id = "DraftId"..draftId.."_id"..#draft_sorties[side]+1,
																								rejected = {},
																								MainMPOveRide = MultiPlayerOveRide,
																							}																																													
																							
																							
																							draft_sorties_entry.target.TitleName =  target_name													-- ATO_G_Debug04 correction targetName
																							
																							--score the sortie
																							local route_threat = route.threats.ground_total + route.threats.air_total						--combine route ground and air threat
																							if task == "CAP" or task == "Intercept" or task == "SAR" then
																								draft_sorties_entry.score = unit_loadouts[l].capability * target.priority					--route threat does not matter for CAP and intercept
																							else
																								draft_sorties_entry.score = unit_loadouts[l].capability * target.priority / route_threat	--calculate the score to measure the importance of the sortie
																							end
																							
																							if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
																							and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																							or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
																							then
																								debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_30b: score: " .. tostring(draft_sorties_entry.score).." = Load_capability: "..tostring(unit_loadouts[l].capability).." *T_priority "..tostring(target.priority).." /threat "..tostring(route_threat)
																								.." (ground_total "..route.threats.ground_total.." + air_total:"..route.threats.air_total.." )") 
																							end
																							
																							local reduce_score = 0																		--factor to reduce score for station missions with less aircraft than required to cover station
																							if task == "CAP" then																		--station tasks with flights of 2
																								reduce_score = flights_requested - aircraft_assign / math.ceil(target.firepower.max / unit_loadouts[l].firepower) --increase factor by one for each flight that is missing
																							elseif task == "AWACS" or task == "Refueling"  then											--station tasks with flights of 1
																								reduce_score = flights_requested - aircraft_assign										--increase factor by one for each flight that is missing
																							
																							end
																							draft_sorties_entry.score = draft_sorties_entry.score - reduce_score * 0.01					--reduce score slighthly for station missions with less aircraft than required to cover station
																		
																							--ATO_G_adjustment02
																							if unit[n].tasksCoef and unit[n].tasksCoef[task] then
																								draft_sorties_entry.score = draft_sorties_entry.score * unit[n].tasksCoef[task]																						
																							end
																						
																							if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
																							and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																							or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
																							then
																								debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_30d: score: " .. tostring(draft_sorties_entry.score).." "..unit[n].type.." "..tostring(task))
																							end
																							
																							-- miguel21 modification M11.q multiplayer
																							
																							if  multiPlaneSet[side] and  multiPlaneSet[side][unit[n].type] and  multiPlaneSet[side][unit[n].type][task] and task_bool and  multiPlaneSet[side][unit[n].type][task].NbPlane > 0 then
																								draft_sorties_entry.score = draft_sorties_entry.score + 1000
																								if MultiPlayerOveRide then
																									draft_sorties_entry.score = draft_sorties_entry.score * 2 +1000
																									end
																							elseif  Multi.Target and Multi.Target[side] == target_name  then
																								draft_sorties_entry.score = draft_sorties_entry.score * 2
																								end
																							
																							if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
																							and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																							or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
																							then
																								-- debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_30e: score: " .. tostring(draft_sorties_entry.score).." "..unit[n].type.." "..tostring(task)) 
																							end
																							
																							--insert sortie entry into draft_sorties table sorted by score (highest first)
																							if #draft_sorties[side] == 0 then															--if draft_sorties table is empty
																								-- table.insert(draft_sorties[side], draft_sorties_entry)
																								draft_sorties[side][#draft_sorties[side]+1] = draft_sorties_entry
																							else
																								for d = 1, #draft_sorties[side] do														--iterate through draft_sorties
																									if draft_sorties_entry.score > draft_sorties[side][d].score then					--score is bigger than current table entry
																										-- table.insert(draft_sorties[side], d, draft_sorties_entry)						--insert at current position in table
																										draft_sorties[side][#draft_sorties[side]+1] = draft_sorties_entry
																										break
																									elseif draft_sorties_entry.score == draft_sorties[side][d].score then				--score is same as current table entry
																										local sum = 1
																										for s = d + 1, #draft_sorties[side] do											--iterate through subsequent table entries
																											if draft_sorties_entry.score == draft_sorties[side][s].score then			--if these entries also have the same score
																												sum = sum + 1															--sum them
																											else
																												break
																											end
																										end
																										table.insert(draft_sorties[side], d + math.random(0, sum), draft_sorties_entry)	--insert random position position in table
																										-- draft_sorties[side][d + math.random(0, sum)] = draft_sorties_entry
																										break
																									elseif d == #draft_sorties[side] then												--if end of table is reached
																										-- draft_sorties_entry["id"] = "id"..#draft_sorties[side]+1
																										draft_sorties[side][#draft_sorties[side]+1] = draft_sorties_entry
																									end
																								end
																							end
																							if task == "CAP" or task == "AWACS" or task == "Refueling"  then
																								aircraft_assign = aircraft_assign - 1													--make additional draft sortie for lesser amount of aircraft
																							elseif MultiPlayerOveRide then
																								aircraft_assign = aircraft_assign - 4
																							else
																								aircraft_assign = 0																		--do not make additional draft sorties
																							end
																							
																							if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "A")   
																							and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																							or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == target_name ))
																							then
																								debuGenTxt = debuGenTxt.."\n"..("AtoG passe A_30_INIT aircraft_assign: "..aircraft_assign)
																							end
																						
																						until aircraft_assign <= 0																		--stop making more draft sorties
																					end
																				
																					variant = variant - 2																			--determines if while-loop does another route variant depending on daytime
																				end
																			end
																		end
																	end
																end
															end
														end
													end
												end
											end
										end
									end
								end
							end
						end
					end
				end
			end
		end
	end
end

print("-")
print("ATO Generating Sortie (" .. status_counter_sorties .. ") - Complete")
debuGenTxt = debuGenTxt.."\n"..("ATO Generating Sortie (" .. status_counter_sorties .. ") - Complete")

-- Modif Miguel21 M13 Performance Scripting	
-- ATO_G_debug02b haut score

-- local sorties_str = TableSerialization(draft_sorties["blue"], 0)
-- local sorties_File = io.open("Debug/BEFORE_sorties_str_R.lua", "w")										--open targetlist file
-- sorties_File:write(sorties_str)																		--save new data
-- sorties_File:close()

	local shuffled = {}
	for i, v in ipairs(oob_air["blue"]) do
		local pos = math.random(1, #shuffled+1)
		table.insert(shuffled, pos, v)
	end
	oob_air["blue"] = shuffled

	shuffled = {}
	for i, v in ipairs(oob_air["red"]) do
		local pos = math.random(1, #shuffled+1)
		table.insert(shuffled, pos, v)
	end
	oob_air["red"] = shuffled


	table.sort(draft_sorties["blue"], function(a,b) return a.score > b.score  end)
	table.sort(draft_sorties["red"], function(a,b) return a.score > b.score  end)
	
	
-- local sorties_str = TableSerialization(draft_sorties["blue"], 0)
-- local sorties_File = io.open("Debug/AFTER_sorties_str_R.lua", "w")										--open targetlist file
-- sorties_File:write(sorties_str)																		--save new data
-- sorties_File:close()


if Debug.Generator.affiche then	
	local di = 1 
	debuGenTxt = debuGenTxt.."\n"..("BLUE PART A")
	for draft_n, draft in pairs(draft_sorties["blue"]) do	
		if  di < Debug.Generator.nb or draft.name == Debug.Generator.SpySquad  or draft.target_name == Debug.Generator.SpyTarget then		--if  di < Debug.Generator.nb and string.find(draft.task, "Strike") then
			debuGenTxt = debuGenTxt.."\n"..(	"A N° " .. draft_n..
					" /Id/ " ..tostring(draft.id)..
					" /Nb/ " ..draft.number..
					" /flights/ " ..tostring(draft.flights)..
					" /Type/ "..draft.type..
					" /threatsGround/ "..round(draft.threatsGround)..
					" /threatsAir/ "..round(draft.threatsAir)..
					" /Score/ " ..round(draft.score)..
					" /Task/ "..draft.task..
					" /Target/ "..draft.target_name..
					" /Sead_Of/ "..tostring(draft.route.threats.SEAD_offset)..
					" /MainMPOveRide/ " ..tostring(draft.MainMPOveRide)
					-- .." /loadout/ "..tostring(draft.loadout.loadout_name)
					)
					debuGenTxt = debuGenTxt.."\n"
				
			di = di +1
		end
	end
	debuGenTxt = debuGenTxt.."\n"
end

if Debug.Generator.affiche then	
	local di = 1 
	debuGenTxt = debuGenTxt.."\n"..("RED PART A")
	for draft_n, draft in pairs(draft_sorties["red"]) do	
		if  di < Debug.Generator.nb or draft.name == Debug.Generator.SpySquad  or draft.target_name == Debug.Generator.SpyTarget then
			debuGenTxt = debuGenTxt.."\n"..(	"A N° " .. draft_n..
					" /Id/ " ..tostring(draft.id)..
					" /Nb/ " ..draft.number..
					" /flights/ " ..tostring(draft.flights)..
					" /Type/ "..draft.type..
					" /threatsGround/ "..round(draft.threatsGround)..
					" /threatsAir/ "..round(draft.threatsAir)..
					" /Score/ " ..round(draft.score)..
					" /Task/ "..draft.task..
					" /Target/ "..draft.target_name..
					" /Sead_Of/ "..tostring(draft.route.threats.SEAD_offset)..		
					" /MainMPOveRide/ " ..tostring(draft.MainMPOveRide)
					-- .." /loadout/ "..tostring(draft.loadout.loadout_name)
					)
					debuGenTxt = debuGenTxt.."\n"
			di = di +1
		end
	end
	debuGenTxt = debuGenTxt.."\n\n\n"
end

--create additional draft sorties with support flights assigned
local wk = 1							
i_timmer02 = 0

--inversion des 2 boucles draft_sortie en premier, oob_air ensuite, pour homogeniser les chances de sortie de tous les escadrons support
for sideS, draftT in pairs(draft_sorties) do		
	for draft_n, draft in pairs(draft_sorties[sideS]) do													--iterate through all draft sorties beginning with the highest scored

		if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B") 
		and ( Debug.Generator.SpySquad and Debug.Generator.SpySquad == draft.name 
		or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
		then 
			debuGenTxt = debuGenTxt.."\n\n"..(tostring(draft.id).." AtoG II passe B_00 target_name draftType: "..draft.type.." "..tostring(draft.target_name) .." "..tostring(draft.score)  ) 
		end
		
		--determine enemy side
		local enemy																						--determine enemy side (opposite of unit side)
		if side == "blue" then
			enemy = "red"
		else
			enemy = "blue"
		end
			
		
		local shuffled = {}
		for i, v in ipairs(oob_air["blue"]) do
			local pos = math.random(1, #shuffled+1)
			table.insert(shuffled, pos, v)
		end
		oob_air["blue"] = shuffled

		shuffled = {}
		for i, v in ipairs(oob_air["red"]) do
			local pos = math.random(1, #shuffled+1)
			table.insert(shuffled, pos, v)
		end
		oob_air["red"] = shuffled		
		
		for side, unit in pairs(oob_air) do																	--iterate through all sides						
			local NbTotalSupport = {}
			for n = 1, #unit do																				--iterate through all units
				
				local SupportMPOveRide = false
				
				if side == sideS and unit[n].inactive ~= true and db_airbases[unit[n].base] and db_airbases[unit[n].base].inactive ~= true and ( SupportMPOveRide or (aircraft_availability[unit[n].name] and aircraft_availability[unit[n].name].available > 0))  and db_airbases[unit[n].base].x  then	--if unit is active, its base is active and has available aircraft -- ATO_G_debug01 Fin de campagne					
					
				
					if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B") 
					and ( Debug.Generator.SpySquad and Debug.Generator.SpySquad == draft.name 
					or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
					then 
						debuGenTxt = debuGenTxt.."\n\n"..(tostring(draft.id).." AtoG II passe B_02_a draft.: "..draft.type.." OOBunit: "..unit[n].type.." MainMPOveRide?: "..tostring(draft.MainMPOveRide))
					end
		
					
					
					for task, task_bool in pairs(unit[n].tasks) do											--iterate through all tasks of unit
						local ClientPlayer = false
						local aliasTask = ""

						--permet l'escorte Strike d'un heli par un autre heli
						
						-- if draft.helicopter and draft.task == "CSAR" and unit[n].helicopter and (not unit[n].tasks.Escort or unit[n].tasks.Escort == nil)   and unit[n].tasks.Strike  then
						-- 	task = "Escort"
						-- 	aliasTask = "Strike"
						-- 	if Debug.Generator.affiche then
						-- 		print("AtoG AtoG II passe TEST BBBBBBBBBB_a task = Escort  aliasTask = Strike ")
						-- 	end

						-- 	if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
						-- 	and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
						-- 	or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
						-- 	then
						-- 			print("AtoG AtoG II passe TEST BBBBBBBBBB_b task = Escort  aliasTask = Strike ")
						-- 	end		
						-- end
						
						if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B") and multiPlaneSet[side]   
						and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
						or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
						then
							debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_02_c  "..draft.type.." OOBunit: "..unit[n].type.." "..task.." "..draft.target_name) 
							debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_02_d MainMPOveRide: "..tostring(draft.MainMPOveRide).." multiPlaneSet: "..tostring(multiPlaneSet[side][unit[n].type]).." task_bool: "..tostring(task_bool) ) 
						end						
						
						if draft.MainMPOveRide and multiPlaneSet[side][unit[n].type] and task_bool then	--and multiPlaneSet[unit[n].type][task] and task == "Strike" 
							SupportMPOveRide = true							
						else
							SupportMPOveRide = false	
						end
						
						if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
						and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
						or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
						then
							debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_02_e SupportMPOveRide: "..tostring(SupportMPOveRide)) 
						end

						local temp_draft_sorties = {}														--temporary table to hold additional draft sorties with escorts assigned
						-- if (SupportMPOveRide or (task == "SEAD" or task == "Escort" or task == "Escort Jammer" or task == "Flare Illumination" or task == "Laser Illumination")) and task_bool then	--task is a support task and is true
						if ( draft.task ~= "CAP" and draft.task ~= "Intercept" ) and (task == "SEAD" or task == "Escort" or task == "Escort Jammer" or task == "Flare Illumination" or task == "Laser Illumination" or task == "Strike") and task_bool then	--task is a support task --and is true and draft.task ~= "SAR"
							
							if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B") 
							and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
							or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
							then
								debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_03 task_bool draft: "..task.." SupportMPOveRide: "..tostring(SupportMPOveRide)) 
							end
							
							--get possible loadouts
							local unit_loadouts = {}														--table to hold all loadouts for this aircraft type and task
		
							-- if aliasTask ~= "" then
							-- 	for loadout_name, ltable in pairs(db_loadouts[unit[n].type][aliasTask]) do			--iterate through all loadouts for the aircraft type and task
							-- 		ltable.name = loadout_name
							-- 		unit_loadouts[#unit_loadouts+1] = ltable
							-- 	end
							-- else
							-- 	for loadout_name, ltable in pairs(db_loadouts[unit[n].type][task]) do			--iterate through all loadouts for the aircraft type and task
							-- 		ltable.name = loadout_name
							-- 		unit_loadouts[#unit_loadouts+1] = ltable
							-- 	end		
							-- end
							
							for loadout_name, ltable in pairs(db_loadouts[unit[n].type][task]) do			--iterate through all loadouts for the aircraft type and task
								ltable.name = loadout_name
								unit_loadouts[#unit_loadouts+1] = ltable
							end
							
							for l = 1, #unit_loadouts do													--iterate through all available loadouts				
								--get possible Time on Target
								local tot_from = 0															--earliest Time on Target for this loadout
								local tot_to = 0															--latest Time on target for this loadout
								if unit_loadouts[l].day and unit_loadouts[l].night then						--loadout is day and night capable
									tot_from = 0															--from mission start
									tot_to = camp.mission_duration											--to mission end
								elseif unit_loadouts[l].day then											--loadout is day capable
									if daytime == "night-day" then
										tot_from = camp.dawn - camp.time									--from dawn
										tot_to = camp.mission_duration										--to mission end
									elseif daytime == "day" then
										tot_from = 0														--from missiom start
										tot_to = camp.mission_duration										--to mission end
									elseif daytime == "day-night" then
										tot_from = 0														--from mission start
										tot_to = camp.dusk - camp.time										--to dusk
									end
								elseif unit_loadouts[l].night then											--loadout is night capable
									if daytime == "day-night" then
										tot_from = camp.dusk - camp.time									--from dusk
										tot_to = camp.mission_duration										--to mission end
									elseif daytime == "night" then
										tot_from = 0														--from mission start
										tot_to = camp.mission_duration										--to mission end
									elseif daytime == "night-day" then
										tot_from = 0														--from mission start
										tot_to = camp.dawn - camp.time										--to dawn
									end
								end
								
								if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
								and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
								or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
								then
									debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_04 tot_from: |"..tostring(tot_from).."|"..tostring(tot_to).."|" ) 
								end

								if SupportMPOveRide or (tot_from ~= 0 or tot_to ~= 0)   then										--loadout has an eligible time on target
									
									if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
									and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
									or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
									then
										debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_05 tot_from  "..task) 
									end
									
									local _NbTotalSupport = 0

									if not draft.support[task] then draft.support[task] ={} end
									if not draft.support[task]["NbTotalSupport"] then draft.support[task]["NbTotalSupport"] = 0 end
									-- if not draft.support[task]["escort_max"] then draft.support[task]["escort_max"] = campMod.Setting_Generation.limit_escort end
									if not draft.support[task]["escort_max"] then draft.support[task]["escort_max"] = 999 end
									
									local MP_Game = false
									if multiPlaneSet then
										if multiPlaneSet[side] and multiPlaneSet[side][unit[n].type]  and multiPlaneSet[side][unit[n].type][task] then	--and task ~= "CAP" and task ~= "Intercept"
											if Multi.Target and Multi.Target[side] and Multi.Target[side] == draft.target_name then	
												MP_Game = true
												
												if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
												and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
												or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
												then 
													debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_10c MP_Game = true ") 
												end

											end
										end
									end
									
									if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
									and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
									or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
									then
										if draft.loadout.support and draft.loadout.support[task] then
											debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_11a tot_from  "..tostring(task))
										else
											debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_11b tot_from  "..tostring(task).." NbTotalSupport: "..tonumber(draft.support[task]["NbTotalSupport"]).." escort_max: "..tonumber(draft.support[task]["escort_max"]))
											-- debuGenTxt = debuGenTxt.."\n".. TableSerialization(draft.loadout, 0)  
										end
										
									end
									
									i_timmer02 = i_timmer02 +1
									if SupportMPOveRide or (draft.loadout.support and draft.loadout.support[task])
										and ( (tonumber(draft.support[task]["NbTotalSupport"]) < tonumber(draft.support[task]["escort_max"])) or MP_Game ) then
										
										
										if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
										and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
										or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
										then
											-- debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_12 draft.loadout.support  "..tostring(draft.loadout.support)) 
											-- debuGenTxt = debuGenTxt.."\n"..TableSerialization(draft.route.threats, 0)
										end
										
										
										local support_requirement = false
										if task == "SEAD" then
											if draft.route.threats.SEAD_offset > 0 then												--draft sortie has a SEAD offset requirement
												support_requirement = true
											end
										elseif task == "Escort" then
											if draft.route.threats.air_total > 0.5 then												--draft sortie has an air threat
												support_requirement = true
											end
										elseif task == "Escort Jammer" then
											if draft.route.threats.SEAD_offset > 0 or draft.route.threats.air_total > 0.5 then		--draft sortie has either a SEAD offest requirement or an air threat
												support_requirement = true
											end
										elseif task == "Flare Illumination" or task == "Laser Illumination"then
											support_requirement = true
										end
										

										if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
										and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
										or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
										then
											debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_15 SEAD_offset?: "..tostring(draft.route.threats.SEAD_offset).." support_requirement?: "..tostring(support_requirement).." "..unit[n].type.." MP_Game: "..tostring(MP_Game)) 
										end
										
										if support_requirement or MP_Game then																	--go ahead with this support task
											if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
											and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
											or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
											then
												debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_15b support_requirement passe: ") 
											end
										
										
											if (unit_loadouts[l].day and draft.loadout.day) or (unit_loadouts[l].night and draft.loadout.night) then	--support can join package at either day or night
												TrackPlayability(unit[n].player, "tot")															--track playabilty criterium has been met
												--admet une vitesse (escort) 75% plus faible que la vitesse du Main
												if unit_loadouts[l].vCruise < draft.loadout.vCruise then
													
													
													if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
													and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
													or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
													then
														debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_15c unit_loadouts[l].vCruise : "..tostring(unit_loadouts[l].vCruise).." < "..tostring(draft.loadout.vCruise).. " | %: "..tostring(unit_loadouts[l].vCruise / draft.loadout.vCruise)) 
													end
													
													if (unit_loadouts[l].vCruise / draft.loadout.vCruise) * 100 >= 75 then
														draft.loadout.vCruise = unit_loadouts[l].vCruise 
													end
												end

												if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
												and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
												or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
												then
													debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_15d support_requirement passe: ") 
												end

												if unit_loadouts[l].vCruise >= draft.loadout.vCruise then										--support has a cruise speed equal or higher than main body
													TrackPlayability(unit[n].player, "target")													--track playabilty criterium has been met
													
													if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
													and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
													or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
													then
														debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_15e support_requirement passe: ") 
													end

													--check weather
													local weather_eligible = true
													if mission.weather["clouds"]["density"] > 8 then											--overcast clouds
														local cloud_base = mission.weather["clouds"]["base"]
														local cloud_top = mission.weather["clouds"]["base"] + mission.weather["clouds"]["thickness"]
														if db_airbases[unit[n].base].elevation + 333 > cloud_base then							--cloud base is less than 1000 ft above airbase elevation
															if unit_loadouts[l].adverseWeather == false then									--loadout is not adverse weather capable
																weather_eligible = false														--not eligible for this weather
															end
														else
															if draft.loadout.hCruise > cloud_base and draft.loadout.hCruise < cloud_top then	--cruise alt is in the clouds
																if unit_loadouts[l].adverseWeather == false then								--loadout is not adverse weather capable
																	weather_eligible = false													--not eligible for this weather
																end
															elseif draft.loadout.hAttack > cloud_base and draft.loadout.hAttack < cloud_top then	--attack alt is in the clouds
																if unit_loadouts[l].adverseWeather == false then								--loadout is not adverse weather capable
																	weather_eligible = false													--not eligible for this weather
																end
															end
														end
													end
													if mission.weather["enable_fog"] == true then												--fog
														if db_airbases[unit[n].base].elevation < mission.weather["fog"]["thickness"] then		--base elevation in fog
															if mission.weather["fog"]["visibility"] < 5000 then									--less than 5000m visibility
																if unit_loadouts[l].adverseWeather == false then								--loadout is not adverse weather capable
																	weather_eligible = false													--not eligible for this weather
																end
															end
														end
													end
													
													if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
													and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
													or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
													then
														debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_15e support_requirement passe: weather_eligible "..tostring(weather_eligible).." SupportMPOveRide "..tostring(SupportMPOveRide)) 
													end

													if weather_eligible or SupportMPOveRide then												--continue of this loadout is eligible for weather
														
														TrackPlayability(unit[n].player, "weather")												--track playabilty criterium has been met								
														--get airbase position
														local airbasePoint = {																	--get the x-y coordinates of the airbase where the unit is located
															x = db_airbases[unit[n].base].x,
															y = db_airbases[unit[n].base].y,
															h = db_airbases[unit[n].base].elevation,
														}												
													
														local route = GetEscortRoute(airbasePoint, draft.route, task, unit_loadouts[l], unit[n], draft)									--get the route to escort this sortie
														
														if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
														and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
														or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
														then
															debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_16 weather_eligible route.lenght: "..tostring(route.lenght).. " <= "..tostring(unit_loadouts[l].range).." * 2 " ..tostring(unit_loadouts[l].range)) 
														end
											
														
														if route.lenght <= unit_loadouts[l].range * 2 and (unit_loadouts[l].minrange == nil or route.lenght > unit_loadouts[l].minrange * 2) then		--escort route lenght is within range capability of loadout
															TrackPlayability(unit[n].player, "target_range")									--track playabilty criterium has been met
															if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
															and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
															or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
															then
																debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_17  ") 
															end
															
															--determine number of escorts
															local escort_num = 0
															local escort_max = 0
															
															if draft.support[task]["escort_max"] ~= 999 then
																escort_max = draft.support[task]["escort_max"]
															else
																escort_max = 0
															end														
															
															if task == "SEAD" then
																escort_num = draft.route.threats.SEAD_offset / unit_loadouts[l].capability		--capability determines amount of offset per aircraft
																escort_num = math.ceil(escort_num / 2) * 2										--round up requested escorts to even number
																
																if totalPlanePerTask[side][task] and totalPlanePerTask[side][task]/2 >= escort_num then
																	draft.score = draft.loadout.capability * draft.target.priority
																end

																if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
																and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
																then
																	debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe_SEAD B "..unit[n].type.." "..task.." "..escort_num.." NbTotalSupport: "..draft.support[task]["NbTotalSupport"].." draft.score: "..draft.score) 
																end

															elseif task == "Escort" then
																if draft.support[task]["escort_max"] ~= 999 then
																	escort_num = draft.support[task]["escort_max"] - draft.support[task]["NbTotalSupport"]	-- Miguel21 modification M11.x : Multiplayer	(x: EscorteTot-max)
																	
																	if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
																	and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																	or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
																	then
																		debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe_Escort B "..unit[n].type.." "..task.." "..escort_num.." NbTotalSupport: "..draft.support[task]["NbTotalSupport"]) 
																	end
																else
															
																	local escort_offset_level = unit_loadouts[l].capability * unit_loadouts[l].firepower	--threat level that each fighter escort can offset
																	escort_num = (draft.route.threats.air_total - 0.5) / escort_offset_level		--number of escorts needed to offset total air threat (-0.5 because that is no air threat)
																	
																	if escort_num > draft.number * 3 then											--when more escorts 3 times escorts than escorted aircraft
																		escort_num = draft.number * 3												--limit escort number to 3 times escorted aircraft
																	end
																	if escort_num > campMod.Setting_Generation.limit_escort then
																		escort_num = campMod.Setting_Generation.limit_escort
																	end

																	escort_num = math.ceil(escort_num / 2) * 2										--round up requested escorts to even number
																	
																	if escort_num > escort_max then
																		escort_max = escort_num
																	end
																	
																	if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
																	and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																	or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
																	then
																		debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe_Escort I "..unit[n].type.." "..task.." "..escort_num) 
																	end
																end
															
															elseif task == "Escort Jammer" then
																escort_num = 1																	--escort jamming by single aircraft
															elseif task == "Flare Illumination" then
																escort_num = 1																	--flare illumination by single aircraft
															elseif task == "Laser Illumination" then
																escort_num = 1																	--laser illumination by single aircraft
															elseif task == "Strike" and SupportMPOveRide then
																escort_num = 4	
															end
															
															if escort_num > aircraft_availability[unit[n].name].available then					--if more escorts are requested than available
																escort_num = aircraft_availability[unit[n].name].available						--reduce requested escorts to number of available escorts
																escort_num = math.floor(escort_num / 2) * 2										--round down to even number
																
																if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
																and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
																then
																	debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe_Escort J "..unit[n].type.." "..task.." escort_num: "..escort_num.." available: "..aircraft_availability[unit[n].name].available)
																end
															end
															
															if MP_Game	then
																escort_num = multiPlaneSet[side][unit[n].type].InitNbPlane
																if escort_num < 4 then escort_num = 4 end
																
																if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
																and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
																then
																	debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe_Escort O "..unit[n].type.." "..task.." "..escort_num)
																end
															end
															
															-- ATO_G_Debug05 interdit l'escorte avion/helico
															-- if draft.helicopter then
															-- 	if not  unit[n].helicopter	then
															-- 		escort_num = 0
															-- 	end
															-- end
															
															if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
															and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
															or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
															then
																debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe_Escort P "..unit[n].type.." "..task.." "..escort_num)
															end
															
															-- miguel21 modification M11.o multiplayer
															if multiPlaneSet then
																if  multiPlaneSet[side] and multiPlaneSet[side][unit[n].type]  and multiPlaneSet[side][unit[n].type][task] then	
																--if multiPlaneSet[unit[n].type]  and multiPlaneSet[unit[n].type][task] and task_bool then
																
																	ClientPlayer = true
																	
																	if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
																	and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																	or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
																	then
																	
																		debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_20a2 escort_num "..tostring(escort_num).." InitNbPlane: "..tostring(multiPlaneSet[side][unit[n].type][task].InitNbPlane)  ) 
																	
																		debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_20a2 escort_num "..tostring(escort_num).." InitNbPlaneByTask: "..tostring(multiPlaneSet[side][unit[n].type][task].InitNbPlaneByTask)  ) 
																	
																	end
																	
																	-- print("W "..unit[n].type.." "..task.." "..escort_num)
																	if escort_num < multiPlaneSet[side][unit[n].type][task].InitNbPlaneByTask then
																		escort_num = multiPlaneSet[side][unit[n].type][task].InitNbPlaneByTask
																		if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
																		and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
																		or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
																		then
																			debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_20b escort_num "..tostring(escort_num)) 
																		end															
																	end																	
																end
															end
															
															if Multi.NbGroup == 0 then
																ClientPlayer = unit[n].player
															end
															
															local wi = 1
															
															
															if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
															and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
															or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
															then
																debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_21a Id"..tostring(draft.id).." escort_num "..tostring(escort_num).." "..draft.target_name.." NbTotalSupport: "..draft.support[task]["NbTotalSupport"]) 
															end
															
															TrackPlayability(unit[n].player, "target_firepower")							--track playabilty criterium has been met
															
															local entryEscortNum
															-- if escort_num > 4 then 
																-- entryEscortNum = 4
															-- else
																-- entryEscortNum = escort_num
															-- end
															entryEscortNum = escort_num
															
															if not draft.support[task] then
																draft.support[task] = {}
															end
															if not draft.support[task][unit[n].type] then
																draft.support[task][unit[n].type] = {}
															end
															
															--add escort table to sortie															
															draft.support[task]["NbTotalSupport"] = draft.support[task]["NbTotalSupport"] + escort_num
															draft.support[task]["escort_max"] = escort_max
															
															if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
															and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
															or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
															then
																debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_21b Id "..tostring(draft.id).." "..unit[n].type.." "..unit[n].name.."".." escort_num "..tostring(escort_num).." "..draft.target_name.." NbTotalSupport: "..draft.support[task]["NbTotalSupport"]) 
																-- os.execute 'pause'
															end

															draft.support[task][unit[n].type] = {
																id = draft.id.."-"..wi.."-"..wk,
																name = unit[n].name,
																playable = ClientPlayer,								--unit[n].player,
																-- playable = unit[n].player,
																type = unit[n].type,
																callsign = unit[n].callsign,
																callsignId = unit[n].callsignId,
																helicopter = unit[n].helicopter,											-- Miguel21 modification M06 : helicopter playable
																number = entryEscortNum,
																country = unit[n].country,
																livery = unit[n].livery,
																sidenumber = unit[n].sidenumber,
																liveryModex = unit[n].liveryModex,
																base = unit[n].base,
																airdromeId = db_airbases[unit[n].base].airdromeId,
																parking_id = unit[n].parking_id,
																skill = unit[n].skill,
																task = task,
																tasks = unit[n].tasks,
																loadout = unit_loadouts[l],
																route = route,
																target = deepcopy(draft.target),
																target_name = draft.target_name,
																tot_from = draft.tot_from,
																tot_to = draft.tot_to,
																rejected = {},
																SupportMPOveRide = SupportMPOveRide,
															}

															--recalculate threat level for sortie adjusted by number of escort
															local route_threat_recalc = 0.5														--recalculated route threat with escort in place (0.5 == no threat)
															if task == "SEAD" then
																local escort_offset = escort_num * unit_loadouts[l].capability					--number of available SEAD to offset threats
																for k,v in pairs(draft.route.threats.ground) do									--iterate through route ground threats
																	if v.offset > 0 then														--if threat can be offset by SEAD
																		if escort_offset >= v.offset then										--some SEAD aircraft remain to offset the threat
																			route_threat_recalc = escort_offset - v.offset							--use these SEAD aircraft to offset and ignore the therat
																		else																	--no SEAD aircraft remain unassignedd
																			route_threat_recalc = route_threat_recalc + v.level					--sum route ground threat levels
																		end
																	else																		--threat cannot be offset by SEAD
																		route_threat_recalc = route_threat_recalc + v.level						--sum route ground threat levels
																	end
																end
																
																if not draft.route.threats.ground_total_Init then
																	draft.route.threats.ground_total_Init = draft.route.threats.ground_total
																end
																
																draft.route.threats.ground_total = route_threat_recalc			--recalculated total route grund threat
															elseif task == "Escort" then
																
																local escort_offset_level = unit_loadouts[l].capability * unit_loadouts[l].firepower		--threat level that each fighter escort can offset
																route_threat_recalc = draft.route.threats.air_total - escort_offset_level * escort_num			--recalculated total route air threat

																if route_threat_recalc < 0.5 then
																	route_threat_recalc = 0.5
																end
																draft.route.threats.air_total = route_threat_recalc
															elseif task == "Escort Jammer" then
--ADD RECALCULATED THREAT LEVEL WITH ESCORT JAMMERS
															end
														
															if  multiPlaneSet[side] and  multiPlaneSet[side][unit[n].type] and  multiPlaneSet[side][unit[n].type][task] and task_bool and  multiPlaneSet[side][unit[n].type][task].NbPlane > 0 then
																draft.score = draft.score + 1000
																debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG B passe multiPlaneSet B: score: " .. tostring(draft.score).." "..unit[n].type.." "..tostring(task))
																
																if draft.MainMPOveRide then
																	draft.score = draft.score * 2 +1000
																	debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG B passe multiPlaneSet C: score: " .. tostring(draft.score).." "..unit[n].type.." "..tostring(task))
																end
															elseif  Multi.Target and Multi.Target[side] == draft.target_name  then
																-- draft.score = draft.score * 2   -- attention tout autre avion non multi augmente drastiquement ici
																draft.score = draft.score + 1 
																debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG B passe multiPlaneSet D:  "..tostring(draft.id).." score: " .. tostring(draft.score).." "..unit[n].type.." "..tostring(task))
															end
															

															--adjust sortie Time on Target
															if tot_from > draft.tot_from then									--if earliest escort Time on Target is later than main body TOT
																draft.tot_from = tot_from							--make earliest escort TOT the draft sortie earliest TOT 
															end
															if tot_to < draft.tot_to then										--if latest escort Time on Target is sooner than main body TOT
																draft.tot_to = tot_to								--make latest escort TOT the draft sortie latest TOT
															end

															--status report
															status_counter_escorts = status_counter_escorts + 1
															--debuGenTxt = debuGenTxt.."\n"..("ATO Assigning Escorts (" .. status_counter_escorts .. ")")	--DEBUG
															
															wi = wi + 1
															
															-- escort_num = escort_num - 4 
															
															-- escort_num = 0
															
															if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "B")   
															and (Debug.Generator.SpySquad and Debug.Generator.SpySquad == unit[n].name  and  Debug.Generator.SpyTask == task
															or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft.target_name ))
															then
																debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG II passe B_22 escort_num "..tostring(escort_num).." "..unit[n].type.." target_name: "..tostring(draft.target_name)) 
															end

														
														end
													end
												else
													-- print("ATO_G  Refused02 ||:if unit_loadouts[l].vCruise >= draft.loadout.vCruise "..debug.getinfo(1).currentline)
												end
											else
												-- print("ATO_G  Refused02 ||:if (unit_loadouts[l].day and draft.loadout.day) or "..debug.getinfo(1).currentline)
											end
										end
									else
										-- print("ATO_G  Refused02 ||:if draft.loadout.support and draft.loadout.support[task] and "..debug.getinfo(1).currentline)
										-- print("    draft.type"..tostring(draft.type).."[task]?: "..tostring(task).." NbTotalSupport: "..tonumber(draft.support[task]["NbTotalSupport"]).." < "..tonumber(draft.support[task]["escort_max"]).." or "..tostring(MP_Game))
									end
									if i_timmer02 >= 1000  then io.write(".") i_timmer02 = 0 end
									wk = wk +1
								end	
							end
						end
					end
				end
			end
		end
	end
end
print()
print("ATO Assigning Escorts (" .. status_counter_escorts .. ")")	--DEBUG
debuGenTxt = debuGenTxt.."\n\n"..("ATO Assigning Escorts (" .. status_counter_escorts .. ")")

-- ATO_G_debug02b haut score

	table.sort(draft_sorties["blue"], function(a,b) return a.score > b.score  end)
	table.sort(draft_sorties["red"], function(a,b) return a.score > b.score  end)

	
if Debug.Generator.affiche then	
	local di = 1 
	debuGenTxt = debuGenTxt.."\n"..("BLUE PART B")
	for draft_n, draft in pairs(draft_sorties["blue"]) do	
		if  di < Debug.Generator.nb or draft.name == Debug.Generator.SpySquad  or draft.target_name == Debug.Generator.SpyTarget then
			
			debuGenTxt = debuGenTxt.."\n"..(	"B N° " .. draft_n..
					-- " /support/ " ..tostring(draft.support)..
					" /Id " ..tostring(draft.id)..
					" /Name/ " ..tostring(draft.name)..
					" /Nb/ " ..draft.number..
					" /flights/ " ..tostring(draft.flights)..
					" /Type/ "..draft.type..
					" /thrtGrnd/ "..round(draft.threatsGround)..
					" /thrtA/ "..round(draft.threatsAir)..
					" /Score/ " ..round(draft.score)..
					" /NbTotSupt/ " ..tostring(draft.NbTotalSupport)..
					
					" /Task/ "..draft.task..
					" /Target/ "..draft.target_name..
					" /Sead_Of/ "..tostring(draft.route.threats.SEAD_offset)..
					" /MainMPOveRide/ " ..tostring(draft.MainMPOveRide)..
					" /loadout/ "..tostring(draft.loadout.loadout_name)
					)

			di = di +1
			for _PlaneTask, PlaneTask in pairs(draft.support) do
				for taskName, task in pairs(PlaneTask) do	
				
					if type(task) == "table" then	
						debuGenTxt = debuGenTxt.."\n"..(	"    ---> Nsupport " .._PlaneTask.." ".. taskName..
								" /Id/ " ..tostring(task.id)..
								" /Nb/ " ..task.number..
								" /escort_max/ " ..tostring(PlaneTask.escort_max)..
								" /Type/ "..task.type..
								" /Task/ "..task.task..
								" /NbTotSupt/ " ..tostring(task.NbTotalSupport)..
								" /Target/ "..task.target_name..
								" /SupportMPOveRide/ "..tostring(task.SupportMPOveRide)..
								" /loadout/ "..tostring(task.loadout.loadout_name)
								)
					end
				end
			end
			debuGenTxt = debuGenTxt.."\n\n"
		end
	end
	debuGenTxt = debuGenTxt.."\n"
end

	
if Debug.Generator.affiche then	
	local di = 1 
	debuGenTxt = debuGenTxt.."\n"..("RED PART B")
	for draft_n, draft in pairs(draft_sorties["red"]) do	
		if  di < Debug.Generator.nb or draft.name == Debug.Generator.SpySquad  or draft.target_name == Debug.Generator.SpyTarget  then
			debuGenTxt = debuGenTxt.."\n"..(	"B N° " .. draft_n..
					-- " /support/ " ..tostring(draft.support)..
					" /Id" ..tostring(draft.id)..
					" /Id/ " ..tostring(draft.id)..
					" /Nb/ " ..draft.number..
					" /flights/ " ..tostring(draft.flights)..
					" /Type/ "..draft.type..
					" /threatsGround/ "..round(draft.threatsGround)..
					" /threatsAir/ "..round(draft.threatsAir)..
					" /Score/ " ..round(draft.score)..
					" /Task/ "..draft.task..
					" /Target/ "..tostring(draft.target_name)..
					" /Sead_Of/ "..tostring(draft.route.threats.SEAD_offset)..
					" /MainMPOveRide/ " ..tostring(draft.MainMPOveRide)..
					" /loadout/ "..tostring(draft.loadout.loadout_name)
					)

			di = di +1
			for _PlaneTask, PlaneTask in pairs(draft.support) do
				for taskName, task in pairs(PlaneTask) do	
					if type(task) == "table" then	
						debuGenTxt = debuGenTxt.."\n"..(	"    ---> Nsupport " .._PlaneTask.." ".. taskName..
								" /Id/ " ..tostring(task.id)..
								" /Nb/ " ..task.number..
								" /escort_max/ " ..tostring(PlaneTask.escort_max)..
								" /Type/ "..task.type..
								" /Task/ "..task.task..
								" /NbTotSupt/ " ..tostring(task.NbTotalSupport)..
								" /Target/ "..task.target_name..
								" /SupportMPOveRide/ "..tostring(task.SupportMPOveRide)..
								" /loadout/ "..tostring(task.loadout.loadout_name)
								)
						-- print()
					end
				end
			end
			debuGenTxt = debuGenTxt.."\n\n"
		end
	end
	debuGenTxt = debuGenTxt.."\n\n\n"	
end



--table to store the final ATO
ATO = {
	blue = {},
	red = {}
}


--assign draft sorties to ATO and build packages/flights
for side, draft in pairs(draft_sorties) do																		--iterate through all sides
	
	for n = 1, #draft do																						--iterate through all draft sorties beginning with the highest scored			
		
		if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "C") 
		and ( Debug.Generator.SpySquad and Debug.Generator.SpySquad == draft[n].name 
		or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft[n].target_name ))
		then
			debuGenTxt = debuGenTxt.."\n"..(tostring(draft[n].id).." AtoG C passe 00 "..draft[n].type.." "..draft[n].task.." "..draft[n].score) 
		end
		
		--diminue le minscore en fonction du nombre de tentative de generation de mission
		--evite un blocage de generation
		if draft[n].loadout.minscore then
			-- print("AtoG BEFOR minscore "..draft[n].loadout.minscore)
			draft[n].loadout.minscore = draft[n].loadout.minscore / ((MissionInstance )/10 +1)
			-- print("AtoG After minscore "..draft[n].loadout.minscore)
		end

		if draft[n].loadout.minscore == nil or draft[n].loadout.minscore <= draft[n].score then					--draft sortie has no minimum score requirement or minimum score requirement is satisified		
			
			if draft[n].multipack == nil or draft[n].multipack > 0 then												--target does not have a requirment for a specific number of packages, or still needs more packages		

				if draft[n].target.firepower.max > 0 and draft[n].target.firepower.max >= draft[n].target.firepower.min then	--the target of this draft sortie must have a need for firepower above the minimum firepower threshold	
					local available = aircraft_availability[draft[n].name].unassigned											--shortcut for available aircraft for this draft sortie					

					if available * draft[n].loadout.firepower >= draft[n].target.firepower.min and draft[n].number * draft[n].loadout.firepower >= draft[n].target.firepower.min then	--enough aircraft are available to satisfy minimum firepower requirement for target						

						if draft[n].target.firepower.packmin == nil or available * draft[n].loadout.firepower >= (draft[n].target.firepower.packmin - 1) * draft[n].target.firepower.max + draft[n].target.firepower.min then	--if the target has a minimum package number requirement, sufficient aircraft are available from this unit to satisfy it					
							
							--M11_z
							local limitMP = true   --TODO a revoir, semble inutile
							
							if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "C") 
							and ( Debug.Generator.SpySquad and Debug.Generator.SpySquad == draft[n].name 
							or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft[n].target_name ))
							and multiPlaneSet and multiPlaneSet[side] and multiPlaneSet[side][draft[n].type] 
							and multiPlaneSet[side][draft[n].type][draft[n].task]							
							then 
								debuGenTxt = debuGenTxt.."\n"..(tostring(draft[n].id).." AtoG C passe 00_b  ".." "..draft[n].type
								.." available: "..tostring(available)
								.." < NbPlane? ".. tostring(multiPlaneSet[side][draft[n].type][draft[n].task].NbPlane)
								.." MainMPOveRide?: "..tostring(draft[n].MainMPOveRide)
								.." SupportMPOveRide?: "..tostring(draft[n].SupportMPOveRide)
							)
							end
						
							if (draft[n].flights == nil or draft[n].number <= available or draft[n].MainMPOveRide) and limitMP then											--for targets with station time (multiple flights), continue only if sufficient aircraft are availabe. Additional lower scored sorties with less airctaft required will come later 

								--adjust the number of requested aircraft to the number of available aircraft
								if draft[n].number > available and not draft[n].MainMPOveRide then
									draft[n].number = available
								
								
									if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "C") 
									and ( Debug.Generator.SpySquad and Debug.Generator.SpySquad == draft[n].name 
									or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft[n].target_name ))
									then 
										debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG passe 00_c  number "..tostring(draft[n].number)) 
									end	
								
								end
								
								--check if there are enough supports available if supports are required		
								local support_available = true		
								-- local supportMandatory = true					
								
								local need = {}																														--collect the total number of aircraft needed from each unit to complete the package
								need[draft[n].name] = draft[n].number																								--number of main body aircraft 
								local avail = {}																													--collect the maximal number of available aircraft from this unit (biggest number of all tasks)
								avail[draft[n].name] = aircraft_availability[draft[n].name].unassigned								

								-- ["newTaskRequest"] = 
								-- {
								-- 	["red"] = 
								-- 	{
								-- 		["C-130"] = 
								-- 		{
								-- 			["Transport"] = 
								-- 			{
								-- 				["Escort"] = true,
								-- 			},
							
								-- 		},
								-- 	},
								-- },

								-- --ajoute une task obligatoire en fonction du learning des missions précédentes
								-- if camp.newTaskRequest then
								-- 	for rSide, rSides in pairs(camp.newTaskRequest) do
								-- 		if rSide == side then
								-- 			for rTypeName, rTypes in pairs(rSides) do
								-- 				if rTypeName == draft[n].type then
								-- 					for rTaskEnCours, rNewTasks in pairs(rTypes) do
								-- 						if rTaskEnCours == draft[n].task then
								-- 							for rNewTask, value in pairs(rNewTasks) do
								-- 								if value then
								-- 									for support_name, supportPart in pairs(draft[n].support) do										--iterate through all package support
								-- 										if type(supportPart) == "table" then	
								-- 											for _plane, support in pairs(supportPart) do
								-- 												if type(support) == "table" and not support.SupportMPOveRide then
								-- 													if  support.number > aircraft_availability[support.name].unassigned then 
								-- 														support_available = false
								-- 														-- print("AtoG passe support_available FALSE "..draft[n].target_name.." "..support.name.." "..support.number)
								-- 														-- os.execute 'pause'

								-- 														local TabRejected = {}
								-- 														TabRejected["sujet"]  = draft[n].id.." type: "..support.type.." newTaskRequest  AVION SUPPORT INSUFFISANTsupport.number < unassigned "
								-- 														TabRejected["cause"] = { [1] = aircraft_availability[support.name].unassigned, [2] = "newTaskRequest", }
								-- 														TabRejected["ligne"]  = debug.getinfo(1).currentline														
								-- 														table.insert(draft[n]["rejected"], TabRejected)

								-- 													end
								-- 												end
								-- 											end
								-- 										end
								-- 									end	
								-- 									-- print("AtoG passe newTaskRequest "..draft[n].target_name.." "..rTypeName .." rTaskEnCours: "..rTaskEnCours.." rNewTask: ".. rNewTask)
								-- 									-- os.execute 'pause'

								-- 								end
								-- 							end
								-- 						end
								-- 					end
								-- 				end
								-- 			end
								-- 		end
								-- 	end
								-- end

								-- ["newTaskPerTarget"] = 
								-- {
								-- 	["EWR-Eyeball"] = 
								-- 	{
								-- 		["tasks"] = 
								-- 		{
								-- 			["SEAD"] = 1,
								-- 			["Escort"] = 2,
								-- 		},
								-- 		["difficult"] = 2,
								-- 		["lastNumMission"] = 2,
								-- 	},
								-- 	["North Cyprus-Turkish Force 4"] = 
								-- 	{
								-- 		["tasks"] = 
								-- 		{
								-- 			["SEAD"] = 1,
								-- 		},
								-- 		["difficult"] = 1,
								-- 		["lastNumMission"] = 3,
								-- 	},
								-- },

								--en fonction du learning des missions passé, interdit une mission si les task support ne sont pas present
								
								local tempInfo = draft[n].id.." AtoG NbTotPlanePerTask CALCUL"
								local draft_availability = deepcopy(aircraft_availability)
								if camp.newTaskPerTarget then
									for tableTargetName, targetTask in pairs(camp.newTaskPerTarget) do
										if tableTargetName == draft[n].target_name and targetTask.tasks then
											
											for taskLearning, value in pairs(targetTask.tasks) do
												for supportTask, supportPart in pairs(draft[n].support) do		
													
													local NbTotPlanePerTask = 0
													
													if supportTask == taskLearning then
														if type(supportPart) == "table" then	
															for _plane, support in pairs(supportPart) do
																
																if type(support) == "table" and not support.SupportMPOveRide then

																	--enleve le nombre de plane du main si le meme type de plane est compté pour le support
																	tempInfo = tempInfo .."\n"..tostring(draft[n].name).." ==? "..tostring(support.name)
																	if draft[n].name == support.name then
																		draft_availability[support.name].unassigned = draft_availability[support.name].unassigned - draft[n].number
																		tempInfo = tempInfo .."\n AtoG NbTotPlanePerTask AA "..supportTask.." ".._plane.." "..support.name.." Need "..draft[n].number.." Dispo: "..draft_availability[support.name].unassigned
																	end

																	draft_availability[support.name].unassigned = draft_availability[support.name].unassigned - support.number

																	tempInfo = tempInfo .."\n AtoG NbTotPlanePerTask BB "..supportTask.." ".._plane.." "..support.name.." Need "..support.number.." Dispo: "..draft_availability[support.name].unassigned

																	if draft_availability[support.name].unassigned >= 0 then
																		NbTotPlanePerTask = NbTotPlanePerTask + support.number
																		
																		tempInfo = tempInfo .."\nAtoG NbTotPlanePerTask CC "..supportTask.." NbTotPlanePerTask: "..NbTotPlanePerTask
																	end

																end
															end
														end
														if NbTotPlanePerTask < 2 then
															support_available = false

															tempInfo = tempInfo .."\nAtoG NbTotPlanePerTask REJETE CC "

															local TabRejected = {}
															TabRejected["sujet"]  = draft[n].id.." "..supportTask.." newTaskPerTarget  AVION TOTAL SUPPORT INSUFFISANT NbTotPlanePerTask <= 0 "
															TabRejected["cause"] = { [1] = NbTotPlanePerTask, [2] = "newTaskPerTarget", }
															TabRejected["ligne"]  = debug.getinfo(1).currentline														
															table.insert(draft[n]["rejected"], TabRejected)
														end

														if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "C") 
														and ( Debug.Generator.SpySquad and Debug.Generator.SpySquad == draft[n].name 
														or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft[n].target_name ))
														then 
															debuGenTxt = debuGenTxt.."\n"..tempInfo 
														end

													end

													-- if supportTask == taskLearning then
													-- 	if type(supportPart) == "table" then	
													-- 		for _plane, support in pairs(supportPart) do
																
													-- 			if type(support) == "table" and not support.SupportMPOveRide then
																	
													-- 				draft_availability[support.name].unassigned = draft_availability[support.name].unassigned - support.number
																	
													-- 				if  draft_availability[support.name].unassigned >= 0 then 
													-- 					support_available = false
																		
													-- 					local TabRejected = {}
													-- 					TabRejected["sujet"]  = draft[n].id.." "..supportTask.." type: "..support.type.." newTaskPerTarget  AVION SUPPORT INSUFFISANTsupport.number < unassigned "
													-- 					TabRejected["cause"] = { [1] = draft_availability[support.name].unassigned, [2] = "newTaskPerTarget", }
													-- 					TabRejected["ligne"]  = debug.getinfo(1).currentline														
													-- 					table.insert(draft[n]["rejected"], TabRejected)
																	
													-- 				end
													-- 			end
													-- 		end
													-- 	end
													-- end	
												end
											end
										end
									end
								end
														
								if not draft[n].MainMPOveRide then
									for unitname,_ in pairs(need) do
										if need[unitname] > avail[unitname] then																						--more aircraft are needed from this unit across all package tasks than are available
											support_available = false																									--not enough support available
										local TabRejected = {}
											TabRejected["sujet"]  = draft[n].id.." type: "..draft[n].type.." AVION SUPPORT INSUFFISANT()support_available if need[unitname] > avail[unitname]"
											TabRejected["cause"] = { [1] =  need[unitname], [2] = avail[unitname], }
											TabRejected["ligne"]  = debug.getinfo(1).currentline														
											table.insert(draft[n]["rejected"], TabRejected)
										end
									end
								end
								-- ATO_G_adjustment01 escort mandatory or not
								-- regarde uniquement pour les bombardiers necessitant une escorte
								
								-- if campMod.StrikeOnlyWithEscorte and not draft[n].loadout.self_escort then
								-- 	if (db_loadouts[draft[n].type]["Anti-ship Strike"] or db_loadouts[draft[n].type]["Strike"])  then	
								-- 		local break_loop = false
								-- 		for n_squad, squad in pairs(oob_air[side]) do
											
								-- 			if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "C") 
								-- 			and ( Debug.Generator.SpySquad and Debug.Generator.SpySquad == draft[n].name 
								-- 			or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft[n].target_name ))
								-- 			then
								-- 				debuGenTxt = debuGenTxt.."\n"..(tostring(draft.id).." AtoG III passe SWE _01 "..draft[n].type.." "..squad.type ) 
								-- 			end
											
								-- 			if draft[n].MainMPOveRide or ((squad.tasks["Anti-ship Strike"]  or squad.tasks["Strike"] ) and squad.type == draft[n].type) then
								-- 				local needSupport = {}																														--collect the total number of aircraft needed from each unit to complete the package																							--number of main body aircraft 
								-- 				local availSupport = {}																													--collect the maximal number of available aircraft from this unit (biggest number of all tasks)
												
								-- 				if not needSupport[draft[n].name] then needSupport[draft[n].name] = 0 end
								-- 				if not availSupport[draft[n].name] then availSupport[draft[n].name] = 0 end
								-- 				needSupport[draft[n].name] =  deepcopy(draft[n].number)	
												
								-- 				--TODO comment ça marche? ça a l'air inutile....
								-- 				availSupport[draft[n].name] =  aircraft_availability[draft[n].name].unassigned
												
								-- 				for _p,_support in pairs(draft[n].support) do																							--iterate through support in draft sortie	
								-- 					if 	type(_support) == "table" then	
								-- 						for _a,support in pairs(_support) do											
								-- 							if 	type(support) == "table" then

								-- 								if not needSupport[support.name] then needSupport[support.name] = 0 end																															
								-- 								if not availSupport[support.name] then availSupport[support.name] = 0 end																
																
								-- 								needSupport[support.name] =  needSupport[support.name] + support.number																	--add number of support aircraft from same unit
								-- 								availSupport[support.name] =  aircraft_availability[support.name].unassigned														
															
								-- 							end
								-- 						end
								-- 					end
								-- 				end		
												
								-- 				--TODO encore utile ça?												
								-- 				for Sname,_ in pairs(needSupport) do 
								-- 					-- print("AtoG NeedName"..Sname.." |Need| "..needSupport[Sname].." |dispo| "..availSupport[Sname])
								-- 					if needSupport[Sname] - (needSupport[Sname] * 0.25)  > availSupport[Sname] then	
								-- 					----more aircraft are needed from this unit across all package tasks than are available
								-- 						-- print("AtoG TabRejected: Necessaire: "..needSupport[Sname].." >  Dispo "..availSupport[Sname])
								-- 						support_available = false																									--not enough support available
								-- 							local TabRejected = {}
								-- 							TabRejected["sujet"]  = draft[n].id.." BOMBARDIER NECESSITANT ESCORTE()support_available if needSupport[Sname] - (needSupport[Sname] * 0.15) > availSupport[Sname]"
								-- 							TabRejected["cause"] = { [1] =  needSupport[Sname] - (needSupport[Sname] * 0.25), [2] = availSupport[Sname], }
								-- 							TabRejected["ligne"]  = debug.getinfo(1).currentline														
								-- 							table.insert(draft[n]["rejected"], TabRejected)
								-- 					end
								-- 				end
								-- 			end
								-- 		end
								-- 	end	
								-- end
								
								if not draft[n].MainMPOveRide and campMod.StrikeOnlyWithEscorte then
									for _p,_support in pairs(draft[n].support) do																							--iterate through support in draft sortie
										if support_available and	type(_support) == "table" then	
											for _,support in pairs(_support) do																							--iterate through support in draft sortie
												if 	type(support) == "table" then	
													if support.number > aircraft_availability[support.name].unassigned then															--not enough aircraft available from this unit for this task
														support_available = false																									--not enough support available
														local TabRejected = {}
														TabRejected["sujet"]  = support.id.." type: "..support.type.." support_available if support.number > aircraft_availability[support.name].unassigned"
														TabRejected["cause"] = { [1] =  support.number, [2] = aircraft_availability[support.name].unassigned, }
														TabRejected["ligne"]  = debug.getinfo(1).currentline														
														table.insert(draft[n]["rejected"], TabRejected)
													end
												end
											end
										end
									end
									
									if support_available and draft[n].loadout.support then																									--main body loadout support requirements
										for supporttype, bool in pairs(draft[n].loadout.support) do																		--iterate through support requirements of loadout
											if (supporttype == "Flare Illumination" or supporttype == "Laser Illumination") and bool then								--Flare Illumination and Laser Illumination is a necessary support type. If it is not present in the draft sortie, no package will be created				
												if draft[n].support[supporttype] == nil then																			--if draft sortie has no such support type assigned
													support_available = false																							--necessary support is not available
												
													local TabRejected = {}
													TabRejected["sujet"]  = draft[n].id.." type: "..support.type.." ILLUMINATION ABSENT()support_available if draft[n].support[supporttype] == nil"
													TabRejected["cause"] = { [1] =  draft[n].support[supporttype], [2] = "", }
													TabRejected["ligne"]  = debug.getinfo(1).currentline														
													table.insert(draft[n]["rejected"], TabRejected)
												end
											end
										end
									end
									
									
									for _p,_support in pairs(draft[n].support) do																							--iterate through support in draft sortie
										if support_available and type(_support) == "table" then	
											for _,support in pairs(_support) do																							--iterate through support in draft sortie
												if 	type(support) == "table" then	
													if aircraft_availability[support.name].unassigned <=0 then
														support_available = false
														
														local TabRejected = {}
														TabRejected["sujet"]  = draft[n].id.." type: "..support.type.." AVION SUPPORT INSUFFISANT()support_available if aircraft_availability[support.name].unassigned <=0"
														TabRejected["cause"] = { [1] = aircraft_availability[support.name].unassigned, [2] = "", }
														TabRejected["ligne"]  = debug.getinfo(1).currentline														
														table.insert(draft[n]["rejected"], TabRejected)
													end
												end
											end
										end
									end	
								end
								
								--si c'est un task d'une demande MP, on chunte la restrition plus loin
								local MultiPlayerOveRide  = false
								if multiPlaneSet[side] and multiPlaneSet[side][draft[n].type] and multiPlaneSet[side][draft[n].type][draft[n].task] then
									MultiPlayerOveRide = true
								
									if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "C") 
									and ( Debug.Generator.SpySquad and Debug.Generator.SpySquad == draft[n].name 
									or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft[n].target_name ))
									then
										debuGenTxt = debuGenTxt.."\n"..(tostring(draft[n].id).." AtoG passe C_01 "..draft[n].type.." "..draft[n].task ) 
									end
								end
							
								if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "C") 
								and ( Debug.Generator.SpySquad and Debug.Generator.SpySquad == draft[n].name 
								or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft[n].target_name ))
								then
									-- aircraft_availability[draft[n].name].serviceable > (aircraft_availability[draft[n].name].available / denom_NeDonnePasTOUT )

									debuGenTxt = debuGenTxt.."\n"..(tostring(draft[n].id).." AtoG passe C_02a serviceable: "
												..tostring(aircraft_availability[draft[n].name].serviceable)
												.." |available: "..tostring(aircraft_availability[draft[n].name].available)
												.." >? "..tostring(aircraft_availability[draft[n].name].available / denom_NeDonnePasTOUT)) 
								end

								-- Miguel21 modification M11.u : Multiplayer	(u: reserve avion Escorte)
								-- interdit aux possible avion d'escorte de tout donner dans CAP ou Intercept
								if not MultiPlayerOveRide and (draft[n].task == "CAP" or draft[n].task == "Intercept" )  and (aircraft_availability[draft[n].name].serviceable > (aircraft_availability[draft[n].name].available / denom_NeDonnePasTOUT )) then	--> (aircraft_availability[draft[n].name].available / 3 ))
									local break_loop = false
									for n_squad, squad in pairs(oob_air[side]) do
										if squad.type == draft[n].type and squad.name == draft[n].name and (squad.tasks["Escort"] or squad.tasks["SEAD"] or squad.name["Strike"] ) then
											-- if aircraft_availability[draft[n].name].unassigned - draft[n].number <= aircraft_availability[draft[n].name].serviceable/2 then
											
											-- local serciMini = 9999
											local serciMini = 3
											if aircraft_availability[draft[n].name].serviceable and aircraft_availability[draft[n].name].serviceable > 2 then
												serciMini = math.random(1,aircraft_availability[draft[n].name].serviceable/2)
											end
											
											

											if aircraft_availability[draft[n].name].unassigned - draft[n].number <= serciMini then
												support_available = false
												
												if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "C") 
												and ( Debug.Generator.SpySquad and Debug.Generator.SpySquad == draft[n].name 
												or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft[n].target_name ))
												then
													debuGenTxt = debuGenTxt.."\n"..(tostring(draft[n].id).." AtoG passe C_02b  "..squad.type.." "..draft[n].task) 
												end
								
								
													local TabRejected = {}
													TabRejected["sujet"]  = draft[n].id.." NE DONNE PAS TOUT en CAP ou Intercept ()support_available if aircraft_availability[draft[n].name].unassigned - draft[n].number <= aircraft_availability[draft[n].name].serviceable/3"
													TabRejected["cause"] = { [1] = aircraft_availability[draft[n].name].unassigned - draft[n].number, [2]  = aircraft_availability[draft[n].name].serviceable/ denom_NeDonnePasTOUT, }
													TabRejected["ligne"]  = debug.getinfo(1).currentline														
													table.insert(draft[n]["rejected"], TabRejected)	
													
												break_loop = true																		
												break
											end
										end
										if break_loop == true then
											break																							
										end
									end
								end
								
								-- ne donne pas tout aux strike si du sead est possible en task escadrille
								--bug avec de petite campagne comme le Tchad
								--TODO prevoir seulement si SEAD prévu, ou pas.
								-- if testCode then
								-- 	if not MultiPlayerOveRide and (draft[n].task == "Strike" or draft[n].task == "Anti-ship Strike" )   then	--and (aircraft_availability[draft[n].name].serviceable > (aircraft_availability[draft[n].name].available / 1.01 ))
								-- 		local break_loop = false
								-- 		for n_squad, squad in pairs(oob_air[side]) do
								-- 			if squad.type == draft[n].type and squad.name == draft[n].name and ( squad.tasks["Escort"] or squad.tasks["SEAD"] or squad.tasks["Laser Illumination"]   ) then --squad.tasks["Fighter Sweep"] or or squad.tasks["Fighter Sweep"]
								-- 				--aircraft_availability[support.name].unassigned
								-- 				if aircraft_availability[draft[n].name].unassigned - draft[n].number <= aircraft_availability[draft[n].name].serviceable / 2 then
								-- 					support_available = false
													
								-- 					if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "C") 
								-- 					and ( Debug.Generator.SpySquad and Debug.Generator.SpySquad == draft[n].name 
								-- 					or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft[n].target_name ))
								-- 					then
								-- 						debuGenTxt = debuGenTxt.."\n"..(tostring(draft[n].id).." AtoG passe C_03  "..draft[n].type.." "..draft[n].task) 
								-- 					end
								-- 						local TabRejected = {}
								-- 						TabRejected["sujet"]  = draft[n].id.." NE DONNE PAS TOUT en Strike ()support_available if aircraft_availability[draft[n].name].unassigned - draft[n].number <= aircraft_availability[draft[n].name].serviceable/6"
								-- 						TabRejected["cause"] = { [1] = aircraft_availability[draft[n].name].unassigned - draft[n].number, [2]  = aircraft_availability[draft[n].name].serviceable/3, }
								-- 						TabRejected["ligne"]  = debug.getinfo(1).currentline														
								-- 						table.insert(draft[n]["rejected"], TabRejected)	
														
								-- 					break_loop = true																		
								-- 					break
								-- 				end
								-- 			end
								-- 			if break_loop == true then
								-- 				break																							
								-- 			end
								-- 		end
								-- 	end
								-- end

								if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "C") 
								and ( Debug.Generator.SpySquad and Debug.Generator.SpySquad == draft[n].name 
								or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft[n].target_name ))
								then
									debuGenTxt = debuGenTxt.."\n"..(tostring(draft[n].id).." AtoG passe C_04  support_available "..tostring(support_available).." MultiPlayerOveRide: "..tostring(MultiPlayerOveRide)) 
								end	
								
								
								if support_available  then																		--continue if no support is required or enough support is available to create package
									--add new package to ATO
									local pack_n = #ATO[side]
									ATO[side][pack_n + 1] = {
										["main"] = {},																			--package main body
										["Escort"] = {},																		--Fighter escort
										["SEAD"] = {},																			--SEAD escort
										["Escort Jammer"] = {},																	--jammer escort
										["Flare Illumination"] = {},															--illumination flare
										["Laser Illumination"] = {},															--laser illumination
										["Strike"] = {},
										["Anti-ship Strike"] = {},
										
									}
									pack_n = pack_n + 1
									
									--add flights of 1, 2 or 4 aircraft to package
									local function AddFlight(assign, role, entry)
										
										

										local assigned
										while assign > 0 do																		--loop as long as there are aircraft to assign
											
											local debugA = ""
											local debugE = ""
											
											if entry.flights then																--for multiple flights with station time (CAP, AWACS, Tanker etc.)
												local flightsize = math.ceil(draft[n].target.firepower.max / draft[n].loadout.firepower)	--how many aircraft should be in each flight
												debugA = "assign: "..assign.." >=? flightsize: "..flightsize
												if assign >= flightsize then													--if there are more aircraft left to assign than the size of one flight
													assigned = flightsize														--assign one full flight
													debugA = debugA .." ||if assign >= flightsize: assigned: "..assigned
												else																			--if there are less aircraft left to assign than size of one flight
													assigned = assign	
													debugA = debugA .." ||else assigned: "..assigned												--assign whatever is left
												end
												entry.flights = entry.flights - 1												--one less flight to assign
												
												debugA = debugA .." ||result entry.flights: "..entry.flights

											elseif entry.task == "Transport" or entry.task == "Escort Jammer" or entry.task == "Flare Illumination" or entry.task == "Laser Illumination" then		--for tasks with single aircraft
												assigned = 1																	--assign one aircraft per flight	
											elseif entry.task == "Intercept" then
												if assign >= 2 then																--if more than 2 aircraft are to be assigned
													assigned = 2																--assign flight of 2 aircaft
												else
													assigned = 1																--else assign flight of 1 aicraft
												end
											elseif entry.type == "S-3B" or entry.type == "F-117A" or entry.type == "B-1B" or entry.type == "B-52H" or entry.type == "Tu-22M3" or entry.type == "Tu-95MS" or entry.type == "Tu-142" or entry.type == "Tu-160" or entry.type == "MiG-25RBT" then	--for bombers
												assigned = 1																	--assigne one aircraft per flight
											elseif entry.task == "Reconnaissance" then											--for recon
												if assign == 1 then																--if there is one aircraft left to assign
													assigned = 1																--assigne one aircraft per flight
												elseif assign >= 4 then															--if more than 4 aircraft are to be assigned
													assigned = 4																--assign flight of 4 aircaft
												elseif assign == 3 then															--if more than 3 aircraft are to be assigned
													assigned = 3																--assign flight of 3 aircaft
												else
													assigned = 2																--else assign flight of 2 aicraft
												end
											elseif (entry.task == "SAR" or entry.task == "CSAR") and not MultiPlayerOveRide then											--for recon
												assigned = 1											
											else																			--for everything else
												debugE = "else BEFORE assigned: if assigned and assign == 1? "..assign
												if assigned and assign == 1 then												--if there is one aircraft left to assign and there was already a previous flight assigned, stop assigning (do not add leftover single-ships)
													break
												elseif assign >= 4 then															--if more than 4 aircraft are to be assigned
													assigned = 4																--assign flight of 4 aircaft
													debugE = debugE .." || elseif assign >= 4 then"
												else
													assigned = assign															--else assign flight size of what is left
												end
												debugE = debugE .. " || elseAFTER assigned: "..assigned
											end

											-- if assign >= 4 then															--if more than 4 aircraft are to be assigned
											-- 	assigned = 4																--assign flight of 4 aircaft
											-- else
											-- 	assigned = assign															--else assign flight size of what is left
											-- end
											
											if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "C") 
											and ( Debug.Generator.SpySquad and Debug.Generator.SpySquad == draft[n].name 
											or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft[n].target_name ))
											then 
												debuGenTxt = debuGenTxt.."\n"..(tostring(draft[n].id).." AtoG passe C_04a   _A_" ..debugA.." \r\n _E_ "..debugE.." \r\n assigned "..assigned) 
											end

											local flight = {																	--build ATO flight entry
												name = entry.name,
												playable = entry.playable,
												type = entry.type,
												callsign = entry.callsign,
												callsignId = entry.callsignId,
												helicopter = entry.helicopter,
												number = assigned,																--number of aircraft in flight
												country = entry.country,
												livery = entry.livery,
												sidenumber = entry.sidenumber,
												liveryModex = entry.liveryModex,
												base = entry.base,
												airdromeId = entry.airdromeId,
												parking_id = entry.parking_id,
												skill = entry.skill,
												task = entry.task,
												loadout = entry.loadout,
												route = {},																		--route is a table and connot be copied as a whole
												target = deepcopy(entry.target),
												target_name = entry.target_name,
												firepower = assigned * entry.loadout.firepower,
												tot_from = entry.tot_from,
												tot_to = entry.tot_to,
												id = entry.id,
											}
											for r = 1, #entry.route do															--make copy of route table
												flight.route[r] = {}
												for k,v in pairs(entry.route[r]) do
													flight.route[r][k] = v
												end
											end
											
											if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "C") 
											and ( Debug.Generator.SpySquad and Debug.Generator.SpySquad == draft[n].name 
											or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft[n].target_name ))
											then 
												debuGenTxt = debuGenTxt.."\n"..(tostring(draft[n].id).." AtoG passe C_05a number "..assigned.." "..entry.task) 
											end
										

											if multiPlaneSet and multiPlaneSet[side] and multiPlaneSet[side][draft[n].type]  and multiPlaneSet[side][draft[n].type][draft[n].task]  then
											
												multiPlaneSet[side][draft[n].type][draft[n].task].NbPlane = multiPlaneSet[side][draft[n].type][draft[n].task].NbPlane - assigned
												
												if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "C") 
												and ( Debug.Generator.SpySquad and Debug.Generator.SpySquad == draft[n].name 
												or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft[n].target_name ))
												then 
													debuGenTxt = debuGenTxt.."\n"..(tostring(draft[n].id).." AtoG passe C_05b (NbPlane - assigned) "..multiPlaneSet[side][draft[n].type][draft[n].task].NbPlane) 
												end
											end

											--###################################################################
											--#############"" insert/create ATO table ###########################
											
											table.insert(ATO[side][pack_n][role], flight)										--add flight to package role (main, SEAD or escort)											
											
											--#############"" insert/create ATO table ###########################
											--###################################################################

											--store time assigned aircraft are unavailable for future missions
											local operating_hours														--time the unit is operating each day
											if entry.loadout.day and entry.loadout.night then							--day/night loadout
												operating_hours = 86400													--full day in seconds
											elseif entry.loadout.day then												--day loadout
												operating_hours = camp.dusk - camp.dawn									--daytime in seconds
											elseif entry.loadout.night then												--night loadout
												operating_hours = camp.dawn + (86400 - camp.dusk)						--nighttime in seconds
											end
											local time_to_next_mission = operating_hours / entry.loadout.sortie_rate	--time duration until aircraft can do the next mission based on its sortie rate
											if entry.loadout.tStation and #ATO[side][pack_n][role] == 1 then			--for a flight that has a station time and for the first flight in package
												time_to_next_mission = time_to_next_mission - entry.loadout.tStation	--remove station time from time to next mission, because flight could airstart current mission at close to end of its station time
											end
											local current_time = (camp.day - 1) * 86400 + camp.time						--current absolute campaign time
											local unavailable = current_time + time_to_next_mission 					--campaign time until this aircraft unavailable for new mission
											for a = 1, assigned do														--iterate through all assigned aircraft
												if #aircraft_availability[entry.name].unavailable == 0 then
													table.insert(aircraft_availability[entry.name].unavailable, unavailable)						--insert unavailable time into unavailable table of this unit
												else
													for u = 1, #aircraft_availability[entry.name].unavailable do
														if unavailable > aircraft_availability[entry.name].unavailable[u] then
															table.insert(aircraft_availability[entry.name].unavailable, u, unavailable)				--insert unavailable time into unavailable table of this unit sorted from highest to lowest
															break
														elseif u == #aircraft_availability[entry.name].unavailable then
															table.insert(aircraft_availability[entry.name].unavailable, u + 1, unavailable)			--insert unavailable time into unavailable table of this unit sorted from highest to lowest
														end
													end
												end
											end
											
											aircraft_availability[entry.name].assigned = aircraft_availability[entry.name].assigned + assigned
											aircraft_availability[entry.name].unassigned = aircraft_availability[entry.name].unassigned - assigned		--remove assigned aircraft from total number of available aircraft for this unit
											assign = assign - assigned															--continue loop until are aircraft are assigned
										
										
											if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "C") 
											and ( Debug.Generator.SpySquad and Debug.Generator.SpySquad == draft[n].name 
											or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft[n].target_name ))
											then 
												debuGenTxt = debuGenTxt.."\n"..(tostring(draft[n].id).." AtoG passe C_05b   assign "..assign.." type: "..entry.type.." unassigned: "..aircraft_availability[entry.name].unassigned) 
											end
										
										end
									end
									
									if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "C") 
									and ( Debug.Generator.SpySquad and Debug.Generator.SpySquad == draft[n].name 
									or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft[n].target_name ))
									then 
										debuGenTxt = debuGenTxt.."\n"..(tostring(draft[n].id).." AtoG passe C_06b  number "..tostring(draft[n].number)) 
									end	
									
									AddFlight(draft[n].number, "main", draft[n])												--add main body flights to package
									
									for support_name, supportPart in pairs(draft[n].support) do										--iterate through all package support
										if type(supportPart) == "table" then	
											for _plane, support in pairs(supportPart) do
												local number  = 0
												if type(support) == "table" and (support.SupportMPOveRide or aircraft_availability[support.name].unassigned >= 2) then
													
													if support.number >= aircraft_availability[support.name].unassigned then 
														number = aircraft_availability[support.name].unassigned 
													end
													if support.number < aircraft_availability[support.name].unassigned then 
														number = support.number 
													end
													
													if support.SupportMPOveRide then number = support.number end
														
													if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "C") 
													and ( Debug.Generator.SpySquad and Debug.Generator.SpySquad == draft[n].name 
													or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft[n].target_name ))
													then
														debuGenTxt = debuGenTxt.."\n"..(tostring(draft[n].id).." AtoG passe C_07  numberFINAL "..tostring(number).." support_name: "..support_name.." unassigned: "..tostring(aircraft_availability[support.name].unassigned)) 
													end	
									
													AddFlight(number, support_name, support)										--add support flights to package
						
												else
													if type(support) ~= "table" then
														txt0 = "support != table "
															.." OveRide?: "..tostring(draft[n].MainMPOveRide)
															.." type: "..tostring(draft[n].type)
															.." key: "..tostring(_plane)
															.." supportPart(_plane): "..tostring(supportPart[_plane]) 
															.." support: "..tostring(support) 
															.." supportPart: "..tostring(supportPart) 
															.." || "
														
															if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "C") 
															and ( Debug.Generator.SpySquad and Debug.Generator.SpySquad == draft[n].name 
															or (Debug.Generator.SpyTarget and Debug.Generator.SpyTarget == draft[n].target_name ))
															then
																debuGenTxt = debuGenTxt.."\n"..(tostring(draft[n].id).." AtoG passe C_08")
																debuGenTxt = debuGenTxt.."\n"..(txt0)
																-- _affiche(supportPart, "supportPart")
															end	
															
													else
														
														txt0 = draft[n].id.." IN AddFlight unassigned < 2 "
															.." OveRide?: "..tostring(draft[n].MainMPOveRide)
															.." "..tostring(draft[n].type) 
															.." "..tostring(support.type)
															.." "..tostring(support.name)
															.." || "

															local TabRejected = {}
														TabRejected["sujet"]  = txt0
														TabRejected["cause"] = { [1] = support_available, [2]  = "", }
														TabRejected["ligne"]  = debug.getinfo(1).currentline
														table.insert(draft[n]["rejected"], TabRejected)
													end
												end
											end
										else
											local TabRejected = {}
											TabRejected["sujet"]  = draft[n].id.." IN AddFlight type(supportPart) == table"
											TabRejected["cause"] = { [1] = support_available, [2]  = "", }
											TabRejected["ligne"]  = debug.getinfo(1).currentline
											table.insert(draft[n]["rejected"], TabRejected)
										end
									end
															
									--remove the firepower applied by package to target from maximum firepower of all other draft sorties to the same target
									local firepower_applied = 0																	--collect the amount of firepower combined by all main body flights of this package
									for f = 1, #ATO[side][pack_n].main do														--iterate through all main body flights
										firepower_applied = firepower_applied + ATO[side][pack_n].main[f].firepower				--sum firepower
									end
									for m = 1, #draft do																		--iterate through all draft sorties again
										if draft[n].target_name == draft[m].target_name then									--if draft sortie with same target as present package is found
											if draft[m].multipack then															--target has a fixed requirement for number of packages 
												draft[m].multipack = draft[m].multipack - 1										--reduce number of packages per one
												if draft[m].target.firepower.packmin then											--target has a fixed requirement for minimal number of packages 
													draft[m].target.firepower.packmin = draft[m].target.firepower.packmin - 1		--reduce number of minimal packages per one
												end
											else																				--target is stricly firepower controlled
												draft[m].target.firepower.max = draft[m].target.firepower.max - firepower_applied	--remove the firepower applied by current package from maximum firepower for this sortie
												draft[m].number = math.ceil(draft[m].number - (firepower_applied / draft[m].loadout.firepower))	--reduce the number of aircraf to be assigned to this sortie as a result of the firepower reduction
											end
										end
									end
									
									--status report
									status_counter_ATO = status_counter_ATO + 1
									--print("ATO Generation (" .. status_counter_ATO .. ")")	--DEBUG
								else
									local TabRejected = {}
									TabRejected["sujet"]  = draft[n].id.." SUPPORT IMPOSSIBLE()if support_available"
									TabRejected["cause"] = { [1] = support_available, [2]  = "", }
									TabRejected["ligne"]  = debug.getinfo(1).currentline
									table.insert(draft[n]["rejected"], TabRejected)
								end
							else
								local TabRejected = {}
								TabRejected["sujet"]  = draft[n].id.." AVIONS INSUFFISANT()if draft[n].number <= available and limitMP then {draft[n].number, limitMP}"
								TabRejected["cause"] = {draft[n].number, limitMP}
								TabRejected["ligne"]  = debug.getinfo(1).currentline
								table.insert(draft[n]["rejected"], TabRejected)
							end
						else
							--if draft[n].target.firepower.packmin == nil or available * draft[n].loadout.firepower >= (draft[n].target.firepower.packmin - 1) * draft[n].target.firepower.max + draft[n].target.firepower.min
							local TabRejected = {}
							TabRejected["sujet"]  = draft[n].id.." FIREPOWER du PACKAGE INSUFFISANT()if  available * draft[n].loadout.firepower >= (draft[n].target.firepower.packmin - 1) * draft[n].target.firepower.max"
							TabRejected["cause"] = { [1] = available * draft[n].loadout.firepower, [2]  = (draft[n].target.firepower.packmin - 1) * draft[n].target.firepower.max, }
							TabRejected["ligne"]  = debug.getinfo(1).currentline
							table.insert(draft[n]["rejected"], TabRejected)
						end
					else
						local TabRejected = {}
						TabRejected["sujet"]  = draft[n].id.." "..tostring(draft[n].type).."AVION DISPONIBLE INSUFFISANT ()if available * draft[n].loadout.firepower >= draft[n].target.firepower.min and draft[n].number * draft[n].loadout.firepower >= draft[n].target.firepower.min"
						TabRejected["cause"] = { [1] = available * draft[n].loadout.firepower, [2]  = draft[n].target.firepower.min, }
						TabRejected["ligne"]  = debug.getinfo(1).currentline
						table.insert(draft[n]["rejected"], TabRejected)
					end
				else
					local TabRejected = {}
					TabRejected["sujet"]  = draft[n].id.." FIREPOWER INSUFFISANT (a augmenter dans loadout)if draft[n].target.firepower.max > 0 and draft[n].target.firepower.max >= draft[n].target.firepower.min"
					TabRejected["cause"] = { [1] = draft[n].target.firepower.max, [2]  = draft[n].target.firepower.max, }
					TabRejected["ligne"]  = debug.getinfo(1).currentline
					table.insert(draft[n]["rejected"], TabRejected)
				end
			else
				local TabRejected = {}
				TabRejected["sujet"]  = draft[n].id.." MultiPACKAGE A 0 (?)if draft[n].multipack == nil or draft[n].multipack > 0 || target_name: "..tostring(draft[n].target_name).." || multipack: " ..tostring(draft[n].multipack)
				TabRejected["cause"] = { [1] = draft[n].multipack, [2]  = draft[n].multipack, }
				TabRejected["ligne"]  = debug.getinfo(1).currentline
				table.insert(draft[n]["rejected"], TabRejected)
			end
		else 
			local TabRejected = {}
			TabRejected["sujet"]  = draft[n].id.." MENACE TROP IMPORTANTE (descendre minscore ou diminuer Menace AA AS) draft[n].loadout.minscore <= draft[n].score"
			TabRejected["cause"] = { [1] = draft[n].loadout.minscore, [2]  = draft[n].score, }
			TabRejected["ligne"]  = debug.getinfo(1).currentline
			table.insert(draft[n]["rejected"], TabRejected)	
		end
	end
end

if Debug.Generator.affiche then	--and string.find(Debug.Generator.chapter, "C") 
	
	local ShowSquad 
	local ShowTarget 
	
	if Debug.Generator.SpySquad then
		ShowSquad = Debug.Generator.SpySquad
	end
	if Debug.Generator.SpyTarget  then
		ShowTarget = Debug.Generator.SpyTarget
	end

	
	-- local ShowSquad = "111.Filo"
	
	for side, sorties in pairs(draft_sorties) do	
		local di = 1 
		debuGenTxt = debuGenTxt.."\n"..(side.."  PART C")
		for draft_n, draft in pairs(sorties) do	
			local NameOK = false
			if draft.target_name == ShowTarget then
				NameOK = true
			end
			for _PlaneTask, PlaneTask in pairs(draft.support) do
				for taskName, task in pairs(PlaneTask) do	
					if type(task) == "table" then
						if task.name == ShowSquad  then
							NameOK = true
						end
					end
				end
			end	
						
			if  di < Debug.Generator.nb or draft.name == ShowSquad or NameOK  then
				debuGenTxt = debuGenTxt.."\n"..(	"C N° " .. draft_n..
						-- " /support/ " ..tostring(draft.support)..
						" /Id" ..tostring(draft.id)..
						" /name/ " ..draft.name..
						" /Nb/ " ..draft.number..
						" /Type/ "..draft.type..
						" /Tot_to/ "..draft.tot_to ..
						" /threatsGround/ "..round(draft.threatsGround)..
						" /threatsAir/ "..round(draft.threatsAir)..
						" /Score/ " ..round(draft.score)..
						" /Task/ "..draft.task..
						" /Target/ "..tostring(draft.target_name)
						)
				di = di +1
				for _PlaneTask, PlaneTask in pairs(draft.support) do
					for taskName, task in pairs(PlaneTask) do	
						if type(task) == "table" then	
							debuGenTxt = debuGenTxt.."\n"..(	"    ---> Nsupport " .._PlaneTask.." ".. taskName..
									" /Id" ..tostring(task.id)..
									" /name/ " ..task.name..
									" /Nb/ " ..task.number..
									" /escort_max/ " ..tostring(PlaneTask.escort_max)..
									" /Type/ "..task.type..
									" /Task/ "..task.task..
									" /NbTotSupt/ " ..tostring(task.NbTotalSupport)..
									" /Target/ "..task.target_name
									)
						end
					end
				end
				if draft.rejected then
					for id, _rejected in pairs(draft.rejected) do
						debuGenTxt = debuGenTxt.."\n"..(	" rejected/ ".._rejected.sujet..
							" / cause " ..tostring(_rejected.cause[1])..
							" "..tostring(_rejected.cause[2])..
							" / ligne " ..tostring(_rejected.ligne)
							)
					end
				end
				debuGenTxt = debuGenTxt.."\n"
			end
		end
	end
end

--complete unit unavailable table with zero entries for unassigned aircraft
for side,unit in pairs(oob_air) do																					--iterate through all sides
	for n = 1, #unit do																								--iterate through all units
		if aircraft_availability[unit[n].name] and aircraft_availability[unit[n].name].unavailable then
			for u = 1, unit[n].roster.ready - #aircraft_availability[unit[n].name].unavailable do					--for all ready aircraft that are not assigned to the ATO			
				table.insert(aircraft_availability[unit[n].name].unavailable, 0)									--insert a zero unavilable entry
			end
		end
	end
end


if Debug.Generator.affiche and string.find(Debug.Generator.chapter, "C") then	
	
	local camp_str = "ATO = " .. TableSerialization(ATO, 0)						--make a string
	local campFile = io.open("Debug/ATO_AtoGenerator.lua", "w")										--open targetlist file
	campFile:write(camp_str)																		--save new data
	campFile:close()

	local camp_str = "camp = " .. TableSerialization(camp, 0)						--make a string
	local campFile = io.open("Debug/CAMP_Ato_Generator.lua", "w")										--open targetlist file
	campFile:write(camp_str)																		--save new data
	campFile:close()
end

--place la clef occurence à tous les loadouts
for plane, planeTab  in pairs(db_loadouts_archive) do
	for taskName, loadout  in pairs(planeTab) do
		for loadoutName, value  in pairs(loadout) do																													
			if type(value) == "table" then
				if not value["occurence"] then value["occurence"] = 0 end
			end
		end
	end
end


-- miguel21 modification M49.c big central db_loadout (c: loadout statistics)
local found = false
for side, pack in pairs(ATO) do	
	for p = 1, #pack do	
		for role,flight in pairs(pack[p]) do
			for f = 1, #flight do
				local found = false
				for plane, planeTab  in pairs(db_loadouts_archive) do
					if plane == flight[f].type then
						for taskName, loadout  in pairs(planeTab) do
							for loadoutName, value  in pairs(loadout) do																										
								if loadoutName  == flight[f].loadout.name then					
									if not value["occurence"] or value["occurence"] == nil or value["occurence"] == " " then value["occurence"] = 0 end		
									value["occurence"] = value["occurence"] + 1																										
									found = true																											
									break																											
								end																										
								if found then break end
							end
							if found then break end
						end
						if found then break end
					end
					if found then break end
				end
			end
		end
	end
end


local s = ""
--place la clef occurence à tous les loadouts
for plane, planeTab  in pairs(db_loadouts_archive) do
	for taskName, loadout  in pairs(planeTab) do
		for loadoutName, value  in pairs(loadout) do																																			
			if type(value) == "table" then				
				s = s.."\n"
				s = s..plane
				for i=1, 15 - string.len(plane) do
					s = s.." "
				end

				s = s..taskName
				for i=1, 20 - string.len(taskName) do
					s = s.." "
				end

				if value.occurence == 0 then
					value.occurence = " "
				end
				s = s..value.occurence
				for i=1, 5 - string.len(value.occurence) do
					s = s.." "
				end
				
				local minsCore = ""
				if value.minscore then minsCore = value.minscore end

				s = s..minsCore
				for i=1, 5 - string.len(minsCore) do
					s = s.." "
				end	

				s = s..loadoutName				
			end
		end
	end
end

if Debug.Generator.affiche then
	local debugGenMFile = io.open("Debug/debugGenerator.txt", "w")										--open targetlist file
	debugGenMFile:write(debuGenTxt)																		--save new data
	debugGenMFile:close()
end

--*****************ne pas effacer commenter**********************	
local loadoutSTR = StringToTxt(s)
local dloadoutFile = io.open("Debug/SUM_dloadoutFile.lua", "w")										--open targetlist file
dloadoutFile:write(loadoutSTR)																		--save new data
dloadoutFile:close()
--***************ne pas effacer commenter	**************************


local camp_str = "ATO_ATO_PA = " .. TableSerialization(ATO, 0)						--make a string
local campFile = io.open("Debug/ATO_AtoGenerator.lua", "w")										--open targetlist file
campFile:write(camp_str)																		--save new data
campFile:close()
				