--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:  M57_a M38_k
if not versionDCE then versionDCE = {} end
versionDCE["MAIN_NextMission.lua"] = "1.24.108"
------------------------------------------------------------------------------------------------------- 
-- debug_d 							(d: oob_ground not in mission)(c: EndMission)
-- Reglage_b						(a: Init/loadout selection)
-- cleanCode_d
-- 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_d		Accept result mission (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		Versionning
-- 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
-- -------------------------------------------------------------------------------------------------------
--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()


---- 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)
	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] = "return(true)"
	-- mission.trig.actions[trig_n] = 'a_do_script_file(getValueResourceByKey("ResKey_Action_' .. trig_n .. '")); mission.trig.funcStartup[' .. trig_n .. ']=nil;'
	mission.trig.actions[trig_n] = 'a_do_script_file(getValueResourceByKey("ResKey_Action_' .. trig_n .. '"));'		-- Miguel21 modification M11 : Multiplayer
	mission.trigrules[trig_n] = {
		['rules'] = {},
		['eventlist'] = '',
		['comment'] = 'Trigger ' .. trig_n,
		['predicate'] = 'triggerStart',
		['actions'] = {
			[1] = {
				['file'] = 'ResKey_Action_' .. trig_n,
				['predicate'] = 'a_do_script_file',
				['ai_task'] = {
					[1] = '',
					[2] = '',
				},
			},
		},
	}
end


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

----- run scripts to create content of next mission -----
dofile("../../../ScriptsMod."..versionPackageICM.."/UTIL_Data.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


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											-- miguel21 modification M37.d SuperCarrier
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

-- cherche le code a appliquer au loadout, pour charger le bon..loadout ^^
if not ( campConfMod and  campConfMod.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
	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 = {}
	dofile("../../../ScriptsMod."..versionPackageICM.."/UTIL_db_loadouts.lua")	
	for plane, planeTab  in pairs(db_all_loadouts) do		
		for taskName, loadout  in pairs(planeTab) do					
			for loadoutName, value  in pairs(loadout) do
				if value.code_loadout and value.code_loadout ~= "" then 								
					for code_loadout_number, code in pairs(value.code_loadout) do																					
						if string.lower(campConfMod.code_loadout) == string.lower(code) or string.lower(code) == "all" then
							if not db_loadouts[plane] then
								-- print("MainNM passe G ")							
								db_loadouts[plane] = {}
							end 
							if not db_loadouts[plane][taskName] then db_loadouts[plane][taskName] = {} end 
							if not db_loadouts[plane][taskName][loadoutName] then db_loadouts[plane][taskName][loadoutName] = {} end 
							db_loadouts[plane][taskName][loadoutName] = value
						end						
					end
				end
			end
		end
	end
end

-- 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
	

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

--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")
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_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

	----- 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/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")

	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 

if camp.waitingNextGen then
	camp.waitingNextGen = false
end
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")


----- 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 = " .. TableSerialization(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()
