--To generate a new mission file. Unzips template mission, defines content of next missions and packs a new mission file
--Initiated by Debrief_Master.lua, BAT_FirstMission.lua or BAT_RedoMission.lua
------------------------------------------------------------------------------------------------------- 
-- last modification:  M63_a
if not versionDCE then versionDCE = {} end
versionDCE["MAIN_NextMission.lua"] = "1.30.122"
------------------------------------------------------------------------------------------------------- 
-- debug_e 							(e camp_ZoneSAR in skipmod)(d: oob_ground not in mission)(c: EndMission)
-- Reglage_c						(c stop si < 2.7.0 (ver18))(a: Init/loadout selection)
-- adjustment_a						(a: add Loadout tiers)
-- cleanCode_e
-- Miguel21 modification M63_a		compatible Datacard Generator or CombatFlite
-- Miguel21 modification M62_a		allows you to use third party files that Data information without being overwritten by central information updates
-- Miguel21 modification M61_a		SAR
-- miguel21 modification M60_c		add CTLD (c load_CTLD option)(b debug)
-- Psyko modification M59_a			silences the tower
-- Norman99 modification M57_a		Simple Fuel Check Script
-- miguel21 modification M56_a		AssignCallnameSquad
-- miguel21 modification M53_a		automatic update of the conf_mod file
-- Miguel21 modification M52_a		campaign player's choices 
-- miguel21 modification M51_a		Moonphase
-- miguel21 modification M49_f		big central db_loadout (f: detection automatique du codeNom)(d: tag in conf_mod)(ce: loadout statistics)(b: archive)
-- miguel21 modification M48_e		Accept result mission (e: debug horaire)(d: garde en memoire le txt camp["briefing_text"])
-- miguel21 modification M47_c		keeps the history of the campaign files (c: save debugging information during mission generation)
-- Miguel21 modification M40_k		Template Active GroundGroup moving front (k: update Active/db_airbase)
-- miguel21 modification M40		Pedro
-- Miguel21 modification M38_k		Check and Help CampaignMaker (ijk: debug)(h: KillTarget step by step)
-- miguel21 modification M37_d		SuperCarrier
-- Miguel21 modification M35_d		(d: info log) version ScriptsMod
-- Miguel21 modification M36_d		(d: add timer) MenuRadio request manual TurnIntoWind
-- miguel21 modification M34_b		custom FrequenceRadio (b: move file location)
-- Miguel21 modification M29		AddCommandRadioF10 CallTankRefuel
-- Miguel21 modification M26		destroys targets if below a certain value
-- miguel21 modification M18_e		despawn (e: option confMod)
-- Miguel21 modification M17_f		add AddPropAircraft Option all type
-- Miguel21 modification M11A_v		Multiplayer (u: AltitudeFloor in UTIL_Data) (t: AltitudeFloor)
-- Miguel21 modification M14_c		Versionning(c: use changelog.lua)
-- Tomsk    modification M09_b		Integration de  Prune Script
-- Miguel21 modification M05_c		ajout picture Briefing (c: correction path vide)
-- Miguel21 modification M00_b		Integration de conf_mod
-- -------------------------------------------------------------------------------------------------------

flag_MainNextMission = true
flag_MainAcceptMission = false

--Check_TaskPossibleByPlane
----- unpack template mission file ----
local minizip = require('minizip')

local zipFile = minizip.unzOpen("Init/base_mission.miz", 'rb')

zipFile:unzLocateFile('mission')
local misStr = zipFile:unzReadAllCurrentFile()
local misStrFunc = loadstring(misStr)()

zipFile:unzLocateFile('options')
local optStr = zipFile:unzReadAllCurrentFile()
local optStrFunc = loadstring(optStr)()

zipFile:unzLocateFile('warehouses')
local warStr = zipFile:unzReadAllCurrentFile()
local warStrFunc = loadstring(warStr)()

zipFile:unzLocateFile('l10n/DEFAULT/dictionary')
local dicStr = zipFile:unzReadAllCurrentFile()
local dicStrFunc = loadstring(dicStr)()

zipFile:unzLocateFile('l10n/DEFAULT/mapResource')
local resStr = zipFile:unzReadAllCurrentFile()
local resStrFunc = loadstring(resStr)()

zipFile:unzClose()

if mission.version < 19 then --19ok 18bad
	print("(MainNM) ATTENTION: BaseMission.miz is too old. (prior to DCS version 2.7.0) try to save it again with the mission editor. Or ask the creator of this campaign to provide an update.")
	os.execute 'pause'
	os.exit()
end

NameTheatre =  string.lower(mission.theatre)

---- add trigger to destory scenery objects -----
mission.trig.flag[1] = true
mission.trig.conditions[1] = "return(true)"
mission.trig.actions[1] = ""
mission.trig.funcStartup[1] = "if mission.trig.conditions[1]() then mission.trig.actions[1]() end"
mission.trigrules[1] = {
	["rules"] = {},
	["eventlist"] = "",
	["actions"] = {},
	["comment"] = "Scenery Destruction",
	["predicate"] = "triggerStart",
}

