params [
		["_unit", objNull, [objNull]],
		["_maximumDistance", 2000, [0]],
		["_minimumAltitude", 0, [0]],
		["_flakRoundsEvery", 2, [0]],
		["_speedDispersion", 20, [0]],
		["_distanceDispersion", 30, [0]],
		["_removeMissiles", true, [true]]
];

diag_log text "[MILSIM] (ambience) initializing flak v18";

_primaryTurret = objNull;

if (_removeMissiles) then {

	diag_log text "[MILSIM] (ambience) removing missiles";

	_magazines = magazinesAllTurrets _unit;

	{
		_magazine = _x select 0;
		diag_log text format["[MILSIM] (ambience) checking: %1", _magazine];
		
		_ammo = gettext( configfile >> "CfgMagazines" >> _magazine >> "ammo");
		diag_log text format["[MILSIM] (ambience) ammo: %1", _ammo];
		
		_type = gettext(configFile >> "CfgAmmo" >> _ammo >> "simulation");
		diag_log text format["[MILSIM] (ambience) ammo type: %1", _type];

		if (_type == "shotMissile") then {
			_unit removeMagazinesTurret [_magazine, [0]];
			diag_log text format["[MILSIM] (ambience) removing ammo: %1", _ammo];
		};

		if ((_type == "shotBullet") && (_primaryTurret isEqualTo objNull)) then {
			_primaryTurret = _forEachIndex;
			diag_log text format["[MILSIM] (ambience) found primary turret: %1", _unit weaponsTurret [0] select _primaryTurret];
		};
		
	} foreach _magazines;

};

_weapon = _unit weaponsTurret [0] select _primaryTurret;

_fullAmmoCount = _unit ammo _weapon;


_unit setVariable["feh_maximumDistance", _maximumDistance];
_unit setVariable["feh_minimumAltitude", _minimumAltitude];
_unit setVariable["feh_primaryTurret", _primaryTurret];
_unit setVariable["feh_fullAmmoCount", _fullAmmoCount];
_unit setVariable["feh_flakRoundsEvery", _flakRoundsEvery];
_unit setVariable["feh_speedDispersion", _speedDispersion];
_unit setVariable["feh_distanceDispersion", _distanceDispersion];

diag_log text format [
					"[MILSIM] (ambience) {[_this, maximumDistance: %1, minimumAltitude: %2, primaryTurret: %3, fullAmmoCount: %4, flakRoundsEvery: %5, speedDispersion: %6, distanceDispersion: %7] call milsim_fnc_flakEH;}",
					_maximumDistance,
					_minimumAltitude,
					_primaryTurret,
					_fullAmmoCount,
					_flakRoundsEvery,
					_speedDispersion,
					_distanceDispersion
				];
	

 _unit addEventHandler ["Fired",
	format[
		"[_this, %1, %2, %3, %4, %5, %6, %7] call milsim_fnc_flakEH",
		_maximumDistance,
		_minimumAltitude,
		_primaryTurret,
		_fullAmmoCount,
		_flakRoundsEvery,
		_speedDispersion,
		_distanceDispersion
	]
];