require("Active/oob_scen")
for scen_name,scen in pairs(oob_scen) do											--iterate through destroyed scenery objects
	if scen.x and scen.z then														--destroyed scenery object has x and z coordinates
		
		local zones_n = #mission.triggers.zones	+ 1									--trigger zone number
		
		--add trigger zone
		mission.triggers.zones[zones_n] = {
			["x"] = scen.x,
			["y"] = scen.z,
			["radius"] = 1,
			["zoneId"] = zones_n,
			["color"] = 
			{
				[1] = 1,
				[2] = 1,
				[3] = 1,
				[4] = 0.15,
			},
			["hidden"] = true,
			["name"] = "SceneryDestroyZone" .. #mission.trigrules[1].actions + 1,
		}

		--add trigger
		mission.trig.actions[1] = mission.trig.actions[1] ..  "a_scenery_destruction_zone(" .. zones_n .. ", 100);"
		
		mission.trigrules[1].actions[#mission.trigrules[1].actions + 1] = {
			["ai_task"] = {
				[1] = "",
				[2] = "",
			},
			["predicate"] = "a_scenery_destruction_zone",
			["destruction_level"] = 100,
			["zone"] = zones_n,
		}
	end
end

----- prepare triggers to run files in mission -----
local trig_n = 1
local function AddFileTrigger(filename, cond0, predicat0)
	local cond = ""
	local rule = ""
	if not cond0 then
		cond = "return(true)"
		rule = nil
	else 
		cond = "return(c_time_after("..tostring(cond0)..") )"
		rule = {
			['predicate'] = 'c_time_after',
			['seconds'] = cond0,
		}
	end

	local predicate = ""
	if not predicat0 then
		predicate = "triggerStart"

	else 
		predicate =predicat0
	end
	
	trig_n = trig_n + 1
	mapResource["ResKey_Action_" .. trig_n] = filename
	mission.trig.funcStartup[trig_n] = "if mission.trig.conditions[" .. trig_n .. "]() then mission.trig.actions[" .. trig_n .. "]() end"
	mission.trig.flag[trig_n] = true
	mission.trig.conditions[trig_n] = cond																			--"return(true)"
	mission.trig.actions[trig_n] = "a_do_script_file(getValueResourceByKey('ResKey_Action_" .. trig_n .. "'));"		-- Miguel21 modification M11 : Multiplayer
	mission.trigrules[trig_n] = {
		['rules'] = { rule },
		['eventlist'] = '',
		['comment'] = 'Trigger ' .. trig_n,
		['predicate'] = predicate,
		['actions'] = {
			[1] = {
				['file'] = 'ResKey_Action_' .. trig_n,
				['predicate'] = 'a_do_script_file',
				['ai_task'] = {
					[1] = '',
					[2] = '',
				},
			},
		},
	}
end


----- prepare triggers to run files in mission with tempo-----
function AddFileTriggerTempo(filename, time, predicat0, ActionPredicate0)

	local Table_trigrulesAction = {}
	local trig_n =  #mission.trig.actions + 1										--next available trigger number
	local s = ""

	for key, value in ipairs(ActionPredicate0) do
		local  trigrulesAction = {}
		
		if value.Predicate == "a_do_script_file" then
			trigrulesAction = {
				["file"] = 'ResKey_Action_' .. trig_n,
				["predicate"] = 'a_do_script_file',
			}
				
		elseif value.Predicate == "a_do_script"   then
			trigrulesAction = {
				-- ["text"] = "ctld.JTACAutoLase('JTAC1', 1688, true,\"all\",1)",
				["text"] = "ctld.JTACAutoLase(\""..value.NameJTAC.."\", 1688, true,\\\"all\\\",1)",
				["predicate"] = "a_do_script",
				["ai_task"] = 
				{
					[1] = "",
					[2] = "",
				}
			}
			s = s.."a_do_script(\\\"ctld.JTACAutoLase(\\\'"..value.NameJTAC.."\\\', 1688, true,\\\\\"all\\\\\",1)\");" 
		end
		
		table.insert(Table_trigrulesAction, trigrulesAction)
	end
	
	
	if filename and filename ~= "" then
		mapResource["ResKey_Action_" .. trig_n] = filename
		mission.trig.actions[trig_n] = 'a_do_script_file(getValueResourceByKey(\"ResKey_Action_'..trig_n..'\")); mission.trig.func[' .. trig_n .. ']=nil;'
	else
		--[3] = "a_do_script(\"ctld.JTACAutoLase('JTAC1', 1688, false,\\\"all\\\")\"); mission.trig.func[3]=nil;",		
		-- [11] = "a_out_text_delay(getValueDictByKey(\"DictKey_12\"), 10, false, 0);a_do_script(\"ctld.JTACAutoLase('JTAC1', 1688, true,\\\"all\\\",1)\");a_do_script(\"ctld.JTACAutoLase('JTAC2', 1677, true,\\\"all\\\",2)\"); mission.trig.func[11]=nil;",

		mission.trig.actions[trig_n] = s..' mission.trig.func[' .. trig_n .. ']=nil;'
		
	end

	mission.trig.func[trig_n] = "if mission.trig.conditions[" .. trig_n .. "]() then mission.trig.actions[" .. trig_n .. "]() end"
	mission.trig.flag[trig_n] = true
	mission.trig.conditions[trig_n] = "return(c_time_after(" .. time .. ") )"
	
	mission.trigrules[trig_n] = {
		['rules'] = {
			[1] = {
				["seconds"] = time,
				["predicate"] = "c_time_after",
			},
		},
		['eventlist'] = '',
		['comment'] = 'Trigger ' .. trig_n,
		['predicate'] = predicat0,
	
	}
	mission.trigrules[trig_n]['actions'] = Table_trigrulesAction
	
	-- table.insert(mission.trigrules[trig_n]['actions'], trigrulesAction)
end

AddFileTrigger("camp_status.lua")
AddFileTrigger("EventsTracker.lua")
AddFileTrigger("AddCommandRadioF10.lua")											-- Miguel21 Modification	M29
AddFileTrigger("Fuel_Check.lua")													-- Norman99 Modification	M57
AddFileTrigger("ATC_ShutUp_GENERIC.lua")											-- Psyko Modification		M59
AddFileTrigger("GCIdata.lua")
AddFileTrigger("GCIscript.lua")
AddFileTrigger("ARM_Defence_Script.lua")
AddFileTrigger("CustomTasksScript.lua")
AddFileTrigger("CarrierIntoWindScript.lua")
AddFileTrigger("Pedro.lua")															-- miguel21 modification M40 Pedro
AddFileTrigger("SAR.lua")															-- Miguel21 modification M61 SAR
AddFileTrigger("Cercle_City.lua")													-- Miguel21 modification M61 SAR

if mission_ini.load_mist then
	AddFileTriggerTempo("mist.lua", 2, "triggerOnce", { [1] = {["Predicate"] = "a_do_script_file"}})	-- miguel21 modification M60 CTLD
end
if mission_ini.load_CTLD then
	AddFileTriggerTempo("CTLD.lua", 4, "triggerOnce", { [1] = {["Predicate"] = "a_do_script_file"}})	-- miguel21 modification M60 CTLD
end
----- run scripts to create content of next mission -----
dofile("../../../ScriptsMod."..versionPackageICM.."/UTIL_Data.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/UTIL_DataMap.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/UTIL_Functions.lua")

if 	not mission_ini  or mission_ini == nil  then
	dofile("Init/conf_mod.lua")	
end
local needUpdate = CheckConfModMaster()													-- miguel21 modification M38.d Check and Help CampaignMaker

if needUpdate > 0 then																		-- miguel21 modification M53_a	automatic update of the conf_mod file	
	UpdateConfMod()
end

camp.SC_FullPlaneOnDeck = mission_ini.SC_FullPlaneOnDeck								-- miguel21 modification M37.d SuperCarrier
camp.CVN_Vmax = mission_ini.CVN_Vmax													-- miguel21 modification M37.d SuperCarrier
camp.CVN_windDeck = mission_ini.CVN_windDeck											-- miguel21 modification M37.d SuperCarrier
camp.CVN_despawnAfterLanding = mission_ini.CVN_despawnAfterLanding						-- miguel21 modification M18.e despawn (e: option confMod)
camp.SC_CarrierIntoWind = string.lower(mission_ini.SC_CarrierIntoWind)					-- Miguel21 modification M36.d	MenuRadio request manual TurnIntoWind
camp.debug = Debug.debug
camp.debugInGamePopup = Debug.debugInGamePopup

nbTotalClient = 0
for k=1, Multi.NbGroup do
	nbTotalClient = nbTotalClient + Multi.Group[k].NbPlane
end


-- applique SilenceATC si true et si auto (multi >= 2)									---- Psyko modification M59_a			silences the tower
if mission_ini.SilenceATC and type(mission_ini.SilenceATC) == "boolean" then
	camp.SilenceATC = true
elseif  mission_ini.SilenceATC == "auto" and nbTotalClient >= 2 then
	camp.SilenceATC = true
else
	camp.SilenceATC = false
end
	

local verScriptsModPath = "../../../ScriptsMod."..versionPackageICM.."/UTIL_Changelog.lua"
local TestPath = io.open(verScriptsModPath, "r")
if  TestPath ~= nil then
	io.close(TestPath)
	dofile("../../../ScriptsMod."..versionPackageICM.."/UTIL_Changelog.lua")
	camp.ScriptsMod = versionDCE["UTIL_Changelog.lua"]
	
else 

	local verScriptsModPath = "../../../ScriptsMod."..versionPackageICM.."/UTIL_Version.lua"
	local TestPath = io.open(verScriptsModPath, "r")
	if  TestPath ~= nil then
		io.close(TestPath)
		dofile("../../../ScriptsMod."..versionPackageICM.."/UTIL_Version.lua")
		camp.ScriptsMod = version_ScriptsMod.ScriptsMod	
	end	
	
end




if not camp.path or camp.path == nil then												-- Miguel21 modification M35.d version ScriptsMod
	camp.path = os.getenv('pathSavedGames')												-- Miguel21 modification M35.e version ScriptsMod
	camp.path = string.gsub(camp.path, "\\", "/") 
end

-- Miguel21 modification M35.d (d: info log) version ScriptsMod
camp["versionPackageICM"] = versionPackageICM

if FirstMission then 
	camp["MissionFilename"] =  camp.title.."_first.miz"	
else
	camp["MissionFilename"] =  camp.title.."_ongoing.miz"	
end


-- if  mission_ini.SelectLoadout == "init" then
-- 	require("Init/db_loadouts")
-- else
-- 	-- charge le loadout central en premier pour avoir la table de code_loadout
-- 	dofile("../../../ScriptsMod."..versionPackageICM.."/UTIL_db_loadouts.lua")	
-- end


-- 	if add_campaigns_code_loadout then
-- 		for codeName , name in pairs(add_campaigns_code_loadout) do
-- 			if not campaigns_code_loadout[codeName] then
-- 				campaigns_code_loadout[codeName] = name
-- 			end

-- 		end
-- 	end
-- end

-- -- cherche le code a appliquer au loadout, pour charger le bon..loadout ^^
-- if (not ( campConfMod and  campConfMod.code_loadout) and campaigns_code_loadout )then 
-- 	campConfMod = {}
-- 	local maxOcc = 0
-- 	for codeName , name in pairs(campaigns_code_loadout) do			
-- 		local j = 0
-- 		if type(name) == "table" then
-- 			for i=1, #name do
-- 				if  string.find(string.lower(camp.title) , string.lower(name[i])) then
-- 					j = j +1 
-- 					if j == #name and #name > maxOcc then						-- il a trouv� toutes les occurences du nom
-- 						campConfMod.code_loadout = codeName
-- 						maxOcc = #name											--assigne le nomCode seulement � celui qui a le plus d'occurence
-- 					end
-- 				end
-- 			end
-- 		else
-- 			if  string.find(string.lower(camp.title) , string.lower(name)) then
-- 				campConfMod.code_loadout = codeName
-- 			end
-- 		end
-- 	end
-- end

-- -- if not campConfMod or not campConfMod.code_loadout or mission_ini.SelectLoadout == "init" then
-- if mission_ini.SelectLoadout == "init" then
-- 	require("Init/db_loadouts")
-- else
-- 	-- miguel21 modification M49.a big central db_loadout
-- 	--construit la table loadout en fonction du loadout g�n�ral et de la campagne
-- 	db_loadouts = {}





-- miguel21 modification M49.c big central db_loadout (c: loadout statistics)
local loadoutFile01 = "../../../Missions/Campaigns/"..camp.title.."/Debug/db_loadouts_archive.lua"
local TestPathloadout = io.open(loadoutFile01, "r")																--cette maniere de chercer la presence d un fichier evite un plantage
if TestPathloadout == nil or FirstMission then																	--check si le fichier existe dans ScriptsMod
	local loadout_str = "db_loadouts_archive = " .. TableSerialization(db_loadouts, 0)						--make a string
	local loadoutFile = io.open(loadoutFile01, "w")															--open targetlist file
	
	if not loadoutFile or loadoutFile == nil then
		print("MainNM Tthis campaign folder  |"..camp.title.."|  does not exist ")
		os.execute 'pause'
	end
	
	loadoutFile:write(loadout_str)																			--save new data
	loadoutFile:close()		
end
if TestPathloadout ~= nil then
	TestPathloadout:close()
end
	


--si ADD_data existe, on le precharge pour l'ajouter au DATA centram
local addDataFile02 = "../../../Missions/Campaigns/"..camp.title.."/Init/ADD_data.lua"
local TestPathADD_addData = io.open(addDataFile02, "r")										--cette maniere de chercher la presence d un fichier evite un plantage
if TestPathADD_addData ~= nil  then														--check si le fichier existe dans ScriptsMod
	dofile("../../../Missions/Campaigns/"..camp.title.."/Init/ADD_data.lua")	

	if add_EPLRS_Capacity then
		for key , value in pairs(add_EPLRS_Capacity) do
			if not EPLRS_Capacity[key] then
				EPLRS_Capacity[key] = true
			end
		end
	end

	if add_TaskByPlane then
		for key , value in pairs(add_TaskByPlane) do
			if not TaskByPlane[key] then
				TaskByPlane[key] = true
			end
		end
	end

end

if not UTIL_KillTarget and (skipMission or FirstMission)  then
	require("Active/oob_air")
	require("Active/oob_ground")
	require("Init/conf_mod")
end																				-- Miguel21 modification M00 : need option

--si Active/camp_ZoneSAR n'existe pas, on le créer
local ZoneSARFile = "../../../Missions/Campaigns/"..camp.title.."/Active/camp_ZoneSAR.lua"
local TestPathZoneSAR = io.open(ZoneSARFile, "r")										--cette maniere de chercher la presence d un fichier evite un plantage
if TestPathZoneSAR == nil  then														--check si le fichier existe dans ScriptsMod

	local camp_ZoneSAR = {
        ["blue"] = {},
        ["red"] = {},
        ["neutrals"] = {},
    }
	
	-- local ZoneSAR_str = "camp_ZoneSAR = " .. TableSerialization(camp_ZoneSAR, 0)					--make a string
    -- local ZoneSARFile = io.open("Active/camp_ZoneSAR.lua", "w")										--open ZoneSAR file
    -- ZoneSARFile:write(ZoneSAR_str)																	--save new data
    -- ZoneSARFile:close()	
elseif not UTIL_KillTarget then	--TODO attention, controler si l'actualité des ejectedPilot soit bien mise à jour
	require("Active/camp_ZoneSAR")
end		
--assign les callsign par squad west
AssignCallnameSquad()


--retrocompatibilie location radios_freq_compatible file
--recherche en priorit� le fichier radios_freq_compatible dans le dossier ScriptsMod puis dans le dossier campagne
local RadioFile = "../../../ScriptsMod."..versionPackageICM.."/radios_freq_compatible.lua"
local TestPath = io.open(RadioFile, "r")																--cette maniere de chercer la presence d un fichier evite un plantage
if TestPath ~= nil then																					--check si le fichier existe dans ScriptsMod
	io.close(TestPath)
	dofile("../../../ScriptsMod."..versionPackageICM.."/radios_freq_compatible.lua")
else	
	local RadioFile2 = "../../../Missions/Campaigns/"..camp.title.."/Init/radios_freq_compatible.lua"
	local TestPath2 = io.open(RadioFile2, "r")
	if TestPath2 ~= nil then																			--check si le fichier exist dans le dossier campagne
		io.close(TestPath2)
		dofile(RadioFile2)
	end
end


if Debug.KillGround.flag then
	for side_name,side in pairs(oob_ground) do														--side table(red/blue)											
		if side_name == Debug.KillGround.sideGround then	
			for country_n,country in pairs(side) do														--country table (number array)
				if country.vehicle then																	--if country has vehicles
					for group_n,group in pairs(country.vehicle.group) do								--groups table (number array)
						for unit_n,unit in pairs(group.units) do										--units table (number array)					
							
							if not unit.dead and math.random(1, 100) <= Debug.KillGround.pourcent then
							
								print("MainNT PasseDestroy "..unit.name)
							
									unit.dead = true														--mark unit as dead in oob_ground
									unit.dead_last = true													--mark unit as died in last mission
									-- unit.CheckDay = camp.day  
							end
						end
					end
				end
				if country.static then																--if country has static objects	
					for group_n,group in pairs(country.static.group) do								--groups table (number array)
						for unit_n,unit in pairs(group.units) do									--units table (number array)
							if not unit.dead and math.random(1, 100) <= Debug.KillGround.pourcent then			--check if unitId matches initiatorMissionID (string, needs to be converted to number)
								
								print("MainNT PasseDestroy static "..unit.name)
								
								if unit.dead ~= true then											--unit is not yet dead (some static objects that are spawned in a destroyed state are logged dead at mission start, these must be excluded here)
									group.dead = true												--mark group as dead in oob_ground (static objects can be set as group.dead and spawned in a destroyed state)
									group.hidden = true												--hide dead static object
									unit.dead = true												--mark unit as dead in oob_ground (this is for the targetlist)
									unit.dead_last = true
								end
							end
						
						end
					end
				end
				if country.ship then																--if country has ships
					for group_n,group in pairs(country.ship.group) do								--groups table (number array)
						for unit_n,unit in pairs(group.units) do									--units table (number array)
							if not unit.dead and math.random(1, 100) <= Debug.KillGround.pourcent then				--check if unitId matches initiatorMissionID (string, needs to be converted to number)
								
								print("MainNT PasseDestroy ship "..unit.name)
								
								unit.dead = true													--mark unit as dead in oob_ground
								unit.dead_last = true												--mark unit as died in last mission
								unit.CheckDay = camp.day                            -- ajoute la date de destruction    Miguel21 modification M19 : Repair SAM   
								
							end
						
						end
					end
				end
			end
		end
	end
end
if not UTIL_KillTarget then
	require("Active/targetlist")
end
if Debug.KillGround.flag then
	for side_name,side in pairs(targetlist) do											--iterate through targetlist
		if side_name == Debug.KillGround.sideTarget then
			for target_name,target in pairs(side) do										--iterate through targets
					
				if target.elements and target.elements[1].x then							--if the target has subelements and is a scenery object target (element has x coordinate)
					for element_n,element in pairs(target.elements) do						--iterate through target elements
						if not element.dead and math.random(1, 100) <= Debug.KillGround.pourcent then		
							
							print("MainNT PasseDestroy __SCENERY__ "..element.name)
							
							
							if element.dead then											--element was already dead previously
								element.dead_last = false									--mark element as not died in last mission
							else
								element.dead = true	
							end
						end
					end
				end
			end
		end
	end
end

require("Active/camp_triggers")


dofile("../../../ScriptsMod."..versionPackageICM.."/DC_CampaignSettings.lua")				-- Miguel21 modification M52_a	modification of the campaign by the player

dofile("../../../ScriptsMod."..versionPackageICM.."/DC_Refpoints.lua")

dofile("../../../ScriptsMod."..versionPackageICM.."/DC_MissionScore.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/UTIL_Data.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/UTIL_DataMap.lua")
Check_TaskPossibleByPlane()

dofile("../../../ScriptsMod."..versionPackageICM.."/DC_Time.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/UTIL_MoonPhase.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/DC_Weather.lua")

dofile("../../../ScriptsMod."..versionPackageICM.."/DC_DestroyTarget.lua")					-- miguel21 Mod26
dofile("../../../ScriptsMod."..versionPackageICM.."/DC_NavalEnvironment.lua")

dofile("../../../ScriptsMod."..versionPackageICM.."/DC_UpdateSAR.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/DC_UpdateTargetlist.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/DC_CheckTriggers.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/DC_UpdateTargetlist.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/DC_CheckTriggers.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/DC_UpdateOOBGround.lua")		-- add oob_ground in mission.coalition..... don't forget ^^


if not (EndCampaign or camp.endCampaign )then
	dofile("../../../ScriptsMod."..versionPackageICM.."/ATO_ThreatEvaluation.lua")
	dofile("../../../ScriptsMod."..versionPackageICM.."/ATO_RouteGenerator.lua")
	dofile("../../../ScriptsMod."..versionPackageICM.."/ATO_Generator.lua")
	dofile("../../../ScriptsMod."..versionPackageICM.."/ATO_PlayerAssign.lua")
	dofile("../../../ScriptsMod."..versionPackageICM.."/ATO_Timing.lua")
	dofile("../../../ScriptsMod."..versionPackageICM.."/UTIL_AddPropAircraft.lua")		-- Miguel21 modification M17_f	add AddPropAircraft Option all type
	dofile("../../../ScriptsMod."..versionPackageICM.."/ATO_FlightPlan.lua")

	dofile("../../../ScriptsMod."..versionPackageICM.."/DC_StaticAircraft.lua")
	dofile("../../../ScriptsMod."..versionPackageICM.."/DC_Prune.lua")					-- Tomsk modification M09 Integration de  Prune Script
	dofile("../../../ScriptsMod."..versionPackageICM.."/DC_Briefing.lua")

	-- dofile("../../../ScriptsMod."..versionPackageICM.."/DC_EndCampaign.lua")

	dofile("../../../ScriptsMod."..versionPackageICM.."/UTIL_Debug.lua")

	mission.currentKey = 999999															--not clear how this works but is required for multiplyer clients to be available for selection on mission start

	if camp.waitingNextGen then
		camp.waitingNextGen = false
	end
	--permet d'avancer l'horaire entre 2 missions
	if skipMission then
		if camp.waitingNextGen then
			camp.waitingNextGen = false
		end
	end

	----- convert tables back to strings for insertion into content files -----
	local misStr = "mission = " .. TableSerialization(mission, 0)
	local optStr = "options = " .. TableSerialization(options, 0)
	local warStr = "warehouses = " .. TableSerialization(warehouses, 0)
	local dicStr = "dictionary = " .. TableSerialization(dictionary, 0)
	local resStr = "mapResource = " .. TableSerialization(mapResource, 0)
	local gciStr = "GCI = " .. TableSerialization(GCI, 0)
	local cmpStr = "camp = " .. TableSerialization(camp, 0)

	----- create temporary content files of new mission file -----
	local misFile = io.open("misFile.lua", "w")											--mission
	misFile:write(misStr)
	misFile:close()

	local optFile = io.open("optFile.lua", "w")											--options
	optFile:write(optStr)
	optFile:close()

	local warFile = io.open("warFile.lua", "w")											--warehouses
	warFile:write(warStr)
	warFile:close()

	local dicFile = io.open("dicFile.lua", "w")											--dictionary
	dicFile:write(dicStr)
	dicFile:close()

	local resFile = io.open("resFile.lua", "w")											--mapResource
	resFile:write(resStr)
	resFile:close()

	local gciFile = io.open("GCIdata.lua", "w")											--GCI data file (EWR radars, AWACS, interceptors)
	gciFile:write(gciStr)
	gciFile:close()

	local cmpFile = io.open("Active/camp_status.lua", "w")								--campaign status file
	cmpFile:write(cmpStr)
	cmpFile:close()


	----- create new mission file and add content files -----

	local NbMission  = camp.mission

	if mission_ini.backupAllMissionFiles and mission_ini.backupAllMissionFiles == true then
		if not FirstMission then
			NbMission = tostring(camp.mission - 1)
			--en skipMission, la mission n'a pas �t� jou�e, donc c'est la suivante
			if skipMission then
				NbMission = NbMission + 1 
			end
		end

		if string.len(NbMission) > 1 then
			NbMission = "__"..NbMission
		else
			NbMission = "__0"..NbMission
		end
	else
		NbMission = "__Old"
	end

	if FirstMission then																--is true if script is launched from GenerateFirstMission.lua
		if not (mission_ini.backupAllMissionFiles and mission_ini.backupAllMissionFiles == true) then		
			os.remove("../"..camp.title.."/Debriefing/"..camp.title.."_first"..NbMission..".miz")
		end	
		os.rename("../"..camp.title.."_first.miz", "../"..camp.title.."/Debriefing/"..camp.title.."_first"..NbMission..".miz")
		miz = minizip.zipCreate("../" .. camp.title .. "_first.miz")					--create the first campaign mission
	else																				--is false if script is launched from Debrief_Master.lua
		if skipMission then
			os.remove( "../"..camp.title.."/Debriefing/"..camp.title.."_ongoing"..NbMission..".miz")
		end	
		res = os.rename("../"..camp.title.."_ongoing.miz", "../"..camp.title.."/Debriefing/"..camp.title.."_ongoing"..NbMission..".miz")
		miz = minizip.zipCreate("../" .. camp.title .. "_ongoing.miz")					--create the ongoing campaign mission
	end
	
	
	miz:zipAddFile("mission", "misFile.lua")
	miz:zipAddFile("options", "optFile.lua")
	miz:zipAddFile("warehouses", "warFile.lua")
	miz:zipAddFile("l10n/DEFAULT/dictionary", "dicFile.lua")
	miz:zipAddFile("l10n/DEFAULT/mapResource", "resFile.lua")
	miz:zipAddFile("l10n/DEFAULT/EventsTracker.lua", "../../../ScriptsMod."..versionPackageICM.."/Mission Scripts/EventsTracker.lua")
	miz:zipAddFile("l10n/DEFAULT/GCIdata.lua", "GCIdata.lua")
	miz:zipAddFile("l10n/DEFAULT/GCIscript.lua", "../../../ScriptsMod."..versionPackageICM.."/Mission Scripts/GCIscript.lua")
	miz:zipAddFile("l10n/DEFAULT/ARM_Defence_Script.lua", "../../../ScriptsMod."..versionPackageICM.."/Mission Scripts/ARM_Defence_Script.lua")
	miz:zipAddFile("l10n/DEFAULT/CustomTasksScript.lua", "../../../ScriptsMod."..versionPackageICM.."/Mission Scripts/CustomTasksScript.lua")
	miz:zipAddFile("l10n/DEFAULT/CarrierIntoWindScript.lua", "../../../ScriptsMod."..versionPackageICM.."/Mission Scripts/CarrierIntoWindScript.lua")
	miz:zipAddFile("l10n/DEFAULT/AddCommandRadioF10.lua", "../../../ScriptsMod."..versionPackageICM.."/Mission Scripts/AddCommandRadioF10.lua")				-- Miguel21 Modification M29
	miz:zipAddFile("l10n/DEFAULT/Fuel_Check.lua", "../../../ScriptsMod."..versionPackageICM.."/Mission Scripts/Fuel_Check.lua")								-- Norman99 modification M57_a
	miz:zipAddFile("l10n/DEFAULT/ATC_ShutUp_GENERIC.lua", "../../../ScriptsMod."..versionPackageICM.."/Mission Scripts/ATC_ShutUp_GENERIC.lua")				-- Psyko modification M59_a
	miz:zipAddFile("l10n/DEFAULT/Pedro.lua", "../../../ScriptsMod."..versionPackageICM.."/Mission Scripts/Pedro.lua")										-- Miguel21 Pedro TEST
	miz:zipAddFile("l10n/DEFAULT/camp_status.lua", "Active/camp_status.lua")
	miz:zipAddFile("l10n/DEFAULT/debugGenMission.txt", "Debug/debugGenMission.txt")
	miz:zipAddFile("l10n/DEFAULT/debugFlight.txt", "Debug/debugFlight.txt")
	miz:zipAddFile("l10n/DEFAULT/SAR.lua", "../../../ScriptsMod."..versionPackageICM.."/Mission Scripts/SAR.lua")	
	miz:zipAddFile("l10n/DEFAULT/Cercle_City.lua", "../../../ScriptsMod."..versionPackageICM.."/Mission Scripts/Cercle_City.lua")	
	

	if mission_ini.load_mist then
		miz:zipAddFile("l10n/DEFAULT/mist.lua", "../../../ScriptsMod."..versionPackageICM.."/Mission Scripts/mist.lua")											-- miguel21 modification M60 CTLD
	end
	if mission_ini.load_CTLD then
		miz:zipAddFile("l10n/DEFAULT/CTLD.lua", "../../../ScriptsMod."..versionPackageICM.."/Mission Scripts/CTLD.lua")											-- miguel21 modification M60 CTLD	
		miz:zipAddFile("l10n/DEFAULT/beacon.ogg", "../../../ScriptsMod."..versionPackageICM.."/Mission Scripts/beacon.ogg")											-- miguel21 modification M60 CTLD
		miz:zipAddFile("l10n/DEFAULT/beaconsilent.ogg", "../../../ScriptsMod."..versionPackageICM.."/Mission Scripts/beaconsilent.ogg")											-- miguel21 modification M60 CTLD
	end

	local BriefingImages = {}
	for _i,_filename in ipairs(BriefingImagesB) do	
		findValue = false
		for i,filename in ipairs(BriefingImages) do
			if _filename == filename then findValue = true    break end
		end
		if not findValue then
			table.insert(BriefingImages, _filename)
		end 
	end
	for _i,_filename in ipairs(BriefingImagesR) do	
		findValue = false
		for i,filename in ipairs(BriefingImages) do
			if _filename == filename then findValue = true  break end
		end
		if not findValue then
			table.insert(BriefingImages, _filename)
		end 
	end

	for i,filename in ipairs(BriefingImages) do											-- Miguel21 M05.b : ajout picture Briefing + pictures Target
		if type(filename) == "string" and string.len(filename) > 0 then 				-- Miguel21 M05.c : ajout picture Briefing (c: correction path vide)
			miz:zipAddFile("l10n/DEFAULT/" .. filename, "Images/" .. filename)
		end
	end

	miz:zipAddFile("l10n/DEFAULT/alarme.wav" , "Sounds/alarme.wav")


	miz:zipClose()

end		--if not (EndCampaign or camp.endCampaign )then 


dofile("../../../ScriptsMod."..versionPackageICM.."/DC_EndCampaign.lua")
	
	
----- remove temporary content files -----
os.remove("misFile.lua")
os.remove("optFile.lua")
os.remove("warFile.lua")
os.remove("dicFile.lua")
os.remove("resFile.lua")
os.remove("GCIdata.lua")

if not Debug.debug then
	--delete mission temporary files
	os.remove("../"..camp.title.."/Debug/debugFlight.txt")
	-- os.remove("../"..camp.title.."/Debug/briefingDescriptionText.txt")
	-- os.remove("../"..camp.title.."/Debug/briefing.txt")
	os.remove("../"..camp.title.."/Debug/debugGenMission.txt")
end


----- save updated status files  -----
local air_str = "oob_air = " .. TableSerialization(oob_air, 0)								--make a string
if TypeAlias then
	air_str = air_str .. "TypeAlias = " .. TableSerialization(TypeAlias, 0)
end
local airFile = io.open("Active/oob_air.lua", "w")											--open oob air file
airFile:write(air_str)																		--save new data
airFile:close()

local ground_str = "oob_ground = " .. TableSerialization(oob_ground, 0)						--make a string
local groundFile = io.open("Active/oob_ground.lua", "w")									--open oob ground file
groundFile:write(ground_str)																--save new data
groundFile:close()


local tgt_str = "targetlist = " .. TableSerialization(targetlist, 0)						--make a string
local tgtFile = io.open("Active/targetlist.lua", "w")										--open targetlist file
tgtFile:write(tgt_str)																		--save new data
tgtFile:close()

local trigStr = "camp_triggers = " .. TableSerializationAG(camp_triggers, 0)
local trigFile = io.open("Active/camp_triggers.lua", "w")
trigFile:write(trigStr)
trigFile:close()

if not (EndCampaign or camp.endCampaign) then 
	local loadout_str = "db_loadouts_archive = " .. TableSerialization(db_loadouts_archive, 0)	--make a string
	local loadoutFile = io.open("Debug/db_loadouts_archive.lua", "w")							--open targetlist file
	loadoutFile:write(loadout_str)																--save new data
	loadoutFile:close()	
end
--M40_k
local airbases_Str = "db_airbases = " .. TableSerialization(db_airbases, 0)
local trigFile = io.open("Active/db_airbases.lua", "w")
trigFile:write(airbases_Str)
trigFile:close()

if camp_ZoneSAR then
	local ZoneSAR_str = "camp_ZoneSAR = " .. TableSerialization(camp_ZoneSAR, 0)					--make a string
	local ZoneSARFile = io.open("Active/camp_ZoneSAR.lua", "w")										--open ZoneSAR file
	ZoneSARFile:write(ZoneSAR_str)																	--save new data
	ZoneSARFile:close()
end




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