CMANO LUA CLIPBOARD updated 18Sep 2017

Lots of borrowed examples, some original code.  You can tell originals because it's messy, but works
thanks be to the Command Lua Masters, mostly Apache85, the Mikes, Gunner, Randomizer, too many to list. 

This is my lua snippet museum.  I have this in notepad++, open, when designing scenarios. There are quite a few redundancies, but also some fantastic Command Lua examples. Enjoy!!
Nick G

fortyporkpies@gmail.com
******************************************THE FOLLOWING ARE FROM AN EARLY LUA TUTORIAL
ScenEdit_AssignUnitToMission('Fulcrum #1', 'MCAP-Agrr')
ScenEdit_AssignUnitToMission('Fulcrum #2', 'MCAP-Agrr')
ScenEdit_AssignUnitToMission('Fulcrum #3', 'MCAP-Agrr')
ScenEdit_AssignUnitToMission('Fulcrum #4', 'MCAP-Agrr')
---------------------
ScenEdit_AddUnit({type = 'Aircraft', side = 'Red EW', name = 'A-50 Mainstay', dbid = 711, loadoutid = 8060, heading = 322, altitude="35000 ft", })
ScenEdit_AssignUnitToMission('A-50 Mainstay', 'AEW')
---------------------
ScenEdit_SetSidePosture('Red EW', 'Red', 'N')

ScenEdit_SetSidePosture('Red EW', 'Red', 'F')
---------------------

ScenEdit_SetUnit({side="Red", name="Armored Plt (T-62 MBT x 4)-1", Autodetectable="yes"})
ScenEdit_SetUnit({side="Red", name="Armored Plt (T-62 MBT x 4)-2", Autodetectable="yes"})
ScenEdit_SetUnit({side="Red", name="Armored Plt (T-62 MBT x 4)-3", Autodetectable="yes"})
ScenEdit_SetUnit({side="Red", name="Armored Plt (T-62 MBT x 4)-4", Autodetectable="yes"})
---------------------

ScenEdit_AssignUnitToMission('Armored Plt (T-62 MBT x 4)-1', 'Tank-Retreat')
ScenEdit_AssignUnitToMission('Armored Plt (T-62 MBT x 4)-2', 'Tank-Retreat')
ScenEdit_AssignUnitToMission('Armored Plt (T-62 MBT x 4)-3', 'Tank-Retreat')
ScenEdit_AssignUnitToMission('Armored Plt (T-62 MBT x 4)-4', 'Tank-Retreat')

---------------------
a = math.random(1,2)
if a == 1 then 
ScenEdit_AssignUnitToMission('SA-2 M', 'SA-2-M-HiPK') 
elseif a == 2 then 
ScenEdit_AssignUnitToMission('SA-2 M', 'None') 
ScenEdit_SetEMCON('Unit', 'SA-2 M', 'Radar=Active')
end
---------------------
a = math.random(1,3)
if a == 1 then 
ScenEdit_AddUnit({type="Land", name="SA-3", side="Red SAM", DBID=1617 , latitude='43.989207494803', longitude='19.7805623780113', autodetectable="false"})
elseif a == 2 then 
ScenEdit_AddUnit({type="Land", name="SA-6", side="Red SAM", DBID=1247 , latitude='43.989207494803', longitude='19.7805623780113', autodetectable="true", holdposition="true"})
elseif a == 3 then 
ScenEdit_AddUnit({type="Land", name="SA-8", side="Red SAM", DBID=1702 , latitude='43.989207494803', longitude='19.7805623780113', holdposition="true"})
end
---------------------
a = math.random(1,5)
if a == 1 or a == 2 then 
  ScenEdit_AddUnit({type="Land", name="SA-3", side="Red SAM", DBID=1617 , latitude='43.2815673924034', longitude='21.3040611946082', autodetectable="false"})
elseif a == 3 or a == 4 then 
  ScenEdit_AddUnit({type="Land", name="SA-6", side="Red SAM", DBID=1247 , latitude='43.2815673924034', longitude='21.3040611946082', holdposition="true"})
elseif a == 5 then
ScenEdit_AddUnit({type="Land", name="SA-8", side="Red SAM", DBID=1702 , latitude='43.2815673924034', longitude='21.3040611946082', holdposition="true"})
end
---------------------
a = math.random(1,100)
if a < 33 then 
ScenEdit_AssignUnitToMission('Fulcrum #5', 'NCAP')
ScenEdit_AssignUnitToMission('Fulcrum #6', 'NCAP')
ScenEdit_AssignUnitToMission('Fulcrum #7', 'NCAP')
ScenEdit_AssignUnitToMission('Fulcrum #8', 'NCAP')
ScenEdit_AssignUnitToMission('Fulcrum #9', 'NCAP')
ScenEdit_AssignUnitToMission('Fulcrum #10', 'NCAP')
ScenEdit_AssignUnitToMission('Fulcrum #11', 'NCAP')
ScenEdit_AssignUnitToMission('Fulcrum #12', 'NCAP')
ScenEdit_AssignUnitToMission('Fulcrum #13', 'SCAP')
ScenEdit_AssignUnitToMission('Fulcrum #14', 'SCAP')
ScenEdit_AssignUnitToMission('Fulcrum #15', 'SCAP')
ScenEdit_AssignUnitToMission('Fulcrum #16', 'SCAP')
ScenEdit_AssignUnitToMission('Fulcrum #17', 'SCAP')
ScenEdit_AssignUnitToMission('Fulcrum #18', 'SCAP')
ScenEdit_AssignUnitToMission('Fulcrum #19', 'SCAP')
ScenEdit_AssignUnitToMission('Fulcrum #20', 'SCAP')
elseif a < 66 then 
ScenEdit_AssignUnitToMission('Fulcrum #5', 'NMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #6', 'NMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #7', 'NMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #8', 'NMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #9', 'NMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #10', 'NMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #11', 'NMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #12', 'NMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #13', 'SMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #14', 'SMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #15', 'SMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #16', 'SMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #17', 'SMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #18', 'SMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #19', 'SMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #20', 'SMCAP')
else
 ScenEdit_AssignUnitToMission('Fulcrum #5', 'NCAP')
ScenEdit_AssignUnitToMission('Fulcrum #6', 'NCAP')
ScenEdit_AssignUnitToMission('Fulcrum #7', 'NCAP')
ScenEdit_AssignUnitToMission('Fulcrum #8', 'NCAP')
ScenEdit_AssignUnitToMission('Fulcrum #9', 'NCAP')
ScenEdit_AssignUnitToMission('Fulcrum #10', 'NCAP')
ScenEdit_AssignUnitToMission('Fulcrum #11', 'NCAP')
ScenEdit_AssignUnitToMission('Fulcrum #12', 'NCAP')
ScenEdit_AssignUnitToMission('Fulcrum #13', 'SMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #14', 'SMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #15', 'SMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #16', 'SMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #17', 'SMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #18', 'SMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #19', 'SMCAP')
ScenEdit_AssignUnitToMission('Fulcrum #20', 'SMCAP')
end

---------------------
ScenEdit_SetWeather(math.random(-2,3), math.random(5,19), math.random(5,7)/10.0, 5)

ScenEdit_SetWeather(math.random(4,7), math.random(1,7), math.random(1,3)/10.0, 3)

ScenEdit_SetWeather(math.random(8,12), 0, 0, 1)
---------------------
ScenEdit_AssignUnitToMission('Galeb #1', 'Marshal')
ScenEdit_AssignUnitToMission('Galeb #2', 'Marshal')
ScenEdit_AssignUnitToMission('Galeb #3', 'Marshal')
ScenEdit_AssignUnitToMission('Galeb #4', 'Marshal')
ScenEdit_AssignUnitToMission('Galeb #5', 'Marshal')
ScenEdit_AssignUnitToMission('Galeb #6', 'Marshal')
---------------------
a = math.random(1,2)
if a == 1 then 
ScenEdit_AssignUnitToMission('Galeb #1', 'Strike Jaco')
ScenEdit_AssignUnitToMission('Galeb #2', 'Strike Jaco')
ScenEdit_AssignUnitToMission('Galeb #3', 'Strike Jaco')
ScenEdit_AssignUnitToMission('Galeb #5', 'Strike Jaco')
ScenEdit_AssignUnitToMission('Galeb #4', 'Strike Jaco')
ScenEdit_AssignUnitToMission('Galeb #6', 'Strike Jaco')
elseif a == 2 then 
ScenEdit_AssignUnitToMission('Galeb #1', 'Strike Poggio')
ScenEdit_AssignUnitToMission('Galeb #2', 'Strike Poggio')
ScenEdit_AssignUnitToMission('Galeb #3', 'Strike Poggio')
ScenEdit_AssignUnitToMission('Galeb #5', 'Strike Poggio')
ScenEdit_AssignUnitToMission('Galeb #4', 'Strike Poggio')
ScenEdit_AssignUnitToMission('Galeb #6', 'Strike Poggio')
end
---------------------
ScenEdit_SetEMCON('Side', 'Red SAM', 'Radar=Active')
ScenEdit_SetEMCON('Mission', ' SA-2-M-HiPK', 'Radar=Active')
---------------------
ScenEdit_SetSidePosture('Red EW', 'Red SAM', 'N')

ScenEdit_SetSidePosture('Red EW', 'Red SAM ', 'F')

---------------------
ScenEdit_SetEMCON('Side', 'Red SAM', 'Radar=Active')
ScenEdit_SetEMCON('Mission', ' SA-2-M-HiPK', 'Radar=Active')
---------------------
ScenEdit_SetKeyValue('number_of_EW_radars_down', '0')

val = tonumber(ScenEdit_GetKeyValue('number_of_EW_radars_down'))
val = val + 1
ScenEdit_SetKeyValue('number_of_EW_radars_down', val)


ewdown = tonumber(ScenEdit_GetKeyValue('number_of_EW_radars_down'))
if ewdown < 3 then
ScenEdit_SetEMCON('Side', 'Red SAM', 'Radar=Passive')
ScenEdit_SetEMCON('Mission', 'SA-2-M-HiPK', 'Radar=Passive')
end

##################################################
***********************************************
***********************************************
if ScenEdit_GetUnit({name='[Target] SCUD Battery',side='North Korea'}) ~= nil then 
ScenEdit_AssignUnitToMission('[Target] SCUD Battery', 'Seoul Strike') 
end 

{name='Token2', guid='2c14ea0e-8672-42a5-babe-97369df8c617'}
latitude='-85.6095696879484', longitude='-44.9624653058021'

ScenEdit_SetKeyValue('whoo', '1')
b=ScenEdit_GetKeyValue('whoo')
print(b)
b=b+1
print(b)
c=tostring(b)
ScenEdit_SetKeyValue('whoo',c)
bb=ScenEdit_GetKeyValue('whoo')
print (bb)
*************
math.random(); math.random(); math.random()
r = 1
repeat
  f = ( math.random(1,3) )
     r = r + 1
until (r>3)
******************
DEPRECATED::
******************

scoredx = ScenEdit_GetScore('US Civilians')
if scoredx == 0 then
scoredx2 = ScenEdit_GetScore('USSTRATCOM')
scoredx2 = scoredx2 - 22000
q=ScenEdit_SetScore('USSTRATCOM',scoredx2,'Lose 22000 Points for strategic assets being destroyed')
elseif scoredx == 1 then
scoredx2 = ScenEdit_GetScore('USSTRATCOM')
scoredx2 = scoredx2 - 7000
q=ScenEdit_SetScore('USSTRATCOM',scoredx2,'Lose 7000 Points for failure to get mostassets off ground before destruction')
elseif scoredx > 1 then
scoredx2 = ScenEdit_GetScore('USSTRATCOM')
scoredx2 = scoredx2 - 2000
q=ScenEdit_SetScore('USSTRATCOM',scoredx2,'Lose 2000 Points for underground structures being destroyed')
end
**************
scoredx3 = ScenEdit_GetScore('Russian Civilians')
if scoredx3 == 0 then
scoredx2 = ScenEdit_GetScore('USSTRATCOM')
scoredx2 = scoredx2 + 17500
q1=ScenEdit_SetScore('USSTRATCOM',scoredx2,'Gain 17500 points for Destroying Assets in their Silos and Bunkers')
elseif scoredx3 == 1 then
scoredx2 = ScenEdit_GetScore('USSTRATCOM')
scoredx2 = scoredx2 + 4000
q1=ScenEdit_SetScore('USSTRATCOM',scoredx2,'Gain 4000 points for Destroying Empty Assets')
elseif scoredx3 > 1 then
scoredx2 = ScenEdit_GetScore('USSTRATCOM')
scoredx2 = scoredx2 + 7500
q1=ScenEdit_SetScore('USSTRATCOM',scoredx2,'Gain 7500 points for Destroying Underground Facilities whilst getting fucked by a sneak attack')
end
***********************************************SHOWS HOW TO USE GETUNIT .MOUNTS ESPECIALLY special thanks to MICHAELM for help on the forums with this
 q=ScenEdit_GetUnit({name='SSBN 741 Maine [Ohio Class]', guid='9e79fb11-4473-457e-8832-2aa2e29b9696'})
print (q)
unit {
 type = 'Submarine', 
 subtype = '2005', 
 name = 'SSBN 741 Maine [Ohio Class]', 
 side = 'USSTRATCOM', 
 guid = '9e79fb11-4473-457e-8832-2aa2e29b9696', 
 proficiency = 'Veteran', 
 latitude = '39.7510095794948', 
 longitude = '-165.544203654367', 
 altitude = '-76.60005', 
 speed = '4.381683', 
 throttle = 'Loiter', 
 autodetectable = 'False', 
 base = 'NSB-B Submarine Pen', 
 mission = 'SSBN Transit', 
 mounts = '9', 
 magazines = '11', 
 unitstate = 'OnPlottedCourse', 
 fuelstate = 'None', 
 weaponstate = 'None', 
}


q=ScenEdit_GetUnit({name='SSBN 741 Maine [Ohio Class]', guid='9e79fb11-4473-457e-8832-2aa2e29b9696'})
print (q.mounts)
{ [1] = { mount_name = '3-inch Signal Ejector', mount_guid = '2153b086-939d-4cfd-89bb-8deee50801ac', mount_weapons = { [1] = { wpn_current = 2, wpn_name = 'ADC Mk2 Mod 0 Torpedo Decoy', wpn_default = 2, wpn_guid = '931a6bfc-1555-45f5-a9a5-329312f4e950', wpn_maxcap = 2, wpn_dbid = 137 } }, mount_dbid = 1467 }, [2] = { mount_name = '533mm Mk68 TT', mount_guid = '3ed97cf3-717e-4fe5-b819-fc705f905eee', mount_weapons = { [1] = { wpn_current = 1, wpn_name = 'Mk48 Mod 7 ADCAP CBASS', wpn_default = 1, wpn_guid = '30690b37-fd19-4fbe-b919-b4997a3317d0', wpn_maxcap = 1, wpn_dbid = 1712 } }, mount_dbid = 1162 }, [3] = { mount_name = '533mm Mk68 TT', mount_guid = 'a92a438f-90e8-437e-8e11-acdfa600d40b', mount_weapons = { [1] = { wpn_current = 1, wpn_name = 'Mk48 Mod 7 ADCAP CBASS', wpn_default = 1, wpn_guid = '77b974ed-0b23-4f0b-8054-ed616af00d29', wpn_maxcap = 1, wpn_dbid = 1712 } }, mount_dbid = 1162 }, [4] = { mount_name = '533mm Mk68 TT', mount_guid = '60e5912b-9b05-4334-92bc-81de548afe64', mount_weapons = { [1] = { wpn_current = 1, wpn_name = 'Mk48 Mod 7 ADCAP CBASS', wpn_default = 1, wpn_guid = '4c0e4926-8d66-4fb7-a771-2f4d84d0d9fd', wpn_maxcap = 1, wpn_dbid = 1712 } }, mount_dbid = 1162 }, [5] = { mount_name = '533mm Mk68 TT', mount_guid = '8c714cf5-db2d-4a0b-890b-afb6a55dfeae', mount_weapons = { [1] = { wpn_current = 1, wpn_name = 'Mk48 Mod 7 ADCAP CBASS', wpn_default = 1, wpn_guid = 'beaeeef6-d95a-4884-8829-76596f3c44e8', wpn_maxcap = 1, wpn_dbid = 1712 } }, mount_dbid = 1162 }, [6] = { mount_name = 'CSA Mk2 Mod 0 [Mk151]', mount_guid = 'a98cdf6d-dd44-41f4-b2e9-dd68ff168a3f', mount_weapons = { [1] = { wpn_current = 0, wpn_name = 'ADC Mk2 Mod 3 Torpedo Decoy', wpn_default = 0, wpn_guid = '77d5a0a1-6528-4621-a0e3-171269a517f4', wpn_maxcap = 4, wpn_dbid = 2457 }, [2] = { wpn_current = 2, wpn_name = 'ADC Mk3 Mod 1 Torpedo Countermeasure', wpn_default = 2, wpn_guid = '86d36190-a831-4ba1-a61f-aa1ec7d103d0', wpn_maxcap = 4, wpn_dbid = 2458 }, [3] = { wpn_current = 2, wpn_name = 'ADC Mk4 Mod 1 Sonar Jammer', wpn_default = 2, wpn_guid = '63436be5-1424-41bf-9a95-86961928193c', wpn_maxcap = 4, wpn_dbid = 126 } }, mount_dbid = 2116 }, [7] = { mount_name = 'CSA Mk2 Mod 0 [Mk151]', mount_guid = 'd4e8cba4-674d-4407-b180-1c7f61386000', mount_weapons = { [1] = { wpn_current = 0, wpn_name = 'ADC Mk2 Mod 3 Torpedo Decoy', wpn_default = 0, wpn_guid = '0e89c337-96c0-42fd-9140-b14cef69f503', wpn_maxcap = 4, wpn_dbid = 2457 }, [2] = { wpn_current = 2, wpn_name = 'ADC Mk3 Mod 1 Torpedo Countermeasure', wpn_default = 2, wpn_guid = 'a51ea8f0-47fa-4a7b-8e6a-175ba9ae66db', wpn_maxcap = 4, wpn_dbid = 2458 }, [3] = { wpn_current = 2, wpn_name = 'ADC Mk4 Mod 1 Sonar Jammer', wpn_default = 2, wpn_guid = '513f273d-0a71-4b68-9638-c13b28e4f4f5', wpn_maxcap = 4, wpn_dbid = 126 } }, mount_dbid = 2116 }, [8] = { mount_name = 'CSA Mk2 Mod 0 [Mk151]', mount_guid = '5ecf1ef9-f420-4d93-8631-3896a6d60e47', mount_weapons = { [1] = { wpn_current = 6, wpn_name = 'ADC Mk2 Mod 3 Torpedo Decoy', wpn_default = 6, wpn_guid = '05b25fcb-6d8b-41cc-91bb-be2db747259b', wpn_maxcap = 6, wpn_dbid = 2457 }, [2] = { wpn_current = 0, wpn_name = 'ADC Mk3 Mod 1 Torpedo Countermeasure', wpn_default = 0, wpn_guid = '11a84681-d2e1-411b-9cbc-fe084c3e2b7f', wpn_maxcap = 6, wpn_dbid = 2458 }, [3] = { wpn_current = 0, wpn_name = 'ADC Mk4 Mod 1 Sonar Jammer', wpn_default = 0, wpn_guid = 'bf388e1e-4ec4-4caa-bf32-fb30315c5a54', wpn_maxcap = 6, wpn_dbid = 126 } }, mount_dbid = 2115 }, [9] = { mount_name = 'Trident D5', mount_guid = 'dc619382-acd1-4960-b85b-e882153027dc', mount_weapons = { [1] = { wpn_current = 24, wpn_name = 'UGM-133 Trident II D5 [4 MIRV x W88 475kT Nuclear]', wpn_default = 24, wpn_guid = 'f7af2147-affa-4df3-820a-a74402d3754c', wpn_maxcap = 24, wpn_dbid = 2686 } }, mount_dbid = 2927 } }

-- from above
 [9] = { mount_name = 'Trident D5', mount_guid = 'dc619382-acd1-4960-b85b-e882153027dc', mount_weapons = { [1] = { wpn_current = 24, wpn_name = 'UGM-133 Trident II D5 [4 MIRV x W88 475kT Nuclear]', wpn_default = 24, wpn_guid = 'f7af2147-affa-4df3-820a-a74402d3754c', wpn_maxcap = 24, wpn_dbid = 2686 } }, mount_dbid = 2927 }

a=ScenEdit_GetUnit({name='SSBN 741 Maine [Ohio Class]', guid='9e79fb11-4473-457e-8832-2aa2e29b9696'})
q=(a.mounts[9].mount_weapons[1].wpn_current)
print (q)
****************************************************taken myks bunker, good stuff here
function draw_circle(a,b,t,txt)
    if txt == nil then
       txt = ""
    end
    t = t
    tg = t - 1
    lat1 = a.latitude
    lon1 = a.longitude
    r = b / 60 
 
    for i=0,tg do
        th = 2 * math.pi * i / t 
	rlat = lat1 + r * math.cos(th)
        rlon = lon1 + r * math.sin(th) / math.cos(math.rad(lat1))
        ScenEdit_AddReferencePoint({
            side='PlayerSide',
            lat=rlat,
            lon=rlon,
            name=txt,
            highlighted="yes"})
    end
 
end



Now paste this code, change red syntax for your own side/unit name (here is Red and test), change radius (350) and desired number of verticals (24). Run it... 

 
local unit = ScenEdit_GetUnit({side="Red", name="test"})
draw_circle({latitude=unit.latitude, longitude=unit.longitude}, 350, 24, "RP")
--grana func below

function draw_circle(a,b,t,txt)
    if txt == nil then
       txt = ""
    end
    shit = 0
    t = t
    tg = t - 1
    lat1 = a.latitude
    lon1 = a.longitude
    r = b / 60 
 
    for i=0,tg do
        th = 2 * math.pi * i / t 
	rlat = lat1 + r * math.cos(th)
        rlon = lon1 + r * math.sin(th) / math.cos(math.rad(lat1))
        shit = shit + 1
        txt2 = (txt .. (tostring (shit)))
        ScenEdit_AddReferencePoint({
            side='PlayerSide',
            lat=rlat,
            lon=rlon,
            name=txt2,
            highlighted="yes"})
    end
 
end

local unit = ScenEdit_GetUnit({name='Thule AFB', guid='85831809-769a-45de-95b6-18b8da5349d0'})
draw_circle({latitude=unit.latitude, longitude=unit.longitude}, 500, 12, "ThuleADIZ")

ScenEdit_SetSpecialAction({ActionNameOrID = 'ICBMs Engage Countervalue Targets', IsActive='True', IsRepeatable='False'})
ScenEdit_SetSpecialAction({ActionNameOrID = 'USS Maine Strike ICBM Targets', IsActive='True', IsRepeatable='False'})

************************************Examples from COW SCENARIOS THIS IS SOME ADVANCED STUFF
ScenEdit_SetUnit({Name="Korea SAM Bty (THAAD)", OutOfComms="True"})
ScenEdit_SetEMCON('Unit', 'Korea SAM Bty (THAAD)', 'Radar=Passive')
a=ScenEdit_GetScore("China")
ScenEdit_SetScore('China',(a-200),'-200 Points for Disrupting Korean THAAD')

ScenEdit_SetUnit({Name="USS Ronald Reagan", autodetectable="True"})
a=ScenEdit_GetScore("China")
ScenEdit_SetScore('China',(a-750),'-750 Points for Disrupting Naval Surface Communications')

if ScenEdit_GetUnit({side="United States-Japan-South Korea", name="Sentinel #1"}) ~= nil then
ScenEdit_SetUnit({side='United States-Japan-South Korea',name='Sentinel #1',RTB='true'})
end
*********************************BOOM NOTE BE CAREFUL WITH THAT WARHEAD ID! 
ScenEdit_AddExplosion({warheadid = 593 , lat='36.5057805616381', lon='-118.881844548913', altitude= 50000})

*******************DEPRECATED:
math.randomseed(os.time())
local a = math.random(1,10)
if a < 2 then
ScenEdit_AddUnit({type = 'Submarine', name = 'PLARK-949AM Orel [Oscar III]', heading = 90, dbid = 568, side = 'Russian Forces', latitude='40.305545816975', longitude='-159.094618929175'})
ScenEdit_AssignUnitToMission('PLARK-949AM Orel [Oscar III]', 'Sea Control 1')
elseif a < 4 then
ScenEdit_AddUnit({type = 'Submarine', name = 'PLA-885 Severodvinsk [Yasen]', heading = 90, dbid = 405, side = 'Russian Forces', latitude='39.9503522266312', longitude='-167.603887607065'})
ScenEdit_AssignUnitToMission('PLA-885 Severodvinsk [Yasen]', 'Sea Control 1')
elseif a < 6 then
ScenEdit_AddUnit({type = 'Submarine', name = 'PLARK-949A Tomsk [Oscar II]', heading = 90, dbid = 626, side = 'Russian Forces', latitude='39.9503522266312', longitude='-167.603887607065'})
ScenEdit_AssignUnitToMission('PLARK-949A Tomsk [Oscar II]', 'Sea Control 1')
end

qzu=ScenEdit_SetScore('Russian Forces',0,'initialize')
qzu=ScenEdit_SetScore('USSTRATCOM',0,'initialize')
qzu=ScenEdit_SetScore('US Civilians',0,'initialize')
qzu=ScenEdit_SetScore('Russian Civilians',0,'initialize')
qzu=ScenEdit_SetScore('US Satellites',0,'initialize')
qzu=ScenEdit_SetScore('Russian Satellites',0,'initialize')
qzu=ScenEdit_SetScore('Token1',0,'initialize')
qzu=ScenEdit_SetScore('US AD',0,'initialize')

ScenEdit_SetKeyValue('uslaunch', '0')
ScenEdit_SetKeyValue('ruslaunch', '0')
ScenEdit_SetKeyValue('ustoken', '0')
ScenEdit_SetKeyValue('rustoken', '0')
ScenEdit_SetKeyValue('russneak', '0')

*************************DEPRECATED:

local lastCount = ScenEdit_GetKeyValue('usnukes')
local lastCountN = tonumber(lastCount)

if ((lastCountN == nil) or (lastCountN ~= 0)) then
ScenEdit_SetDoctrine({side='USSTRATCOM'}, {use_nuclear_weapons= 'yes' })
ScenEdit_SetSidePosture('USSTRATCOM', 'Russian Forces', 'H')
ScenEdit_SetSidePosture('USSTRATCOM', 'Russian Civilians', 'H')
ScenEdit_SpecialMessage('USSTRATCOM','NUCLEAR WEAPON RELEASE GRANTED!')
lastCountN = 0
ScenEdit_SetKeyValue('usnukes', tostring(lastCountN))
end
************************************NEWER VERSION BELOW OF ABOVE CODE
local lastCount = ScenEdit_GetKeyValue('usnukes')
local lastCountN = tonumber(lastCount)

if ((lastCountN == nil) or (lastCountN ~= 0)) then
ScenEdit_SetDoctrine({side='USSTRATCOM'}, {use_nuclear_weapons= 'yes' })
ScenEdit_SetSidePosture('USSTRATCOM', 'Russian Forces', 'H')
ScenEdit_SetSidePosture('USSTRATCOM', 'Russian Civilians', 'H')
ScenEdit_SetSpecialAction({ActionNameOrID = 'ICBMs Engage Countervalue Targets', IsActive='True', IsRepeatable='False'})
ScenEdit_SetSpecialAction({ActionNameOrID = 'USS Maine Strike ICBM Targets', IsActive='True', IsRepeatable='False'})
ScenEdit_SetSpecialAction({ActionNameOrID = 'Show Current Civilian Deaths', IsActive='True', IsRepeatable='True'})
ScenEdit_SpecialMessage('USSTRATCOM','NUCLEAR WEAPON RELEASE GRANTED!')
lastCountN = 0
ScenEdit_SetKeyValue('usnukes', tostring(lastCountN))
end





************************************ DEPRECATED:
local lastCount = ScenEdit_GetKeyValue('rusnukes')
local lastCountN = tonumber(lastCount)
if ((lastCountN == nil) or (lastCountN ~= 0)) then
ScenEdit_SetDoctrine({side="Russian Forces"}, {use_nuclear_weapons= "yes" })
ScenEdit_SetSidePosture('Russian Forces', 'USSTRATCOM', 'H')
ScenEdit_SetSidePosture('Russian Forces', 'US Civilians', 'H')
ScenEdit_SetSidePosture('Russian Forces', 'US AD', 'H')
local f = math.random(1,2)
if f == 1 then
if ScenEdit_GetUnit({name='PLARB-941 Typhoon [Akula]',side='Russian Forces'}) ~= nil then 
ScenEdit_AssignUnitToMission('PLARB-941 Typhoon [Akula]', 'land strike4')
end
if ScenEdit_GetUnit({name='PLARB-955 [Borey]',side='Russian Forces'}) ~= nil then 
ScenEdit_AssignUnitToMission('PLARB-955 [Borey]', 'land strike3')
end
elseif f == 2 then
if ScenEdit_GetUnit({name='PLARB-941 Typhoon [Akula]',side='Russian Forces'}) ~= nil then 
ScenEdit_AssignUnitToMission('PLARB-941 Typhoon [Akula]', 'land strike3')
end
if ScenEdit_GetUnit({name='PLARB-955 [Borey]',side='Russian Forces'}) ~= nil then 
ScenEdit_AssignUnitToMission('PLARB-955 [Borey]', 'land strike4')
end
end

lastCountN = 0
ScenEdit_SetKeyValue('rusnukes', tostring(lastCountN))
end

**********************NEWER VERSION BELOW OF ABOVE CODE
local lastCount = ScenEdit_GetKeyValue('rusnukes')
local lastCountN = tonumber(lastCount)
if ((lastCountN == nil) or (lastCountN ~= 0)) then
ScenEdit_SetDoctrine({side="Russian Forces"}, {use_nuclear_weapons= "yes" })
ScenEdit_SetSidePosture('Russian Forces', 'USSTRATCOM', 'H')
ScenEdit_SetSidePosture('Russian Forces', 'US Civilians', 'H')
ScenEdit_SetSidePosture('Russian Forces', 'US AD', 'H')
local f = math.random(1,2)
if f == 1 then
if ScenEdit_GetUnit({name='PLARB-667BDRM Verkhoturye [Delta IV]', guid='d97f63bd-9dfe-4c02-9e06-d289bb636540'}) ~= nil then 
ScenEdit_AssignUnitToMission('PLARB-667BDRM Verkhoturye [Delta IV]', 'land strike4')
end
if ScenEdit_GetUnit({name='PLARB-955 Dolgorukly [Borey]', guid='3b82a018-4805-4487-9b99-b286f604fcca'}) ~= nil then 
ScenEdit_AssignUnitToMission('PLARB-955 Dolgorukly [Borey]', 'land strike3')
end
elseif f == 2 then
if ScenEdit_GetUnit({name='PLARB-667BDRM Verkhoturye [Delta IV]', guid='d97f63bd-9dfe-4c02-9e06-d289bb636540'}) ~= nil then 
ScenEdit_AssignUnitToMission('PLARB-667BDRM Verkhoturye [Delta IV]', 'land strike3')
end
if ScenEdit_GetUnit({name='PLARB-955 Dolgorukly [Borey]', guid='3b82a018-4805-4487-9b99-b286f604fcca'}) ~= nil then 
ScenEdit_AssignUnitToMission('PLARB-955 Dolgorukly [Borey]', 'land strike4')
end
end

lastCountN = 0
ScenEdit_SetKeyValue('rusnukes', tostring(lastCountN))
end




******************************RUSSIAN SNEAK ATTACK

local a = math.random(1,10)
if a < 3 then
ScenEdit_AddUnit({type = 'Submarine', name = 'PLARB-955 Nevskiy [Borey]', heading = 90, dbid = 136, side = 'Russian Forces', latitude='42.4654303950757', longitude='-154.397902718206'})
ScenEdit_AssignUnitToMission('PLARB-955 Nevskiy [Borey]', 'land strike3')
elseif a < 7 then
ScenEdit_AddUnit({type = 'Submarine', name = 'PLARB-667 Podolsk [DeltaIII]', heading = 90, dbid = 268, side = 'Russian Forces', latitude='44.3937120586337', longitude='-152.510451572438'})
ScenEdit_AssignUnitToMission('PLARB-667 Podolsk [DeltaIII]', 'land strike3')
elseif a < 11 then
ScenEdit_AddUnit({type = 'Submarine', name = 'PLARB-667 Tula [DeltaIV]', heading = 90, dbid = 269, side = 'Russian Forces', latitude='43.8287763931566', longitude='-169.43120872961'})
ScenEdit_AssignUnitToMission('PLARB-667 Tula [DeltaIV]', 'land strike3')
end

local t = math.random(1,2)
if t == 1 then
ScenEdit_AddUnit({type = 'Submarine', name = 'PLARB-667 Ryazan [DeltaII]', heading = 90, dbid = 6, side = 'Russian Forces', latitude='46.4939744085044', longitude='-126.981038711938'})
ScenEdit_AssignUnitToMission('PLARB-667 Ryazan [DeltaII]', 'land strike4')
elseif t == 2 then
ScenEdit_AddUnit({type = 'Submarine', name = 'PLARB-667 Ryazan [DeltaII]', heading = 90, dbid = 6, side = 'Russian Forces', latitude='43.7210134130447', longitude='-161.318476810692'})
ScenEdit_AssignUnitToMission('PLARB-667 Ryazan [DeltaII]', 'land strike4')
end
ScenEdit_SetKeyValue('russneak', '1')

*********************
ScenEdit_SetEMCON('Mission', 'Sea Control 1', 'Radar=Active;OECM=Active;Sonar=Active')

local a = math.random(1,10)
if a < 7 then
ScenEdit_AddUnit({type = 'Facility', name = 'Spetsnaz Detatchment 1', heading = 90, dbid = 1946, side = 'Russian Forces', latitude='36.6913117652817', longitude='-117.8750069807',proficiency=4})
ScenEdit_AssignUnitToMission('Spetsnaz Detatchment 1', 'AirLandStrike1')
end

*********************

local scoredx2 = ScenEdit_GetScore('USSTRATCOM')
local b=ScenEdit_GetKeyValue('uslaunch')
local lastCountNb = tonumber(b)
if lastCountNb == 0 then
scoredx2 = scoredx2 - 20000
local q=ScenEdit_SetScore('USSTRATCOM',scoredx2,'Lose 20000 Points for strategic assets being destroyed')
elseif lastCountNb ~= 0 then
scoredx2 = scoredx2 - 2000
local q=ScenEdit_SetScore('USSTRATCOM',scoredx2,'Lose 2000 Points for underground ICBM structures being destroyed')
end

*******************

local scoredx2 = ScenEdit_GetScore('USSTRATCOM')
local y=ScenEdit_GetKeyValue('ruslaunch')
local lastCountNy = tonumber(y)
if lastCountNy == 0 then
scoredx2 = scoredx2 + 17500
local q1=ScenEdit_SetScore('USSTRATCOM',scoredx2,'Gain 17500 points for Destroying Assets in their Silos and Bunkers')
elseif lastCountNy ~= 0 then
scoredx2 = scoredx2 + 2000
local q1=ScenEdit_SetScore('USSTRATCOM',scoredx2,'Gain 2000 points for Destroying Empty Assets')
end

y=ScenEdit_GetKeyValue('rustoken')
lastCountNy = tonumber(y)
if lastCountNy == 0 then
scoredx2 = ScenEdit_GetScore('USSTRATCOM')
scoredx2 = scoredx2 + 2500
q1=ScenEdit_SetScore('USSTRATCOM',scoredx2,'Gain 2500 points bonus because russians have no token in place')
end


**********************crude examples of
SPECIAL ACTIONS:
**********************
Authenticate, Send "Watch" Alert to Joint Chiefs, and open the "Black Book" containing strilke options under OPLAN 8010

While aboard Air Force One, now diverting its course to a remote facility, the President breaches protocol and hands you "the biscuit", the confirmation code that authenticates her as the Commander in Chief. She realizes that she is not of sound mind at the moment to make such an enormous decision, so she gives you a direct order to handle the situation as you see fit.  You comply and and the aide-de-camp holding the "Nuclear Football" nods his head, pulls you aside, and awaits your command on whether or not to open the 20kg Zero-Halliburton briefcase... 


ScenEdit_SetUnit({name='Token1', guid='750f200a-1a50-4151-9eba-2b765fc81ffd',latitude='-77.7762550996898', longitude='-113.442048119071'})

ScenEdit_SetKeyValue('ustoken', '1')


local lastCount = ScenEdit_GetKeyValue('rustoken')
local lastCountN = tonumber(lastCount)
local lastCount2 = ScenEdit_GetKeyValue('rusnukes')
local lastCountN2 = tonumber(lastCount2)
if lastCountN2 == nil then
lastCountN2 = 666
end
local lastCount3 = ScenEdit_GetKeyValue('russneak')
local lastCountN3 = tonumber(lastCount3)
local postr = ScenEdit_GetSidePosture('Russian Forces', 'USSTRATCOM')
local scoredx2 = ScenEdit_GetScore('USSTRATCOM')


if lastCountN3 == 1 then
scoredx2 = scoredx2 + 10000
local q=ScenEdit_SetScore('USSTRATCOM',scoredx2,'Gain 10000 points because the Russians Sneak Attack')
elseif ((lastCountN == 1) and (lastCountN2 == 666)) then
scoredx2 = scoredx2 + 2000
local q=ScenEdit_SetScore('USSTRATCOM',scoredx2,'Gain 2000 points for authorizing nukewar because russians have token and havent launched')
elseif ((lastCountN == 0) and (postr == 'H')) then
scoredx2 = scoredx2 - 70000
local q=ScenEdit_SetScore('USSTRATCOM',scoredx2,'Lose 70000 Points declaring nuclear war too early but russians consider you hostile')
elseif lastCountN == 0 then
scoredx2 = scoredx2 - 100000
local q=ScenEdit_SetScore('USSTRATCOM',scoredx2,'Lose 100000 Points declaring nuclear war too early')
ScenEdit_SpecialMessage('USSTRATCOM','You Are Penalized for Declaring Nuclear war Unilaterally!')
end

***********

ScenEdit_SetMission('USSTRATCOM', 'Jet Intercept Thule',{isactive=true})

ScenEdit_AssignUnitToMission('Minot AFB [91st Missile Wing, Minot]', 'US Countervalue Strike')
ScenEdit_SetMission('USSTRATCOM', 'US Countervalue Strike',{isactive=true})

ScenEdit_SetUnit({name='SSBN 741 Maine [Ohio Class]', guid='9e79fb11-4473-457e-8832-2aa2e29b9696', altitude='-50', speed='4', throttle='Loiter'})
ScenEdit_AssignUnitToMission('SSBN 741 Maine [Ohio Class]', 'US Counter ICBM Strike')
ScenEdit_SetMission('USSTRATCOM', 'US Counter ICBM Strike',{isactive=true})


***********************Print Civ Deaths
local USCount = ScenEdit_GetKeyValue('uscivcount')
local RUSCount = ScenEdit_GetKeyValue('ruscivcount')
local txt = 'US Civilian Deaths: '
local txt1 = ' Russian Civilian Deaths: '
local txt2 = (txt .. USCount .. txt1 .. RUSCount)
ScenEdit_SpecialMessage('USSTRATCOM',txt2)
*********************CALC CIV DEATHS RUS

local a=ScenEdit_UnitX()
local t=a.name
if a.type == 'Facility' then

local b=ScenEdit_GetKeyValue('ruscivcount')
local civcountnum = tonumber(b)
local deathpercent = (math.random(60,99))/100

local d=math.random(500000,900000)
d=d*deathpercent
civcountnum=civcountnum+d
if t=='Moscow' then
civcountnum=civcountnum+d
civcountnum=civcountnum+d
civcountnum=civcountnum+d
end
local e=math.floor(civcountnum)
local c=tostring(e)
ScenEdit_SetKeyValue('ruscivcount',c)


end


*************************CALC CIV DEATHS US fortyporkpies original macabre and messy

local a=ScenEdit_UnitX()
local t=a.name
if a.type == 'Facility' then

local b=ScenEdit_GetKeyValue('uscivcount')
local civcountnum = tonumber(b)
local deathpercent = (math.random(60,99))/100

local CITYTABLE = {'Washington DC','New York City','Los Angeles','San Francisco','Chicago','Houston','Seattle','Boston','Dallas','Philadelphia','Phoenix','San Diego'}
local POPTABLE = {800000,8500000,4000000,1000000,2700000,2300000,900000,800000,1300000,1500000,1600000,1400000}

for i,line in ipairs(CITYTABLE) do

if t == line then 
local d=POPTABLE[i]
d=d*deathpercent
civcountnum=civcountnum+d
local e=math.floor(civcountnum)
local c=tostring(e)
ScenEdit_SetKeyValue('uscivcount',c)
break
end

end

local d=math.random(250000,500000)
d=d*deathpercent
civcountnum=civcountnum+d
local e=math.floor(civcountnum)
local c=tostring(e)
ScenEdit_SetKeyValue('uscivcount',c)


end



*************************Random thought


That Mk41, holy crap. Imagine being SAC aircrew with that thing in your bomb bay. Absolutely horrifying.
****************************

ScenEdit_SetKeyValue('uscivcount', '0')
ScenEdit_SetKeyValue('ruscivcount', '0')

local b=ScenEdit_GetKeyValue('uscivcount')
local deathpercent = (math.random(60,99))/100
local CITYTABLE = {'Washington DC','New York City','Los Angeles','San Francisco','Chicago','Houston','Seattle','Boston','Dallas','Philadelphia','Phoenix','San Diego'}
local POPTABLE = {800000,8500000,4000000,1000000,2700000,2300000,900000,800000,1300000,1500000,1600000,1400000}

for i,line in ipairs(CITYTABLE) do
if a.name=='Washington DC' then
lower = 100000
upper = 2000000
end



local c=tostring(b)
ScenEdit_SetKeyValue('uscivcount',c)

*************************************




local deathpercent = (math.random(60,99))/100
local CITYTABLE = {'Washington DC','New York City','Los Angeles','San Francisco','Chicago','Houston','Seattle','Boston','Dallas','Philadelphia','Phoenix','San Diego'}
local POPTABLE = {800000,8500000,4000000,1000000,2700000,2300000,900000,800000,1300000,1500000,1600000,1400000}
local city = 'Dallas'
for i,line in ipairs(CITYTABLE) do
if city == line then 
local d=POPTABLE[i]
d=d*deathpercent
local e=math.floor(d)--NOT NEEDED
print (d)
print (e)
print (deathpercent)
print (POPTABLE[i])
break
end

end
**********************************************
math.random(); math.random(); math.random()
r = 1
repeat
  f = ( math.random(1,3) )
     r = r + 1
until (r>3)

********************************************************OLD SCHOOL EXAMPLE i beleive this is original APACHE85

--Merchant generation script (default settings create 8-16 merchant ships in the China Sea assigned to a ferry mission named 'VLADIVOSTOK' on a side named 'Merchant' 
math.randomseed(os.time()) 

merch_num = math.random(8,16) --change 8 or 16 to your specified minimum and maximum number of merchants 

for i = 1,merch_num do 
redo_count = 0 
::redo:: 
local lat_var = math.random(1,(10^13)) 
local lon_var = math.random(1,(10^13)) 
v_lat = math.random(27,32) + (lat_var/(10^13)) --change 27 and 32 to your specified minimum and maximum latitude values; it's important that the first number is smaller than the second. 
v_lon = math.random(119,127) + (lon_var/(10^13)) --change 119 and 127 to your specified minimum and maximum longitude values; it's important that the first number is smaller than the second. 
elevation = World_GetElevation({latitude=v_lat, longitude=v_lon}) 
if elevation > -10 then --Checks to see if the water is deep enough, adjust as you please 
redo_count = redo_count + 1 
if redo_count > 50 then 
print ('A ship was not able to find a suitable spot for placement. Re-check latitude and longitude settings') 
break --this cuts the loop if there are no suitable positions found after 50 tries, prevents infinite loop/game freeze 
else 
goto redo --retries the placement if the water is too shallow 
end 
end 
DBIDTABLE = { 775, 2027, 2029, 2028, 2030, 774, 2026, 2031, 2775, 2023, 773, 2774, 1001, 1374, 2773, 2776, 1006, 222, 1599, 2034, 1002, 1317, 144, 339, 275, 145, 2022, 259 } --list of DBIDs 
DBID = DBIDTABLE[math.random( 1, #DBIDTABLE)] 
local new_merch = ScenEdit_AddUnit({side='Merchant', type='Ship',name='Merchant #'..i, dbid=DBID,latitude=v_lat,longitude=v_lon}) 
local fuel = new_merch.fuel 
fuel[3001].current = fuel[3001].max*math.random(600, 800)/1000 
new_merch.fuel = fuel 
ScenEdit_AssignUnitToMission( new_merch.name, 'VLADIVOSTOK') 
print (new_merch.name..' with dbid '..DBID..' was created in water with a depth of '..elevation..'m') 
end


*******************************the following seems to work US POSITIVE POINT EVALUATOR the idea is to filter all losses through a single tester script for each side??


local a=ScenEdit_UnitX()
local scoredx2 = ScenEdit_GetScore('USSTRATCOM')

if a.type == 'Submarine' then

if ((a.name == 'PLARB-955 Dolgorukly [Borey]') or (a.name == 'PLARB-955 Nevskiy [Borey]')) then
local q=(a.mounts[8].mount_weapons[1].wpn_current)
elseif ((a.name == 'PLARB-667BDRM Verkhoturye [Delta IV]') or (a.name == 'PLARB-667 Tula [DeltaIV]')) then
local q=(a.mounts[5].mount_weapons[1].wpn_current)
elseif ((a.name == 'PLARB-667 Podolsk [DeltaIII]') or (a.name == 'PLARB-667 Ryazan [DeltaII]')) then
local q=(a.mounts[7].mount_weapons[1].wpn_current)
end
if q == 0 then
scoredx2 = scoredx2 + 3000
ScenEdit_SetScore('USSTRATCOM',scoredx2,'Gain 3000 points for sinking a Russian SSBN')
elseif ((q < 17) and (q ~= nil)) then
scoredx2 = scoredx2 + 20000
ScenEdit_SetScore('USSTRATCOM',scoredx2,'Gain 20000 points for sinking a Russian SSBN that hasnt launched all of its missiles')
elseif ((q > 16) or (q == nil)) then
ScenEdit_SpecialMessage('USSTRATCOM','SOMETHING IS WRONG WITH POSITIVE POINT SSBN EVAL')
end

elseif ((a.type == 'Facility') and (a.mounts[1] ~= nil)) then
local q=(a.mounts[1].mount_weapons[1].wpn_current)
if q == nil then
scoredx2 = scoredx2 + 2200
ScenEdit_SetScore('USSTRATCOM',scoredx2,'Gain 2200 points for destroying a Russian Underground Bunker first loop')
elseif q == 0 then
scoredx2 = scoredx2 + 2000
ScenEdit_SetScore('USSTRATCOM',scoredx2,'Gain 2000 points for destroying an Empty Russian ICBM Silo')
elseif q == 1 then
scoredx2 = scoredx2 + 17500
ScenEdit_SetScore('USSTRATCOM',scoredx2,'Gain 17500 points for destroying a Russian ICBM in its Silo')
end
else
scoredx2 = scoredx2 + 2200
ScenEdit_SetScore('USSTRATCOM',scoredx2,'Gain 2200 points for destroying a Russian Underground Bunker second loop')
end

local y=ScenEdit_GetKeyValue('rustoken')
local lastCountNy = tonumber(y)
if lastCountNy == 0 then
scoredx2 = ScenEdit_GetScore('USSTRATCOM')
scoredx2 = scoredx2 + 300
ScenEdit_SetScore('USSTRATCOM',scoredx2,'Gain 300 points bonus because russians have no token in place')
end


**************************************US NEGATIVE POINT EVALUATOR

local a=ScenEdit_UnitX()
local scoredx2 = ScenEdit_GetScore('USSTRATCOM')


if a.name == 'SSBN 741 Maine [Ohio Class]' then
local q=(a.mounts[9].mount_weapons[1].wpn_current)

if q == 0 then
scoredx2 = scoredx2 - 5000
ScenEdit_SetScore('USSTRATCOM',scoredx2,'Lose 5000 points for USS Maine being destroyed')
elseif q < 25 then
scoredx2 = scoredx2 - 20000
ScenEdit_SetScore('USSTRATCOM',scoredx2,'Lose 20000 Points for Maine being sunk with SLBMs on Board')
elseif ((q==nil) or (q > 24)) then
ScenEdit_SpecialMessage('USSTRATCOM','SOMETHING IS WRONG WITH SSBN NEGATIVE POINT EVAL')
end

elseif a.type == 'Facility' then
local q=(a.mounts[1].mount_weapons[1].wpn_current)

if q == 0 then
scoredx2 = scoredx2 - 2000
ScenEdit_SetScore('USSTRATCOM',scoredx2,'Lose 2000 points for empty silo being destroyed')
elseif q == 1 then
scoredx2 = scoredx2 - 20000
ScenEdit_SetScore('USSTRATCOM',scoredx2,'Lose 20000 Points for ICBM being destroyed before leaving the silo')
end

else

ScenEdit_SpecialMessage('USSTRATCOM','SOMETHING IS WRONG WITH NEGATIVE POINT EVAL')

end

******************INITILIZATION
math.randomseed(os.time())
math.random(); math.random(); math.random()
local r = 1
local a = 0
repeat
  a = (math.random(1,10))
  r = r + 1
until (r>10)

if a < 2 then
ScenEdit_AddUnit({type = 'Submarine', name = 'PLARK-949AM Orel [Oscar III]', heading = 90, dbid = 568, side = 'Russian Forces', latitude='40.305545816975', longitude='-159.094618929175'})
ScenEdit_AssignUnitToMission('PLARK-949AM Orel [Oscar III]', 'Sea Control 1')
elseif a < 4 then
ScenEdit_AddUnit({type = 'Submarine', name = 'PLA-885 Severodvinsk [Yasen]', heading = 90, dbid = 405, side = 'Russian Forces', latitude='39.9503522266312', longitude='-167.603887607065'})
ScenEdit_AssignUnitToMission('PLA-885 Severodvinsk [Yasen]', 'Sea Control 1')
elseif a < 6 then
ScenEdit_AddUnit({type = 'Submarine', name = 'PLARK-949A Tomsk [Oscar II]', heading = 90, dbid = 626, side = 'Russian Forces', latitude='39.9503522266312', longitude='-167.603887607065'})
ScenEdit_AssignUnitToMission('PLARK-949A Tomsk [Oscar II]', 'Sea Control 1')
end

if a < 6 then
ScenEdit_DeleteUnit({name='PLARK-949 Oscar I [Granit]', guid='a12aadfd-ed98-42fe-90dc-4ff679d97a99'})
end


ScenEdit_SetScore('USSTRATCOM',10,'initialize test')
ScenEdit_SetScore('USSTRATCOM',0,'initialize')
ScenEdit_SetScore('Russian Forces',0,'initialize')
ScenEdit_SetScore('US Civilians',0,'initialize')
ScenEdit_SetScore('Russian Civilians',0,'initialize')
ScenEdit_SetScore('US Satellites',0,'initialize')
ScenEdit_SetScore('Russian Satellites',0,'initialize')
ScenEdit_SetScore('Token1',0,'initialize')
ScenEdit_SetScore('US AD',0,'initialize')

ScenEdit_SetKeyValue('uslaunch', '0')
ScenEdit_SetKeyValue('ruslaunch', '0')
ScenEdit_SetKeyValue('ustoken', '0')
ScenEdit_SetKeyValue('rustoken', '0')
ScenEdit_SetKeyValue('russneak', '0')

ScenEdit_SetKeyValue('uscivcount', '0')
ScenEdit_SetKeyValue('ruscivcount', '0')
ScenEdit_SetKeyValue('deadhand', '0')

*******************************THIS SCRIPT ASSIGNS lots of units to one mission

local nds = {ScenEdit_GetUnit {side="KPMF", name="Nodong 1"}, ScenEdit_GetUnit {side="KPMF", name="Nodong 2"}, ScenEdit_GetUnit {side="KPMF", name="Nodong 3"}, ScenEdit_GetUnit {side="KPMF", name="Nodong 4"}, ScenEdit_GetUnit {side="KPMF", name="Nodong 5"}, ScenEdit_GetUnit {side="KPMF", name="Nodong 6"}, ScenEdit_GetUnit {side="KPMF", name="Nodong 7"}, ScenEdit_GetUnit {side="KPMF", name="Nodong 8"}, ScenEdit_GetUnit {side="KPMF", name="Nodong 9"} }

ScenEdit_SetSidePosture('KPMF', 'China Targets', 'H')

for i,u in pairs(nds) do
 u.mission = "Conventional Strike"
end
************************************** THE FOLLOWING I AM STILL TRYING TO UNDERSTAND
local function demarshal(value)
	local slen,val = string.match(value,"([0-9]+):(.*)")
	local nlen = tonumber(slen)
	local demarshal_name = string.sub(val,1,nlen)
	local demarshaller = KeyStore.demarshallers[demarshal_name]
	return demarshaller(string.sub(val,nlen+1))
end

KeyStore = { 
	keys = {
	}, 
	demarshallers = {
		prim_str = function(strval) return strval end,
		prim_num = function(strval) return tonumber(strval) end,
		prim_nil = function(strval) return nil end,
		prim_bool= function(strval) return strval=="true" end,
		prim_func= function(strval) return nil end,
		prim_tab = function(strval)
			local istr = strval
			local outt = {}
			while istr:len() > 0 do
				local kslen,rval = string.match(istr,"([0-9]+):(.*)")
				local klen = tonumber(kslen)
				local keyStr = string.sub(rval,1,klen)
				local key = demarshal(keyStr)
				local vslen,vval = string.match(string.sub(rval,klen+1),"([0-9]+):(.*)")
				local vlen = tonumber(vslen)
				local value = demarshal(string.sub(vval,1,vlen))
				outt[key] = value
				istr = string.sub(vval,vlen+1)
			end
			return outt
		end
	} 
}

--metatable
local persister = {}

local function contains(t, e)
  for i = 1,#t do
    if t[i] == e then return true end
  end
  return false
end

function persister.__index(table, key)
	local result = ScenEdit_GetKeyValue(key)

	if result == "" then
		return nil
	end

	if (string.sub(result,1,1) == ":") then
		--unmarshalled
		return string.sub(result,2)
	else
		return demarshal(result)
	end
end



function persister.__newindex(_table,key,value)
	function marshal(value)
		local function marshalTable( table )
			-- format: keylen:key .. vallen:value
			local outp = ""
			for key,value in pairs(table) do
				local mk = marshal(key                            
				local mv = marshal(value)
				outp = outp .. mk:len() .. ":" .. mk .. mv:len() .. ":" .. mv
			end 
			return outp
		end
		local mt = getmetatable(value)
		local name,marshalled = nil,nil
		if mt == nil or (mt ~= nil and mt.__marshal == nil) then
			if type(value) == "string" then
				name,marshalled = "prim_str",value
			elseif type(value) == "number" then
				name,marshalled = "prim_num",tostring(value)
			elseif type(value) == "nil" then
				name,marshalled = "prim_nil",""
			elseif type(value) == "boolean" then
				name,marshalled = "prim_bool",tostring(value)
			elseif type(value) == "function" then
				name,marshalled = "prim_func","" --TODO
			elseif type(value) == "table" then
				name,marshalled = "prim_tab",marshalTable(value)
			else
				name,marshalled = "prim_str",tostring(value) --default to str
			end
		end

		if mt ~= nil and mt.__marshal ~= nil then
			name,marshalled = mt.__marshal(value)
			name = "mrsh_" .. name
		end
		return string.len(name) .. ":" .. name .. marshalled
	end

	if contains(_table.keys,key) then
		ScenEdit_SetKeyValue(key,marshal(value))
	else
		table.insert(_table.keys, key)
		ScenEdit_SetKeyValue(key,marshal(value))
	end
end

function persister.__call(table, key, demarshaller)
	table.demarshallers["mrsh_" .. key] = demarshaller
end

setmetatable(KeyStore, persister)

if KeyStore.readyTELs == nil then KeyStore.readyTELs = {false, false, false, false, false,false,false,false,false} end
*********************************
{name='RUS Timer', guid='d34c991f-056c-4588-8492-776e951b5882'}
{name='US Timer', guid='2fe346e0-3964-41f5-8ead-6f89e8254b73'}
ScenEdit_AssignUnitToMission('US Timer', 'Countdown Mish')
ScenEdit_SetMission('Token1', 'Countdown Mish',{isactive=true})

********************************* random weather deprecated
local valz = tonumber(ScenEdit_GetKeyValue('weath'))
local q=ScenEdit_GetWeather()
local ctemp = q.temp
local crain = q.rainfall
local ccloud = q.undercloud
local csea = q.seastate
local a=(math.random(1,100))

if ((valz < 6) and (a < 20)) then

valz = valz + 1
local c=tostring(valz)
ScenEdit_SetKeyValue('weath',c)
local temp=ctemp - (math.random(2,6))
local rain=crain + (math.random(1,11))
local cloud=ccloud + ((math.random(1,4))/10.0)
local sea=csea + (math.random(1,2))
if ((temp < -2) or (temp > 22)) then temp = ctemp end
if rain > 48 then rain = crain end
if cloud > 1 then cloud = ccloud end
if sea > 7 then sea = csea end
ScenEdit_SetWeather(temp,rain,cloud,sea)
ScenEdit_SpecialMessage('USSTRATCOM', '<P><FONT size=2 face="Courier New">COMMANDER,</P><P>WX REPORT WORSENING,</P> TEMPERATURE: ' .. temp .. ' DEGREES CELSIUS, RAIN STATE: ' .. rain .. ' CLOUD LEVEL: ' .. cloud .. ' AND SEA STATE: ' .. sea)

elseif a < 51 then
local temp=ctemp + (math.random(2,6))
local rain=crain - (math.random(1,11))
local cloud=ccloud - ((math.random(1,4))/10.0)
local sea=csea - (math.random(1,2))
if ((temp < -2) or (temp > 22)) then temp = ctemp end
if rain < 1 then rain = 0 end
if cloud < 0.1 then cloud = 0 end
if sea < 1 then sea = 0 end
ScenEdit_SetWeather(temp,rain,cloud,sea)
ScenEdit_SpecialMessage('USSTRATCOM', '<P><FONT size=2 face="Courier New">COMMANDER,</P><P>WX REPORT IMPROVING,</P> TEMPERATURE: ' .. temp .. ' DEGREES CELSIUS, RAIN STATE: ' .. rain .. ' CLOUD LEVEL: ' .. cloud .. ' AND SEA STATE: ' .. sea)
end


{ rainfall = 0, temp = 15, seastate = 1, undercloud = 0.100000001490116 }
ScenEdit_SetWeather(math.random(-2,3), math.random(5,19), math.random(5,7)/10.0, 5)

ScenEdit_SetWeather(math.random(4,7), math.random(1,7), math.random(1,3)/10.0, 3)

ScenEdit_SetWeather(math.random(8,12), 0, 0, 1)

*************************************
--Random weather mark zero

local temp= math.random(-2,12)
local rain= math.random(0,5)
local cloud= math.random(0,5)/10.0
local sea= math.random(1,4)

ScenEdit_SetWeather(temp,rain, cloud, sea)

--temp range 0 to 25 questionable
--rain range 0 to 50
--cloud range 0.0 to 1.0
--sea range 0-9

ScenEdit_SpecialMessage('USSTRATCOM', '<P><FONT size=2 face="Courier New">COMMANDER,</P><P>NEW WX REPORT,</P> TEMPERATURE: ' .. temp .. ' DEGREES CELSIUS, RAIN STATE: ' .. rain .. ' CLOUD LEVEL: ' .. cloud .. ' AND SEA STATE: ' .. sea)
****************************************@@@@@@@@@@@@@@@@@@@END OF ORIGINAL STUFF THE FOLLOWING RANDOM
for i=1,28 do 
x = ScenEdit_GetUnit({side='Cuba',name='SAM BN (SA-2c) '..i})
if x ~= nil then
ScenEdit_SetEMCON('unit',x.name,'radar=Passive')
chance = math.random(1,4)
if chance <= 1 then
ScenEdit_SetEMCON('unit',x.name,'radar=Active')
end
end
end
****************************************EXAMPLE CODE OF PLACING UNITS USING DO LOOP
units={
{name='AD SAM Key West A Batt (HAWK)', dbid=658, latitude=24.590782015272, longitude=-81.795285752226},
{name='AD SAM Key West B Batt (HAWK)', dbid=658, latitude=24.55917031338, longitude=-81.761067229115},
{name='AD SAM Key West C Batt (HAWK)', dbid=658, latitude=24.57493971116, longitude=-81.658633991921},
{name='AD SAM Key West D Batt (HAWK)', dbid=658, latitude=24.596973877581, longitude=-81.702204556475},
{name='AD Radar Key West USAF AN/FPS-6A', dbid=53, latitude=24.584694410652, longitude=-81.688112035179},
{name='AD Radar Key West USN FPS-37', dbid=557, latitude=24.584608303288, longitude=-81.688945845011},
}

for i = 1,#units do
ScenEdit_AddUnit({side='United States',type='Facility',dbid=units[i].dbid,name=units[i].name,latitude=units[i].latitude,longitude=units[i].longitude})
end

ChangeTension(10)

--[[
Activate 6/65th (HAWK) at NAS Key West

Deploys a HAWK SAM battalion to the vicinity of NAS Key West for air defence.

Units:
24 x M192 I-HAWK
1 x USAF AN/FPS-6A
1 x USN FPS-37

Mission:
Air Defence
***************************************same
qty = 12
maint_req = math.floor(qty*0.33)
avail_ac = qty-maint_req

for i = 1,qty do

if i < avail_ac then

ScenEdit_AddUnit({
type='Air',
side='United States',
dbid=2191,
name='656th Bombardment Sqn #'..i,
base='Lake Charles AFB',
loadoutid=2568
})

else 

ScenEdit_AddUnit({
type='Air',
side='United States',
dbid=2191,
name='656th Bombardment Sqn #'..i,
base='Lake Charles AFB',
loadoutid=4
})

end
end

qty = 3
maint_req = math.floor(qty*0.33)
avail_ac = qty-maint_req

for i = 1,qty do

if i < avail_ac then

ScenEdit_AddUnit({
type='Air',
side='United States',
dbid=157,
name='656th Bombardment Sqn EW Det #'..i,
base='Lake Charles AFB',
loadoutid=447
})

else 

ScenEdit_AddUnit({
type='Air',
side='United States',
dbid=157,
name='656th Bombardment Sqn EW Det #'..i,
base='Lake Charles AFB',
loadoutid=4
})

end
end

ChangeTension(40)

--[[
Aircraft:
12 x B-47E-IV Stratojet
3 x EB-47E Stratojet

Mission:
Strategic Bombing
]]
********************************************************USE OF MSG BOX
tens = tonumber(GetTension())
print (tens)

if tens <= 25 then
tens_str = 'LOW'

elseif tens >25 and tens <50 then
tens_str = 'MEDIUM'

elseif tens >= 50 then 
tens_str = 'HIGH'
end

ScenEdit_MsgBox(
'Tension is currently '..tens_str, 1)
*****************************************************EXAMPLE OF SPECIAL ACTION REQ DEFCON INCREASE

ChangeDefcon(-1)

new_defcon = tonumber(GetDefcon())

if new_defcon <= 1 then
ScenEdit_SpecialMessage
('United States',
'<P><FONT face=Consolas>' .. '\\'..'\\'..'FLASH'.. '\\'..'\\'..'FLASH'.. '\\'..'\\'..'FLASH<BR>' .. 
'FROM: POTUS<BR>' .. 
'TO: ALL US FORCES<BR>' .. 
'RE: DEFCON 1' .. 
'<P><FONT face=Consolas>ALL FORCES ARE ORDERED TO SET DEFCON 1. <BR>'.. 
'<BR>'..
'NUCLEAR RELEASE IS AUTHORISED.'..
'<BR>'..
'<BR>'..
'REPEAT NUCLEAR RELEASE IS AUTHORISED.'..
'</P>'..
'<P><FONT face=Consolas>TOP SECRET'..'\\'..'\\'..'</FONT></P>')

ChangeTension(75)

ScenEdit_SetDoctrine({side='United States'},{use_nuclear_weapons=true})
--authorise nuclear weapon release, increase tension by 75
end

if new_defcon == 2 then
ScenEdit_SpecialMessage
('United States',
'<P><FONT face=Consolas>' .. '\\'..'\\'..'FLASH'.. '\\'..'\\'..'FLASH'.. '\\'..'\\'..'FLASH<BR>' .. 
'FROM: SECDEF<BR>' .. 
'TO: ALL US FORCES<BR>' .. 
'RE: DEFCON 2' .. 
'<P><FONT face=Consolas>ALL FORCES ARE ORDERED TO SET DEFCON 2. <BR>'.. 
'<BR>'..
'STAND-BY ON HIGH ALERT.'..
'<BR>'..
'<BR>'..
'NUCLEAR RELEASE IS NOT AUTHORISED AT THIS TIME.'..
'</P>'..
'<P><FONT face=Consolas>TOP SECRET'..'\\'..'\\'..'</FONT></P>')

ChangeTension(35)

ScenEdit_SetDoctrine({side='United States'},{use_nuclear_weapons=false})
end

if new_defcon == 3 then
ScenEdit_SpecialMessage
('United States',
'<P><FONT face=Consolas>' .. '\\'..'\\'..'FLASH'.. '\\'..'\\'..'FLASH'.. '\\'..'\\'..'FLASH<BR>' .. 
'FROM: SECDEF<BR>' .. 
'TO: ALL US FORCES<BR>' .. 
'RE: DEFCON 3' .. 
'<P><FONT face=Consolas>ALL FORCES ARE ORDERED TO SET DEFCON 3. <BR>'.. 
'<BR>'..
'STAND-BY ON ALERT FOR FURTHER TASKING.'..
'<BR>'..
'<BR>'..
'NUCLEAR RELEASE IS NOT AUTHORISED OR ANTICIPATED AT THIS TIME.'..
'</P>'..
'<P><FONT face=Consolas>TOP SECRET'..'\\'..'\\'..'</FONT></P>')

ChangeTension(25)

ScenEdit_SetDoctrine({side='United States'},{use_nuclear_weapons=false})
end
**************************************************AN EXAMPLE OF A REGULARLY FIRED AI CHECK TRIGGER 
y = ScenEdit_GetSidePosture("Soviet Union", "United States")
if y == 'H' then
ussr = ScenEdit_SetKeyValue('USSR_Hostile','true')
end

x = ScenEdit_GetSidePosture("Cuba", "United States")
if x == 'H' then
cuba = ScenEdit_SetKeyValue('Cuba_Hostile','true')
end

tens = GetTension()
defc = GetDefcon()
cuba = ScenEdit_GetKeyValue('Cuba_Hostile')
ussr = ScenEdit_GetKeyValue('USSR_Hostile')

msgtime=DTG()
--Check tension and defcon and become hostile accordingly if not already

--If neither side is hostile reset SA-2s to stop firing (possible as a result of airspace violations)
if cuba == 'false' and ussr == 'false' then
	for i=1,28 do 
	x = ScenEdit_GetUnit({side='Cuba',name='SAM BN (SA-2c) '..i})
		if x ~= nil then
		ScenEdit_SetDoctrine({side=x.side,guid=x.guid}, {weapon_control_status_air='1'})
		end
	end
end

--if cuba is hostile but not USSR and tension is below 200 and defcon is 2 or higher (as in less ready) then check to see if there's a cease fire (75% chance at tens 50, 50% chance at tens 100, 25% chance at tens 150)
if cuba == 'true' and ussr == 'false' and tens < 200 and defc > 1 then
roll = math.random(1,200)
if roll < tens then 
ScenEdit_SetSidePosture("Cuba", "United States", "U")
ScenEdit_SetSidePosture("United States", "Cuba", "U")

ScenEdit_SpecialMessage
('United States',
'<P><FONT face=Consolas>' .. '\\'..'\\'..'FLASH'.. '\\'..'\\'..'FLASH'.. '\\'..'\\'..'FLASH<BR>' .. 
'FROM: SECDEF<BR>' .. 
'TO: ALL US FORCES<BR>' .. 
'RE: CEASE FIRE <BR>' ..
msgtime..
'<P><FONT face=Consolas>THE CUBAN GOVERNMENT HAS CALLED FOR A CEASE FIRE TO WHICH POTUS HAS GIVEN PROVISIONAL ACCEPTANCE. ALL FORCES ARE ORDERED TO IMMEDIATELY CEASE HOSTILITIES AGAINST CUBAN FORCES AND WITHDRAW FROM CUBAN AIRSPACE. <BR>'.. 
'<BR>'..
'REPEAT: IMMEDIATELY CEASE HOSTILITIES AGAINST CUBAN FORCES AND WITHDRAW FROM CUBAN AIRSPACE.'..
'<BR>'..
'<BR>'..
'REMAIN VIGILANT AND ALERT FOR FURTHER ACTION.'..
'</P>'..
'<P><FONT face=Consolas>TOP SECRET'..'\\'..'\\'..'</FONT></P>')

SetTension(50)
end
end

if tens >=75 and cuba == 'false' and ussr == 'false' then --if tension is over 75 then there's a chance (equal to tension in %) that Cuba will go hostile
local roll = math.random(1,100)
	if roll < tens then
	ScenEdit_SetSidePosture("Cuba", "United States", "H")
	ScenEdit_SetSidePosture("United States", "Cuba", "H")
	ChangeTension(50)
	ScenEdit_SetKeyValue('Cuba_Hostile','true')
	
	ScenEdit_SpecialMessage
('United States',
'<P><FONT face=Consolas>' .. '\\'..'\\'..'FLASH'.. '\\'..'\\'..'FLASH'.. '\\'..'\\'..'FLASH<BR>' .. 
'FROM: SECDEF<BR>' .. 
'TO: ALL US FORCES<BR>' .. 
'RE: WAR WARNING <BR>' ..
msgtime..
'<P><FONT face=Consolas>HUMINT SUGGESTS SIGNS OF IMMINENT HOSTILE ACTION BY CUBAN FORCES. PREPARE IMMEDIATELY TO DEFEND US INTERESTS AND ASSETS AGAINST HOSTILE ACTION.<BR>'.. 
'<BR>'..
'THERE IS NO INDICATION OF HOSTILE INTENTION BY THE SOVIET UNION AT THIS STAGE. DO NOT--REPEAT--DO NOT ENGAGE SOVIET FORCES.'..
'<BR>'..
'GOOD LUCK -SECDEF SENDS.'..
'</P>'..
'<P><FONT face=Consolas>TOP SECRET'..'\\'..'\\'..'</FONT></P>')

	
	end
end

if defc <= 3 and tens >= 100 and cuba == 'true' and ussr == 'false' then --if cuba is hostile and defcon < 3 and tension > 100 then Soviet Union will go hostile based on % chance of tension - 100(ie tension 125 = 25% chance, tension 200 = 100% chance)
local chance = tens - 100
local roll = math.random(1,100)
if roll<chance then
ScenEdit_SetSidePosture("Soviet Union", "United States", "H")
ScenEdit_SetSidePosture("United States", "Soviet Union", "H")
ScenEdit_SetKeyValue('USSR_Hostile','true')
ChangeTension(75)

	ScenEdit_SpecialMessage
('United States',
'<P><FONT face=Consolas>' .. '\\'..'\\'..'FLASH'.. '\\'..'\\'..'FLASH'.. '\\'..'\\'..'FLASH<BR>' .. 
'FROM: SECDEF<BR>' .. 
'TO: ALL US FORCES<BR>' .. 
'RE: WAR WARNING // DEFCON 2 <BR>' ..
msgtime..
'<P><FONT face=Consolas>DIPLOMATIC CABLE FROM RECEIVED FROM SOVIET PREMIER KRUSCHEV STATING "THE SOVIET UNION WILL VIGOUROUSLY DEFEND THE NOBLE CUBAN PEOPLE FROM IMPERIALIST AGGRESSORS". HUMINT SOURCES CONFIRM MOBILISATION OF SOVIET FORCES IN CUBA AND WESTERN EUROPE.<BR>'.. 
'<BR>'..
'INTEL ASSESSMENT IS THAT THE SOVIET UNION WILL COMMENCE HOSTILITIES IN THE CARRIBEAN THEATRE WITH CONVENTIONAL AND POSSIBLY CHEMICAL WEAPONS. NUCLEAR RELEASE IS NOT ANTICIPATED AT THIS TIME BUT MAY OCCUR WITHOUT WARNING. <BR>'..
'<BR>'..
'ALL US FORCES ARE TO SET DEFCON 2. PREPARE IMMEDIATELY TO DEFEND US INTERESTS AND ASSETS AGAINST HOSTILE ACTION.<BR>'..
'<BR>'..
'GOOD LUCK, AND GOD HELP US ALL -SECDEF SENDS.'..
'</P>'..
'<P><FONT face=Consolas>TOP SECRET'..'\\'..'\\'..'</FONT></P>')

SetDefcon(2)
end
end

if defc <2 and ussr == 'true' then --if the soviet union is hostile and defcon is less than 2 then a nuclear strike will be performed against US cities
ScenEdit_SetDoctrine({side='Soviet Union'},{use_nuclear_weapons=true})
cities={
{name='Miami',lat='25.7899995628736',lon='-80.189208984375'},
{name='New Orleans',lat='29.952554831951',lon='-90.0920104980469'},
{name='Dallas',lat='32.8057447329069',lon='-96.83349609375'},
{name='Nashville',lat='36.1733569352216',lon='-86.81396484375'},
{name='Washington',lat='38.8910328264885',lon='-77.01416015625'},
{name='Charlotte',lat='35.2276723549358',lon='-80.88134765625'},
{name='New York',lat='40.7306084777966',lon='40.7306084777966'},
{name='Albuquerue',lat='35.1019340572461',lon='-106.6552734375'},
}
for i=1,#cities do
x = ScenEdit_AddUnit({side='United States',type='facility',dbid='100',name=cities[i].name,latitude=cities[i].lat,longitude=cities[i].lon,autodetectable='true'})
ScenEdit_AssignUnitAsTarget(x.guid, 'Nuclear Strike')
ScenEdit_AssignUnitAsTarget(x.guid, 'MRBMs')
end
end
*****************************************************************EXAMPLE OF INIT KEYS EN MASS
keyships={
'DD765','DD872','DD697','DD933','DD943','DD850','AE17','DD697','DD701','DD704','DD707','DD753','DD775','DDG11','DDG4','DD942','AO55','DDR863','DDR879','CA148','DLG14','CAG2','DD710','DLG8','DD763','AO27','DD878',
'DD471'
}

for i = 1,#keyships do
ScenEdit_SetKeyValue(keyships[i],'false')
end
**********************************************************EXAMPLE OF A LUA INIT WITH SOME COOL FUNC thanks to APACHE85 for the following
math.randomseed(os.time())

function round(num, numDecimalPlaces)
  local mult = 10^(numDecimalPlaces or 0)
  return math.floor(num * mult + 0.5) / mult
end

function DTG ()
TimeVar = ScenEdit_CurrentTime()
TimeVar = TimeVar + 4070908800 -- add seconds to bring year up to 2099 (+129 years)
a = os.date("!*t",TimeVar) -- build timestamp table
months={'JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'}
msgtime = a.day .. string.format('%02d',a.hour) .. string.format('%02d',a.min) .. 'Z ' .. months[a.month] ..' ' .. (a.year-2029)
return msgtime
end

function GetTension()
local current_tension=tonumber(ScenEdit_GetKeyValue('tension'))
return current_tension
end

function ChangeTension(tension_mod)
local current_tension=tonumber(ScenEdit_GetKeyValue('tension'))
local new_tension=tostring(current_tension+tension_mod)
ScenEdit_SetKeyValue('tension',new_tension)
local new_tension = ScenEdit_GetKeyValue('tension')
return ("Tension is now " .. new_tension)
end

function SetTension(tension_value)
ScenEdit_SetKeyValue('tension',tostring(tension_value))
return ("Tension is now " .. tension_value)
end

--Sets up SA2 Launch parameters for later quick recall
function SA2_Launch(current_tension)
chance = math.random(1,100)
count = 0
count_act = 0
	if chance <= current_tension then
	print ('Criteria met for SAM launch - chance roll '..chance..'; tension level '..current_tension)
		for i=1,28 do 
		print ('Checking status of SA-2 site '..i..'...')
		x = ScenEdit_GetUnit({side='Cuba',name='SAM BN (SA-2c) '..i})
			if x ~= nil then
				count = count + 1
				print ('Alive.')
				local roll = math.random(1,100)
				print ('Checking probability of going weapons free...')
				if roll <= current_tension then
				print ('Criteria met. SA-2 site '..i..' going weapons free.')
				ScenEdit_SetDoctrine({side=x.side,guid=x.guid}, {weapon_control_status_air='0'})
				count_act = count_act + 1
				else print ('Criteria *NOT* met. SA-2 site '..i..' ROE unchanged.')
				end
			else print ('Not alive.')
			end
		end
	else
	print ('Criteria *NOT* met for SAM launch - chance roll '..chance..'; needed '..current_tension..' or less.')
	end
	count_perc = round((count_act/count)*100,2)
	print ('Check concluded, ' ..count.. ' of 28 SA-2s are alive, of which ' ..count_act.. ' ('..count_perc..'%) went weapons free.' )
end

function SetDefcon(new_defcon)
ScenEdit_SetKeyValue('defcon', tostring(new_defcon))
print ('Defcon is now '..new_defcon)
end

function GetDefcon()
local defcon = tonumber(ScenEdit_GetKeyValue('defcon'))
return defcon
end

function ChangeDefcon(defcon_mod)
local defcon = tonumber(ScenEdit_GetKeyValue('defcon'))
local defcon = tostring(defcon+defcon_mod)
ScenEdit_SetKeyValue('defcon',defcon)
print ('Defcon is now '.. defcon)
return defcon
end

function ChangeScore(side,amt,reason)
local side = tostring(side)
local current_score = ScenEdit_GetScore(side)
local current_score = current_score + amt
local reason = tostring(reason)
ScenEdit_SetScore('United States',current_score,reason)
end



function ConvertPosDeg(latitude,longitude)

if latitude > 0 then
lat_desc = "N"
elseif latitude < 0 then
lat_desc = "S"
latitude = latitude*-1
end

local lat_degrees = math.floor(latitude) --seperate degrees
local lat_minutes = math.floor((latitude - lat_degrees)*60) --determine minutes
local lat_seconds = (((latitude-lat_degrees)*60) - lat_minutes)*60
local lat_seconds = round(lat_seconds, 0)

if longitude > 0 then
lon_desc = "E"
elseif longitude < 0 then
lon_desc = "W"
longitude = longitude*-1
end

local lon_degrees = math.floor(longitude) --seperate degrees
local lon_minutes = math.floor((longitude - lon_degrees)*60) --determine minutes
local lon_seconds = (((longitude-lon_degrees)*60) - lon_minutes)*60
local lon_seconds = round(lon_seconds, 0)

return (lat_desc..lat_degrees .. "°" .. lat_minutes .. "'" .. lat_seconds .. '", '..lon_desc..lon_degrees .. "°" .. lon_minutes .. "'" .. lon_seconds .. '"')
end
***************************************************CHECKING DBID WITH UNITX
detectedUnit = ScenEdit_UnitX()
if detectedUnit.dbid == 709 then
ScenEdit_SetUnit({guid=detectedUnit.guid,autodetectable=true})
end
******************************************RANDOM CIVVIE AIRLINERS
airliners = {
{dbid=3278,loadout=7691, range=4970}, --Douglas DC-8-50; 4970nm
{dbid=94,loadout=2700, range=2800}, --707-120B; 2800nm
{dbid=3125,loadout=7589, range=4500}, --Douglas DC-8-30; 4500nm
{dbid=2868,loadout=3842, range=2410}, --L-188A Electra; 2410nm
{dbid=3178,loadout=3796, range=3510}, --Il-18 Coot; 3510nm
{dbid=3568,loadout=8522, range=910}, --F.27-200 Friendship; 910nm
{dbid=3177,loadout=7700, range=1335}, --Britannia; 1335nm
{dbid=3126,loadout=7699, range=5000}, --L-1049 Constellation; 5000nm
{dbid=3180,loadout=7705, range=1037}, --DC-7; 1037nm
{dbid=3124,loadout=7586, range=1037}, --DC-4; 1037nm
{dbid=3123,loadout=7583, range=1037}, --DC-6; 1037nm
{dbid=3555,loadout=8482, range=1400}, --C-47A Dakota; 1400nm
{dbid=3176,loadout=7692, range=1037}, --Li-2 Cab; 1037nm
{dbid=3567,loadout=8524, range=910}, --F.27-400 Friendship; 910nm
{dbid=3604,loadout=8648, range=980}, --SE-210 Caravelle III; 980nm
}

airports_blue = {
"Houston",
"Jacksonville",
"Miami",
"New Orleans",
"Tampa"
}

airports_red = {
"Camaguey",
"Havana",
"Santa Maria"
}

airports_green = {
"Belize City",
"Bogota",
"Caracas",
"Managua",
"Merida",
"Nassau",
"Panama City",
"Port-au-Prince",
"San Juan",
"Santo Domingo",
"Tegulcipa"
}

--add 15 aircraft to CONUS airports
--assign CONUS aircraft to neutral country destinations
for i = 1,15 do
	ac_type = math.random(1,#airliners)
	x = ScenEdit_AddUnit({side='Civilian',type='aircraft',name='Civilian Aircraft '..i,dbid=airliners[ac_type].dbid,loadoutid=airliners[ac_type].loadout,base=airports_blue[math.random(1,#airports_blue)]})
	-- ScenEdit_SetLoadout({UnitName=x.guid,LoadoutID=0,TimeToReady_Minutes=math.random(0,360),IgnoreMagazines=true,ExcludeOptionalWeapons=false})
	origin = x.guid
	counter = 0
	::redo_destination::
	destination = ScenEdit_GetUnit({side='Civilian',name=airports_green[math.random(1,#airports_green)]})
		distance = Tool_Range(origin, destination.guid)
		if distance <= (airliners[ac_type].range*.95) then
		ScenEdit_AssignUnitToMission(x.guid,destination.name)
		else
		counter = counter + 1
		if counter <= 25 then
		goto redo_destination
		else ScenEdit_DeleteUnit({guid=x.guid})
		print ('Unable to find suitable destination for aircraft, unit deleted')
		end
end
end


--add 9 aircraft to Cuban airports
--assign Cuban aircraft to neutral country destinations
for i = 16,24 do
	ac_type = math.random(1,#airliners)
	x = ScenEdit_AddUnit({side='Civilian',type='aircraft',name='Civilian Aircraft '..i,dbid=airliners[ac_type].dbid,loadoutid=airliners[ac_type].loadout,base=airports_red[math.random(1,#airports_red)]})
	-- ScenEdit_SetLoadout({UnitName=x.guid,LoadoutID=0,TimeToReady_Minutes=math.random(0,360),IgnoreMagazines=true,ExcludeOptionalWeapons=false})
	origin = x.guid
	counter = 0
	::redo_destination::
	destination = ScenEdit_GetUnit({side='Civilian',name=airports_green[math.random(1,#airports_green)]})
		distance = Tool_Range(origin, destination.guid)
		if distance <= (airliners[ac_type].range*.95) then
		ScenEdit_AssignUnitToMission(x.guid,destination.name)
		else
		counter = counter + 1
		if counter <= 25 then
		goto redo_destination
		else ScenEdit_DeleteUnit({guid=x.guid})
		print ('Unable to find suitable destination for aircraft, unit deleted')
		end
end
end


--add 25 aircraft to neutral airports
--assign neutral aircraft to red, green or blue country destinations
for i = 25,50 do
	ac_type = math.random(1,#airliners)
	x = ScenEdit_AddUnit({side='Civilian',type='aircraft',name='Civilian Aircraft '..i,dbid=airliners[ac_type].dbid,loadoutid=airliners[ac_type].loadout,base=airports_green[math.random(1,#airports_green)]})
	-- ScenEdit_SetLoadout({UnitName=x.guid,LoadoutID=0,TimeToReady_Minutes=math.random(0,360),IgnoreMagazines=true,ExcludeOptionalWeapons=false})
	origin = x.guid
	counter = 0
	::redo_destination::
	chance = math.random(1,100)
	if chance <= 33 then
	destination = ScenEdit_GetUnit({side='Civilian',name=airports_blue[math.random(1,#airports_blue)]})
	elseif chance >33 and chance <= 66 then
	destination = ScenEdit_GetUnit({side='Civilian',name=airports_red[math.random(1,#airports_red)]})
	else
	destination = ScenEdit_GetUnit({side='Civilian',name=airports_green[math.random(1,#airports_green)]})
	end
		distance = Tool_Range(origin, destination.guid)
		if distance <= (airliners[ac_type].range*.95) then
		ScenEdit_AssignUnitToMission(x.guid,destination.name)
		else
		counter = counter + 1
		if counter <= 25 then
		goto redo_destination
		else ScenEdit_DeleteUnit({guid=x.guid})
		print ('Unable to find suitable destination for aircraft, unit deleted')
		end
end
end
*****************************************************************A WICKED WICKED SCRIPT FOR MERCHANT TRAFFIC, APACHE85
RecNames={ --whole list of 40 recreational civilian shipping names
'Ad Lib',
'Addiction',
'Alibi',
'Ambrosia',
'Baraka',
'Blue Moon',
'Bravelove One',
'Calypso',
'Carpe Diem',
'Cleopatra',
'Da Vinci',
'Diamonds are Forever',
'Double Down',
'Ecstasea',
'Element',
'Falcon',
'Fortunate Son',
'Freedom',
'Golden Eagle',
'Here Comes the Sun',
'Happy Days',
'High Power III',
'Illusion',
'Imagine',
'Huntress',
'Honey',
'Incognito',
'Invader',
'Jazz',
'Katya',
'La Familia',
'Liberty',
'Match Point',
'Mayan Queen IV',
'Missing Link',
'Octopus',
'Never Enough',
'Odyssey',
'Pure Bliss',
'Queen K',
'Ranger',
'Rebel'
}

CommNames={ --whole list of 50 commercial shipping names (tanker, freighter etc)
'Aquitania',
'Braverus',
'Buccleuch',
'Cape Cross',
'Cape Bay',
'Cape Falcon',
'Cape Flamingo',
'Cape Heron',
'Cape Osprey',
'Cape Owl',
'Cape Stork',
'Viktorius',
'Castro del Gato',
'Cheshire',
'Colossus',
'Cotswold',
'Divinus',
'Duhallow',
'Falcon Bay',
'Fortune Bay',
'Fortune Symphony',
'Galileo',
'Geraldine Manx',
'Giants Causeway',
'Good Hope Max',
'Grasshopper',
'Iron Baron',
'Imperius',
'Iron King',
'James Prior',
'Kite Bay',
'Lena B',
'Mecsca',
'Miden Max',
'Mykonos Bay',
'Newcastle Max',
'Nicoline Bulker',
'Nordic London',
'Nordic Riga',
'Nordic Stockholm',
'Nordic Visby',
'Ocean Prefect',
'Ocean Prelate',
'Olympius',
'Paradise Bay',
'Power Ranger',
'Premiership',
'Ronez',
'Sadlers Wells',
'Spartacus',
'Ten Jin Maru',
'St Helen'
}

PassNames={ --whole list of 10 passenger liner names
 'Allure Of The Seas',
 'Carnival Fascination',
 'Carnival Triumph',
 'Discovery Sun',
 'Explorer',
 'Freedom of the Seas',
 'Island Sky',
 'Ocean Atlantic',
 'Sea Spirit',
 'Superstar Aquarius'
 }

PortsList={ --pick a spot about 500nm from 
{name='New York',lat='38.4440318744518',lon='-68.9560680532455'},
{name='Charleston',lat='30.3749210197173',lon='-75.3161648292784'},
{name='Puerto Rico',lat='22.8842259527748',lon='-65.6117626768429'},
{name='Norfolk',lat='36.9441524589682',lon='-70.706424500571'},
{name='Europe',lat='48.4779364217548',lon='-14.1474559422142'},
{name='Mediterranean',lat='35.8721060939385',lon='-16.3914889155807'},
{name='Rio',lat='3.59777786410625', lon='-33.821988066078'},
{name='Africa',lat='13.0842538134051', lon='-26.0656761999737'},
}

NewYorkCourses={
{ [1] = { latitude = 18.5558903646358, longitude = -65.7506832671963 }, [2] = { latitude = 32.3281138795531, longitude = -79.2268424854963 }, [3] = { latitude = 35.1368215306519, longitude = -74.7131658745226 }, [4] = { latitude = 40.9960270745726, longitude = -71.2759258459458 } }, --NY>Puerto Rico>Charleston>NY
{ [1] = { latitude = 35.3024062652305, longitude = -74.5466808745456 }, [2] = { latitude = 32.0022752247357, longitude = -78.9558846012704 }, [3] = { latitude = 32.388995067276, longitude = -79.8902268043437 }, [4] = { latitude = 32.8416654150468, longitude = -64.7205181494919 }, [5] = { latitude = 30.7968452003296, longitude = -22.7989755535131 } }, --NY>Charleston>Bermuda>Europe
{ [1] = { latitude = 32.5738616957264, longitude = -64.4078640880097 }, [2] = { latitude = 18.8388075551114, longitude = -67.8227306560902 }, [3] = { latitude = 17.9140886697514, longitude = -68.4047053677233 }, [4] = { latitude = 9.75995728374031, longitude = -80.1773885138617 }, [5] = { latitude = 8.42080145177386, longitude = -79.2933482841764 }, [6] = { latitude = -8.14356731963998, longitude = -83.5271791847107 } }, --NY>Bermuda>Haiti>Panama>Peru
{ [1] = { latitude = 35.0360148065714, longitude = -74.5449434315852 }, [2] = { latitude = 30.8793180566475, longitude = -80.3101109692012 }, [3] = { latitude = 26.2016521158212, longitude = -79.5632833385713 }, [4] = { latitude = 24.3732387621713, longitude = -80.2634109427392 }, [5] = { latitude = 24.1793435515593, longitude = -83.2436472368299 }, [6] = { latitude = 28.4788473733717, longitude = -85.045718520506 }, [7] = { latitude = 27.6904889769286, longitude = -96.4573802562824 } }, --coastal route to TX
{ [1] = { latitude = 32.7552203193599, longitude = -63.8259422675415 }, [2] = { latitude = 15.3197827050877, longitude = -59.6837061199895 }, [3] = { latitude = 8.157604772143, longitude = -56.0265715796616 }, [4] = { latitude = -0.776452539847026, longitude = -44.343344538672 } }, --Brazil via Bermuda
{ [1] = { latitude = 45.9595283326184, longitude = -52.3208226806464 }, [2] = { latitude = 49.1447132036107, longitude = -6.02789710090087 }, [3] = { latitude = 50.6415519704394, longitude = 1.13888007261481 }, [4] = { latitude = 51.7739279135582, longitude = 2.29035052221313 }, [5] = { latitude = 55.8698895776644, longitude = 4.81507503624832 } }, --north sea
{ [1] = { latitude = 35.8799054503605, longitude = -25.5947489441426 }, [2] = { latitude = 35.8700397425184, longitude = -6.36878022446037 }, [3] = { latitude = 36.3265205706774, longitude = -0.572054329022935 } }, --mediterranean
{ [1] = { latitude = 18.5361652939671, longitude = -19.0310185748667 }, [2] = { latitude = 10.0826890075239, longitude = -17.9694398653663 }, [3] = { latitude = 4.10428676312167, longitude = -9.95701711772331 }, [4] = { latitude = 2.3699318740236, longitude = -0.953036234437398 } } --to Africa
}

CharlestonCourses={
{ [1] = { latitude = 19.0204346734694, longitude = -68.0957994697869 }, [2] = { latitude = 17.4532024057405, longitude = -68.1212860592674 }, [3] = { latitude = 12.7404907125251, longitude = -68.2377006624442 }, [4] = { latitude = 11.5999924069319, longitude = -61.7820725895743 }, [5] = { latitude = 11.6186709913839, longitude = -60.5586868025243 }, [6] = { latitude = 0.0559385178089867, longitude = -43.6736865030208 } }, --carribean and coastal route along south america
{ [1] = { latitude = 18.5558903646358, longitude = -65.7506832671963 }, [2] = { latitude = 32.3281138795531, longitude = -79.2268424854963 }, [3] = { latitude = 35.1368215306519, longitude = -74.7131658745226 }, [4] = { latitude = 40.9960270745726, longitude = -71.2759258459458 } }, --Puerto Rico>Charleston>NY
{ [1] = { latitude = 32.5738616957264, longitude = -64.4078640880097 }, [2] = { latitude = 18.8388075551114, longitude = -67.8227306560902 }, [3] = { latitude = 17.9140886697514, longitude = -68.4047053677233 }, [4] = { latitude = 9.75995728374031, longitude = -80.1773885138617 }, [5] = { latitude = 8.42080145177386, longitude = -79.2933482841764 }, [6] = { latitude = -8.14356731963998, longitude = -83.5271791847107 } }, --NY>Bermuda>Haiti>Panama>Peru
{ [1] = { latitude = 30.8793180566475, longitude = -80.3101109692012 }, [2] = { latitude = 26.2016521158212, longitude = -79.5632833385713 }, [3] = { latitude = 24.3732387621713, longitude = -80.2634109427392 }, [4] = { latitude = 24.1793435515593, longitude = -83.2436472368299 }, [5] = { latitude = 28.4788473733717, longitude = -85.045718520506 }, [6] = { latitude = 28.0923448090519, longitude = -95.9168230981626 }, [7] = { latitude = 18.8107088779484, longitude = -82.0541432212781 }, [8] = { latitude = 9.57379828781344, longitude = -79.9534429715542 } }, --coastal route to Tx and off to Panama
{ [1] = { latitude = 32.7552203193599, longitude = -63.8259422675415 }, [2] = { latitude = 15.3197827050877, longitude = -59.6837061199895 }, [3] = { latitude = 8.157604772143, longitude = -56.0265715796616 }, [4] = { latitude = -0.776452539847026, longitude = -44.343344538672 } }, --Brazil via Bermuda
{ [1] = { latitude = 45.9595283326184, longitude = -52.3208226806464 }, [2] = { latitude = 49.1447132036107, longitude = -6.02789710090087 }, [3] = { latitude = 50.6415519704394, longitude = 1.13888007261481 }, [4] = { latitude = 51.7739279135582, longitude = 2.29035052221313 }, [5] = { latitude = 55.8698895776644, longitude = 4.81507503624832 } }, --north sea
{ [1] = { latitude = 35.8799054503605, longitude = -25.5947489441426 }, [2] = { latitude = 35.8700397425184, longitude = -6.36878022446037 }, [3] = { latitude = 36.3265205706774, longitude = -0.572054329022935 } }, --mediterranean
{ [1] = { latitude = 18.5361652939671, longitude = -19.0310185748667 }, [2] = { latitude = 10.0826890075239, longitude = -17.9694398653663 }, [3] = { latitude = 4.10428676312167, longitude = -9.95701711772331 }, [4] = { latitude = 2.3699318740236, longitude = -0.953036234437398 } } --to Africa
}

PuertoRicoCourses={
{ [1] = { latitude = 19.0204346734694, longitude = -68.0957994697869 }, [2] = { latitude = 17.4532024057405, longitude = -68.1212860592674 }, [3] = { latitude = 12.7404907125251, longitude = -68.2377006624442 }, [4] = { latitude = 11.5999924069319, longitude = -61.7820725895743 }, [5] = { latitude = 11.6186709913839, longitude = -60.5586868025243 }, [6] = { latitude = -17.1542639676774, longitude = -8.42419088901781 } }, --Carribean then coastal route to Africa
{ [1] = { latitude = 20.6216543148175, longitude = -73.5164583183621 }, [2] = { latitude = 19.30285512831, longitude = -74.5073855664511 }, [3] = { latitude = 19.3930307803975, longitude = -77.6186829226025 }, [4] = { latitude = 21.6402580316185, longitude = -85.8375097450011 }, [5] = { latitude = 22.1837688595988, longitude = -89.6804132617287 }, [6] = { latitude = 19.0091238555388, longitude = -94.4569217396816 }, [7] = { latitude = 22.7857952329307, longitude = -97.2622733304275 }, [8] = { latitude = 28.7852812211121, longitude = -93.0298985956471 }, [9] = { latitude = 28.5782368975241, longitude = -84.3156801042033 }, [10] = { latitude = 24.0812610073133, longitude = -82.182014887079 }, [11] = { latitude = 24.0839183422896, longitude = -79.7228060598198 } }, --long run around Cuba and GoM
{ [1] = { latitude = 20.7474040585229, longitude = -74.466920221535 }, [2] = { latitude = 23.5138840443822, longitude = -74.4987805079278 }, [3] = { latitude = 27.0542168559546, longitude = -77.1149243757563 }, [4] = { latitude = 40.9211945045429, longitude = -71.0689636807278 }, [5] = { latitude = 49.4874836290601, longitude = -4.59635206812713 } }, --Charleston & NY & UK via Bahamas
{ [1] = { latitude = 40.8500038715918, longitude = -70.8678679009526 }, [2] = { latitude = 39.9895874101671, longitude = -73.3543906378237 }, [3] = { latitude = 36.9657726391144, longitude = -75.524832459451 }, [4] = { latitude = 12.2997021031877, longitude = -65.6534490562906 } }, --US east coast return
{ [1] = { latitude = 32.8098795383768, longitude = -65.7929245230212 }, [2] = { latitude = 35.1387502508422, longitude = -7.84663713123045 } }, --med via bermuda
{ [1] = { latitude = 40.4771143635316, longitude = -70.9535784901039 }, [2] = { latitude = 32.4294893369819, longitude = -64.0047531380262 }, [3] = { latitude = 17.4164402678104, longitude = -67.858227357884 }, [4] = { latitude = 9.72978564986033, longitude = -80.154461874861 } }, --panama via Newport
{ [1] = { latitude = 27.4939690141115, longitude = -77.2523644198484 }, [2] = { latitude = 30.4493949485937, longitude = -80.9605553114299 }, [3] = { latitude = 32.256060059132, longitude = -79.4736147022717 }, [4] = { latitude = 21.9973812985282, longitude = -71.240177852346 }, [5] = { latitude = 17.6834697796141, longitude = -60.0376005890491 }, [6] = { latitude = 4.85144606340143, longitude = -51.0465666195443 } }, --Brazil via Jacksonville & Charleston
{ [1] = { latitude = 49.1447132036107, longitude = -6.02789710090087 }, [2] = { latitude = 50.6415519704394, longitude = 1.13888007261481 }, [3] = { latitude = 51.7739279135582, longitude = 2.29035052221313 }, [4] = { latitude = 55.8698895776644, longitude = 4.81507503624832 } } --north sea
}

NorfolkCourses={
{ [1] = { latitude = 18.5558903646358, longitude = -65.7506832671963 }, [2] = { latitude = 32.3281138795531, longitude = -79.2268424854963 }, [3] = { latitude = 35.1368215306519, longitude = -74.7131658745226 }, [4] = { latitude = 40.9960270745726, longitude = -71.2759258459458 } }, --NY>Puerto Rico>Charleston>NY
{ [1] = { latitude = 35.3024062652305, longitude = -74.5466808745456 }, [2] = { latitude = 32.0022752247357, longitude = -78.9558846012704 }, [3] = { latitude = 32.388995067276, longitude = -79.8902268043437 }, [4] = { latitude = 32.8416654150468, longitude = -64.7205181494919 }, [5] = { latitude = 30.7968452003296, longitude = -22.7989755535131 } }, --NY>Charleston>Bermuda>Europe
{ [1] = { latitude = 32.5738616957264, longitude = -64.4078640880097 }, [2] = { latitude = 18.8388075551114, longitude = -67.8227306560902 }, [3] = { latitude = 17.9140886697514, longitude = -68.4047053677233 }, [4] = { latitude = 9.75995728374031, longitude = -80.1773885138617 }, [5] = { latitude = 8.42080145177386, longitude = -79.2933482841764 }, [6] = { latitude = -8.14356731963998, longitude = -83.5271791847107 } }, --NY>Bermuda>Haiti>Panama>Peru
{ [1] = { latitude = 35.0360148065714, longitude = -74.5449434315852 }, [2] = { latitude = 30.8793180566475, longitude = -80.3101109692012 }, [3] = { latitude = 26.2016521158212, longitude = -79.5632833385713 }, [4] = { latitude = 24.3732387621713, longitude = -80.2634109427392 }, [5] = { latitude = 24.1793435515593, longitude = -83.2436472368299 }, [6] = { latitude = 28.4788473733717, longitude = -85.045718520506 }, [7] = { latitude = 27.6904889769286, longitude = -96.4573802562824 } }, --coastal route to TX
{ [1] = { latitude = 32.7552203193599, longitude = -63.8259422675415 }, [2] = { latitude = 15.3197827050877, longitude = -59.6837061199895 }, [3] = { latitude = 8.157604772143, longitude = -56.0265715796616 }, [4] = { latitude = -0.776452539847026, longitude = -44.343344538672 } }, --Brazil via Bermuda
{ [1] = { latitude = 45.9595283326184, longitude = -52.3208226806464 }, [2] = { latitude = 49.1447132036107, longitude = -6.02789710090087 }, [3] = { latitude = 50.6415519704394, longitude = 1.13888007261481 }, [4] = { latitude = 51.7739279135582, longitude = 2.29035052221313 }, [5] = { latitude = 55.8698895776644, longitude = 4.81507503624832 } }, --north sea
{ [1] = { latitude = 35.8799054503605, longitude = -25.5947489441426 }, [2] = { latitude = 35.8700397425184, longitude = -6.36878022446037 }, [3] = { latitude = 36.3265205706774, longitude = -0.572054329022935 } }, --mediterranean
{ [1] = { latitude = 18.5361652939671, longitude = -19.0310185748667 }, [2] = { latitude = 10.0826890075239, longitude = -17.9694398653663 }, [3] = { latitude = 4.10428676312167, longitude = -9.95701711772331 }, [4] = { latitude = 2.3699318740236, longitude = -0.953036234437398 } } --to Africa
}

EuropeCourses={
{ [1] = { latitude = 19.5423175055227, longitude = -64.2017458328187 }, [2] = { latitude = 20.5276422753366, longitude = -73.1306148049436 } }, 
--Puerto Rico
{ [1] = { latitude = 40.3363018798185, longitude = -68.1503813768766 }, [2] = { latitude = 32.7358953680214, longitude = -77.5388643934872 }, [3] = { latitude = 24.7980498269418, longitude = -79.8763078004708 } }, --US east coast through to GoM
{ [1] = { latitude = 20.8443119276285, longitude = -70.1121123238985 }, [2] = { latitude = 20.2178300963885, longitude = -73.6785518196017 }, [3] = { latitude = 9.83705523110801, longitude = -80.3802659680786 } }, --Panama canal
{ [1] = { latitude = 32.3487635523597, longitude = -63.8302920719605 }, [2] = { latitude = -1.58828249505997, longitude = -42.8159108941334 } }, 
--Bermuda - Brazil
{ [1] = { latitude = 40.7422376692689, longitude = -70.6458298394809 }, [2] = { latitude = 34.5257381438096, longitude = -20.3545218141453 }, [3] = { latitude = 35.718043817172, longitude = -6.48637377473014 } }, 
--med via NY
{ [1] = { latitude = 36.3195565387546, longitude = -24.494309624581 }, [2] = { latitude = 19.5693964098698, longitude = -68.9352346975938 } }, 
--puerto rico via azores
{ [1] = { latitude = 44.0712672746532, longitude = -62.0777739575262 }, [2] = { latitude = -1.01011780932301, longitude = -43.8789922250673 } }, 
--brazil via halifax
{ [1] = { latitude = 31.906627832534, longitude = -64.6031492116329 }, [2] = { latitude = 30.5551023522284, longitude = -80.7462704526204 }, [3] = { latitude = 26.4987840099707, longitude = -79.414583670351 } } --Bermuda, florida straits
}

MediterraneanCourses={
{ [1] = { latitude = 31.906627832534, longitude = -64.6031492116329 }, [2] = { latitude = 30.5551023522284, longitude = -80.7462704526204 }, [3] = { latitude = 26.4987840099707, longitude = -79.414583670351 } }, --Bermuda, florida straits
{ [1] = { latitude = 36.3195565387546, longitude = -24.494309624581 }, [2] = { latitude = 19.5693964098698, longitude = -68.9352346975938 } }, 
--puerto rico via azores
{ [1] = { latitude = 40.7422376692689, longitude = -70.6458298394809 }, [2] = { latitude = 34.5257381438096, longitude = -20.3545218141453 }, [3] = { latitude = 35.718043817172, longitude = -6.48637377473014 } }, --med via NY
{ [1] = { latitude = 20.8443119276285, longitude = -70.1121123238985 }, [2] = { latitude = 20.2178300963885, longitude = -73.6785518196017 }, [3] = { latitude = 9.83705523110801, longitude = -80.3802659680786 } }, --Panama canal
{ [1] = { latitude = 30.2212307557628, longitude = -79.6145905961671 }, [2] = { latitude = 24.1684316921971, longitude = -79.8347195466145 }, [3] = { latitude = 23.7170366296924, longitude = -84.351584593536 } }, --US east coast through to GoM
{ [1] = { latitude = 40.1386179114382, longitude = -32.1243107288875 }, [2] = { latitude = 18.1921901791824, longitude = -63.8943081028816 }, [3] = { latitude = 12.2378533259643, longitude = -64.9969129691809 } }, --Azores to Venezuela
{ [1] = { latitude = 32.3487635523597, longitude = -63.8302920719605 }, [2] = { latitude = -1.58828249505997, longitude = -42.8159108941334 } }, 
--Bermuda - Brazil
{ [1] = { latitude = 33.5408948365048, longitude = -18.3384855685071 }, [2] = { latitude = 7.33185273378324, longitude = -56.0944318006396 }, [3] = { latitude = 33.0678179450334, longitude = -75.1022049188768 } }
--Brazil - NY
}

RioCourses={
{ [1] = { latitude = 11.9054310470606, longitude = -60.3565188439721 }, [2] = { latitude = 11.4099886093259, longitude = -62.1084835155942 }, [3] = { latitude = 18.733503689345, longitude = -82.893284814631 }, [4] = { latitude = 26.2700703773381, longitude = -90.1849849463467 } }, 
--GoM
{ [1] = { latitude = 39.9988412551035, longitude = -73.1199851130537 }, [2] = { latitude = 36.7823071422843, longitude = -75.5323888873247 } },
--NY
{ [1] = { latitude = 19.3300019058249, longitude = -62.3117218608124 }, [2] = { latitude = 20.5380058782236, longitude = -73.627273897316 }, [3] = { latitude = 9.99932226668649, longitude = -79.664333621807 } },
--Panama via Puerto Rico
{ [1] = { latitude = 32.2360637934034, longitude = -63.781236040591 }, [2] = { latitude = 18.9374498119704, longitude = -67.596055377178 } }
--Bermuda - Puerto Rico
}

AfricaCourses={
{ [1] = { latitude = 11.9054310470606, longitude = -60.3565188439721 }, [2] = { latitude = 11.4099886093259, longitude = -62.1084835155942 }, [3] = { latitude = 18.733503689345, longitude = -82.893284814631 }, [4] = { latitude = 26.2700703773381, longitude = -90.1849849463467 } }, 
--GoM
{ [1] = { latitude = 39.9988412551035, longitude = -73.1199851130537 }, [2] = { latitude = 36.7823071422843, longitude = -75.5323888873247 } },
--NY
{ [1] = { latitude = 19.3300019058249, longitude = -62.3117218608124 }, [2] = { latitude = 20.5380058782236, longitude = -73.627273897316 }, [3] = { latitude = 9.99932226668649, longitude = -79.664333621807 } },
--Panama via Puerto Rico
{ [1] = { latitude = 32.2360637934034, longitude = -63.781236040591 }, [2] = { latitude = 18.9374498119704, longitude = -67.596055377178 } }
--Bermuda - Puerto Rico
}

RecTypes={ --dbids; try to make sure they'll run for a week on cruise
{dbid=603,prefix='MY '},--motor yacht 38m
{dbid=664,prefix='SV '}, --civilian sailboat 23m
{dbid=665,prefix='SY '} --civilian sailboat 38m
}

CommTypes={ --dbids; try to make sure they'll run for a week on cruise
{dbid=1867,prefix='MV '}, --feedermax 30,000
{dbid=287,prefix='MV '}, --supply vessel 6,000
{dbid=1318,prefix='MTS '}, --ocean going tug
{dbid=256,prefix='LPG/C '}, --LNG/LPG tanker
{dbid=2117,prefix='FT '}, --factory trawler
{dbid=273,prefix='MV '},--dry bulk 45,000
{dbid=650,prefix='MV '},--dry bulk 25,000
{dbid=651,prefix='MT '}, --tanker
{dbid=580,prefix='AOG '}, --tanker LR
{dbid=2118,prefix='FV '},--large trawler
{dbid=508,prefix='FV '} --fishing boat 35m
}

PassTypes={ --dbids; try to make sure they'll run for a week on cruise
{dbid=285,prefix='MS '},--cruise liner
{dbid=285,prefix='MS '},--cruise liner
{dbid=285,prefix='MS '},--cruise liner (included x 3 for 75% population)
{dbid=509,prefix='MS '},  --ferry (might not make a week at cruise
{dbid=603,prefix='MSY '} --motor yacht 38m
}

for i=1,40 do

port = PortsList[math.random(1,#PortsList)] 

	if port.name == 'New York' then --choose a course
	coursePlot = NewYorkCourses[math.random(1,#NewYorkCourses)] --adjust for civ vs merch traffic

	elseif port.name == 'Charleston' then
	coursePlot = CharlestonCourses[math.random(1,#CharlestonCourses)]

	elseif port.name == 'Puerto Rico' then
	coursePlot = PuertoRicoCourses[math.random(1,#PuertoRicoCourses)]

	elseif port.name == 'Norfolk' then
	coursePlot = NorfolkCourses[math.random(1,#NorfolkCourses)]

	elseif port.name == 'Europe' then
	coursePlot = EuropeCourses[math.random(1,#EuropeCourses)]

	elseif port.name == 'Mediterranean' then
	coursePlot = MediterraneanCourses[math.random(1,#MediterraneanCourses)]

	elseif port.name == 'Rio' then
	coursePlot = RioCourses[math.random(1,#RioCourses)]

	elseif port.name == 'Africa' then
	coursePlot = AfricaCourses[math.random(1,#AfricaCourses)]

	end

::redo_loc::
loc = World_GetCircleFromPoint({latitude=port.lat,longitude=port.lon,radius=math.random(0,1000)}) 
loc = loc[math.random(1,45)]
loc_elev = World_GetElevation({latitude=loc.Latitude,longitude=loc.Longitude})
if loc_elev > -25 then 
goto redo_loc
end

rand_type=math.random(1,#RecTypes)

ScenEdit_AddUnit({
side='Civilian',
name=RecTypes[rand_type].prefix .. RecNames[i],
type='Ship',
dbid=RecTypes[rand_type].dbid,
latitude=loc.Latitude,
longitude=loc.Longitude,
course=coursePlot})
end

for i=1,50 do

port = PortsList[math.random(1,4)] 

	if port.name == 'New York' then --choose a course
	coursePlot = NewYorkCourses[math.random(1,#NewYorkCourses)] --adjust for civ vs merch traffic

	elseif port.name == 'Charleston' then
	coursePlot = CharlestonCourses[math.random(1,#CharlestonCourses)]

	elseif port.name == 'Puerto Rico' then
	coursePlot = PuertoRicoCourses[math.random(1,#PuertoRicoCourses)]

	elseif port.name == 'Norfolk' then
	coursePlot = NorfolkCourses[math.random(1,#NorfolkCourses)]

	elseif port.name == 'Europe' then
	coursePlot = EuropeCourses[math.random(1,#EuropeCourses)]

	elseif port.name == 'Mediterranean' then
	coursePlot = MediterraneanCourses[math.random(1,#MediterraneanCourses)]

	elseif port.name == 'Rio' then
	coursePlot = RioCourses[math.random(1,#Rio)]

	elseif port.name == 'Africa' then
	coursePlot = AfricaCourses[math.random(1,#Africa)]

	end

::redo_loc::
loc = World_GetCircleFromPoint({latitude=port.lat,longitude=port.lon,radius=math.random(0,1000)}) 
loc = loc[math.random(1,45)]
loc_elev = World_GetElevation({latitude=loc.Latitude,longitude=loc.Longitude})
if loc_elev > -25 then 
goto redo_loc
end

rand_type=math.random(1,#CommTypes)

ScenEdit_AddUnit({
side='Civilian',
name=CommTypes[rand_type].prefix .. CommNames[i],
type='Ship',
dbid=CommTypes[rand_type].dbid,
latitude=loc.Latitude,
longitude=loc.Longitude,
course=coursePlot})
end

for i=1,10 do

port = PortsList[math.random(1,#PortsList)] 

	if port.name == 'New York' then --choose a course
	coursePlot = NewYorkCourses[math.random(1,#NewYorkCourses)] --adjust for civ vs merch traffic

	elseif port.name == 'Charleston' then
	coursePlot = CharlestonCourses[math.random(1,#CharlestonCourses)]

	elseif port.name == 'Puerto Rico' then
	coursePlot = PuertoRicoCourses[math.random(1,8)]

	elseif port.name == 'Norfolk' then
	coursePlot = NorfolkCourses[math.random(1,8)]

	elseif port.name == 'Europe' then
	coursePlot = EuropeCourses[math.random(1,8)]

	elseif port.name == 'Mediterranean' then
	coursePlot = MediterraneanCourses[math.random(1,8)]

	elseif port.name == 'Rio' then
	coursePlot = RioCourses[math.random(1,4)]

	elseif port.name == 'Africa' then
	coursePlot = AfricaCourses[math.random(1,4)]

	end

::redo_loc::
loc = World_GetCircleFromPoint({latitude=port.lat,longitude=port.lon,radius=math.random(0,1000)}) 
loc = loc[math.random(1,45)]
loc_elev = World_GetElevation({latitude=loc.Latitude,longitude=loc.Longitude})
if loc_elev > -25 then 
goto redo_loc
end

rand_type=math.random(1,#PassTypes)

ScenEdit_AddUnit({
side='Civilian',
name=PassTypes[rand_type].prefix .. PassNames[i],
type='Ship',
dbid=PassTypes[rand_type].dbid,
latitude=loc.Latitude,
longitude=loc.Longitude,
course=coursePlot})
end
*************************************CHECKS A LARGE LIST TO SEE IF ITS INCLUSIVE
--Cuba Airspace
ScenEdit_SetKeyValue('cuba_airspace','true')
x = ScenEdit_UnitX()
tvalue = nil

aircraft_type={
{type='A-1H',class='Attack',dbid=86,tens=math.random(15,20)},
{type='A-3B',class='Attack',dbid=91,tens=math.random(20,25)},
{type='A-4C',class='Attack',dbid=3315,tens=math.random(15,20)},
{type='A-4C',class='Attack',dbid=1622,tens=math.random(15,20)},
{type='B-47E-IV',class='Bomber',dbid=2191,tens=math.random(30,40)},
{type='B-52F',class='Bomber',dbid=103,tens=math.random(30,40)},
{type='E-1B',class='AEW',dbid=3093,tens=math.random(2,5)},
{type='EB-47E',class='ECM',dbid=157,tens=math.random(15,20)},
{type='EC-121M',class='AEW',dbid=3193,tens=math.random(2,5)},
{type='F-100A',class='Fighter',dbid=88,tens=math.random(10,15)},
{type='F-102A',class='Fighter',dbid=623,tens=math.random(10,15)},
{type='F-104A',class='Fighter',dbid=65,tens=math.random(10,15)},
{type='F-106A',class='Fighter',dbid=663,tens=math.random(10,15)},
{type='F-3B',class='Fighter',dbid=149,tens=math.random(10,15)},
{type='F-4B',class='Fighter',dbid=1625,tens=math.random(10,15)},
{type='F-6A',class='Fighter',dbid=3378,tens=math.random(10,15)},
{type='F-84F',class='Fighter',dbid=43,tens=math.random(10,15)},
{type='F-8C',class='Fighter',dbid=1596,tens=math.random(10,15)},
{type='F-8E',class='Fighter',dbid=1629,tens=math.random(10,15)},
{type='KB-50J',class='Tanker',dbid=293,tens=math.random(2,5)},
{type='P-2V',class='MPA',dbid=235,tens=math.random(2,5)},
{type='P-5M',class='MPA',dbid=351,tens=math.random(2,5)},
{type='RB-47H',class='Recon',dbid=160,tens=math.random(5,15)},
{type='RB-66C',class='Recon',dbid=3099,tens=math.random(5,15)},
{type='RF-101C',class='Recon',dbid=2751,tens=math.random(5,10)},
{type='RF-8A',class='Recon',dbid=1630,tens=math.random(5,10)},--USN
{type='RF-8A',class='Recon',dbid=3422,tens=math.random(5,10)},--USMC
{type='S-2F',class='ASW',dbid=1589,tens=math.random(2,5)},
{type='SH-34A',class='ASW',dbid=705,tens=math.random(2,5)},
{type='SH-3A',class='ASW',dbid=1636,tens=math.random(2,5)},
{type='U-2G',class='Recon',dbid=1890,tens=math.random(2,7)},
{type='UH-25B',class='Utility',dbid=674,tens=math.random(2,5)},
{type='UH-25C',class='Utility',dbid=700,tens=math.random(2,5)},
}

for i = 1,#aircraft_type do 
	if x.dbid == aircraft_type[i].dbid then
	tvalue = aircraft_type[i].tvalue
	ac_type = aircraft_type[i].type
	ac_name = aircraft_type[i].name
	print ('Aircraft recognised as type '..aircraft_type[i].type..'; tension roll '..aircraft_type[i].tens)
	end
end

if tvalue == nil then 
tvalue = math.random(0,10)
end

ChangeTension(tvalue)
current_tension = GetTension()

--checks tension and fires SA2_Launch function
if current_tension > 10 and current_tension < 50 then
print ('Tension threshold above 10 and less than 50, checking for SA-2 launch')
SA2_Launch(current_tension)
end

if current_tension > 50 then 
print ('Tension threshold above 50, checking for Cuba going hostile')
chance = math.random(1,100)
	if chance <= current_tension then
	ScenEdit_SetSidePosture('Cuba','United States','H')
	ScenEdit_SetSidePosture('United States','Cuba','H')
	print ('Criteria met for Cuba to go hostile; chance roll '..chance..', needed '..current_tension)
	ScenEdit_SpecialMessage
		('United States',
		'<P><FONT face=Consolas>' .. '\\'..'\\'..'FLASH'.. '\\'..'\\'..'FLASH'.. '\\'..'\\'..'FLASH<BR>' .. 
		'FROM: SECDEF<BR>' .. 
		'TO: ALL US FORCES<BR>' .. 
		'RE: WAR WARNING <BR>' ..
		msgtime..
		'<P><FONT face=Consolas>HUMINT SUGGESTS SIGNS OF IMMINENT HOSTILE ACTION BY CUBAN FORCES. PREPARE IMMEDIATELY TO DEFEND US INTERESTS AND ASSETS AGAINST HOSTILE ACTION.<BR>'.. 
		'<BR>'..
		'THERE IS NO INDICATION OF HOSTILE INTENTION BY THE SOVIET UNION AT THIS STAGE. DO NOT--REPEAT--DO NOT ENGAGE SOVIET FORCES.'..
		'<BR>'..
		'GOOD LUCK -SECDEF SENDS.'..
		'</P>'..
		'<P><FONT face=Consolas>TOP SECRET'..'\\'..'\\'..'</FONT></P>')
	else
	print ('Criteria NOT met for Cuba to go hostile; chance roll '..chance..', needed '..current_tension)
	end
end
*******************************************THIS DOES SOME CRZY RANDOM AIR OPS 
--0630 daily aircraft init
--set missions to active
missions = 
{'CAP Camaguey AB',
'CAP San Antonio AB',
'CAP San Julian AB',
'CAP Santa Maria AB',
'CAP Santiago de Cuba AB',
'ASuW Strike',
'Land Strike',
'Recon Cuidad Libertad AB',
'Recon La Isabella Naval Base',
'Recon Santiago de Cuba AB'
}

for i=1,#missions do
x = ScenEdit_GetMission('Cuba',missions[i])
x.isactive = true
end

tension = GetTension()
defcon = GetDefcon()
cuba = ScenEdit_GetKeyValue('Cuba_Hostile')
ussr = ScenEdit_GetKeyValue('USSR_Hostile')

recon_helos = {
{name='12th Esc. de Busqueda Det A', qty=2, base='Santiago de Cuba AB',dbid=2059,loadout=1430}, --2 bell 47 @ Santiago de Cuba, need random ready times
{name='12th Esc. de Busqueda Det B', qty=2, base='La Isabella Naval Base',dbid=2059,loadout=1430}, --2 bell 47 @ La Isabella, need random ready times
{name='12th Esc. de Busqueda Det C', qty=2, base='Cuidad Libertad AB',dbid=2059,loadout=1430}, --2 bell 47 @ Cuidad Libertad, need random ready times
}

for i = 1,#recon_helos do 
	for ii = 1,recon_helos[i].qty do
	x = ScenEdit_GetUnit({side='Cuba',name=recon_helos[i].name..' #'..ii})
		if x ~= nil then
		ScenEdit_SetLoadout({UnitName=x.guid,LoadoutID=0,TimeToReady_Minutes=math.random(0,180),IgnoreMagazines=true,ExcludeOptionalWeapons=false})
		end
	end
end

interceptors = {
{name='61st Esc. de Caza', qty=12, base='Santiago de Cuba AB',dbid=1699,loadout=1144}, --12 MiG-15 @ Santiago de Cuba, airfield defence, loadout guns only
{name='101st Esc. de Interceptador', qty=12, base='San Antonio AB',dbid=2067,loadout=1686}, --12 x MiG-19 @ San Antonio, primary air defence interceptors, loadout 2 x AA-2
{name='51st Esc. de Caza', qty=12, base='San Julian AB',dbid=1699,loadout=1144}, --12 MiG-15 @ San Julian, airfield defence, loadout guns only
{name='32nd Esc. de Caza', qty=12, base='Camaguey AB',dbid=2064,loadout=1673}, --12 MiG-17 @ Camaguey, loadout guns only
{name='22nd Esc. de Caza', qty=12, base='Santa Maria AB',dbid=2064,loadout=1673}, --12 MiG-17 @ Santa Maria, loadout guns only
}

--set random amount to maintenance
maintenance_perc = math.random(10,30)
for i = 1,#interceptors do 
	for ii = 1,interceptors[i].qty do
	x = ScenEdit_GetUnit({side='Cuba',name=interceptors[i].name..' #'..ii})
		if x ~= nil then
		chance = math.random(1,100)
			if chance <= maintenance_perc then
			loadout = 4
			else
			loadout = interceptors[i].loadout
			end
		ScenEdit_SetLoadout({UnitName=x.guid,LoadoutID=loadout,TimeToReady_Minutes=math.random(0,180),IgnoreMagazines=true,ExcludeOptionalWeapons=false})
		end
	end
end

--default airfield based intercept
for i = 1,#interceptors do 
	for ii = 1,interceptors[i].qty do
	x = ScenEdit_GetUnit({side='Cuba',name=interceptors[i].name..' #'..ii})
		if x ~= nil then
		ScenEdit_AssignUnitToMission(x.guid,'Airfield Intercept '..interceptors[i].base)
		end
	end
end

--if tension is above 30 or cuba is hostile then send up half of the squadron as CAP

if tension > 30  or cuba == 'true' then 
for i = 1,#interceptors do
		chance = math.random(1,100)
		if chance >= tension then
		sqn_strength = 0
		for ii = 1,interceptors[i].qty do
		x = ScenEdit_GetUnit({side='Cuba',name=interceptors[i].name..' #'..ii})
			if x ~= nil then
			sqn_strength = sqn_strength + 1
			end
		end
		cap_strength = sqn_strength / 2
		counter = 1
		for ii = 1,interceptors[i].qty do
		x = ScenEdit_GetUnit({side='Cuba',name=interceptors[i].name..' #'..ii})
			if x ~= nil and counter <= cap_strength then
			ScenEdit_AssignUnitToMission(x.guid,'CAP '..interceptors[i].base)
			counter = counter + 1
			end
		end
	end
end
end

strikers = {
{name='13th Esc. de Caza', qty=2, base='Santiago de Cuba AB',dbid=2076,loadout=144}, --2 x F-51 Mustang @ Santiago de Cuba, will harass GTMO evac convoy, loadout 1000lb GPB & 70mm rockets
{name='141st Esc. de Caza', qty=6, base='Santiago de Cuba AB',dbid=2078,loadout=679}, --6 x P-47 Thunderbolt @ Santiago de Cuba, will conduct mock attacks on GTMO evac convoy, loadout 2 x 1000lb GPB
{name='33rd Esc. de Bombardeo', qty=15, base='San Antonio AB',dbid=2056,loadout=147}, --15 x B-26 @ San Antonio, loadout 2000lb GPB ATTACK
{name='29th Esc. de Caza', qty=12, base='San Julian AB',dbid=2062,loadout=794}, -- 12 x Sea Fury @ San Julian, loadout 1000lb GPB ATTACK
{name='41st Esc. de Caza', qty=12, base='Santa Maria AB',dbid=1699,loadout=1144}, --12 MiG-15 @ Santa Maria, loadout guns only ATTACK
}

strike_missions = {
"Land Strike",
"ASuW Strike"
}

--set random amount to maintenance
maintenance_perc = math.random(10,30)
for i = 1,#strikers do 
	for ii = 1,strikers[i].qty do
	x = ScenEdit_GetUnit({side='Cuba',name=strikers[i].name..' #'..ii})
		if x ~= nil then
		chance = math.random(1,100)
			if chance <= maintenance_perc then
			loadout = 4
			else
			loadout = strikers[i].loadout
			end
		ScenEdit_SetLoadout({UnitName=x.guid,LoadoutID=loadout,TimeToReady_Minutes=math.random(0,180),IgnoreMagazines=true,ExcludeOptionalWeapons=false})
		end
	end
end

if tension <= 50 and cuba == 'false' then 
for i = 1,#strikers do 
	for ii = 1,strikers[i].qty do
	x = ScenEdit_GetUnit({side='Cuba',name=strikers[i].name..' #'..ii})
		if x ~= nil then
		ScenEdit_AssignUnitToMission(x.guid,'Stand Down')
		end
	end
end
end

if tension > 50 or cuba == 'true' then
for i = 1,#strikers do 
	chance = math.random(1,100)
	if chance <= tension then 
	for ii = 1,strikers[i].qty do
	x = ScenEdit_GetUnit({side='Cuba',name=strikers[i].name..' #'..ii})
		if x ~= nil then
		ScenEdit_AssignUnitToMission(x.guid,strike_missions[math.random(1,#strike_missions)])
		end
	end
	end
end
end
*********************************NATURE N.SHIT ADDS WHALES
local Biol_DBIDs = {
220,
220,
92
}

local BiolQty = math.random(8,12)

for i = 1,BiolQty,1 do

::redo_pos::
local lat_var = math.random(1,(10^13)) --random number between 1 and 10^13
local lon_var = math.random(1,(10^13)) --random number between 1 and 10^13

local pos_lat = math.random(15,30) + (lat_var/(10^13)) --latitude; 
local pos_lon = math.random(-90,-60) + (lon_var/(10^13)) --longitude; 

local pos_elev = World_GetElevation({lat=pos_lat,lon=pos_lon})

if pos_elev > -25 then goto redo_pos end

local x = math.random(1,3)
local a = ScenEdit_AddUnit({side='Nature',type='Submarine',dbid=Biol_DBIDs[x],name='Biol Contact '..i,lat=pos_lat,lon=pos_lon})

ScenEdit_AssignUnitToMission(a.name, 'Whale')

end
***********************************USE OF UNIT Y
unit = ScenEdit_UnitY()
unit = unit.unit
elev = World_GetElevation({latitude=unit.latitude,longitude=unit.longitude})
alt_agl = unit.altitude - elev
if alt_agl <= 610 and (unit.dbid == 3422 or unit.dbid == 1630) then --Aircraft is an RF-8 below 2kft
	ChangeScore('United States',30,'Successful Blue Moon overflight')
	BlueMoon = tonumber(ScenEdit_GetKeyValue('BlueMoon'))
	BlueMoon = BlueMoon + 1
	ScenEdit_SetKeyValue('BlueMoon',tostring(BlueMoon))
		if BlueMoon == 6 then
			ScenEdit_SetEvent('US_BlueMoon_Event',{isactive=false})
				if defcon > 1 and USSR ~= 'H' then
					msgtime = DTG()
					ScenEdit_SpecialMessage('United States',
					'<P><FONT face=Consolas>' .. '\\'..'\\'..'PRIORITY <BR>' .. 
					'FROM: CNO <BR>' .. 
					'TO: COMSOLANT<BR>' ..  
					'RE: OPERATION BLUE MOON<BR>' .. 
					msgtime .. 
					'<P><FONT face=Consolas>ACKNOWLEDGE REPORTS OF SUCCESSFUL OVERFLIGHT OF MRBM SITES AS ORDERED. PHOTINT COLLECTED BY YOUR FORCES WILL BE OF UTMOST VALUE IN BRINGING AN END TO THIS THREAT.<BR>'.. 
					'<BR>'..
					'BRAVO ZULU, POTUS SENDS.<BR>'..
					'</P>'..
					'<P><FONT face=Consolas>TOP SECRET'..'\\'..'\\'..'EYES ONLY'..'\\'..'\\'..'NOFORN</FONT></P>')
					ChangeScore('United States',260,'Operation Blue Moon complete')
				end
		end
end
*********************************EXAMPLE OF AUTOMATIC REF POINT PLACEMENT
--2100Z report to Moscow

local subguid = {
'94eb1977-7e0a-4310-a0d5-8d6c76c8fa48', --B-4
'f89e783f-443f-40ed-9479-4605c75c0e8c', --B-130
'0d59208d-4933-498f-9bd0-6d3818bdb792', --B-36
'8bc0f5b3-ebb7-4a03-8a4e-ff7b73e935ee' --B-59
} --list of GUIDs for subs

local desig = {
'ALPHA',
'BRAVO',
'CHARLIE',
'DELTA'}

for i=1,4 do
local sub = ScenEdit_GetUnit({guid=subguid[i]})

if sub ~= nil then

chance = math.random(1,100)

if chance <= 40 then 
local sublat=sub.latitude
local sublon=sub.longitude

--[[local deviation = 300*(math.random(-15,15))
local deviation = deviation/(10^13)
local rp_lat = sublat + deviation

local deviation = 300*(math.random(-15,15))
local deviation = deviation/(10^13)
local rp_lon = sublon + deviation]]

local radius1 = math.random(0,25)
local circle = World_GetCircleFromPoint({latitude=sublat, longitude=sublon,radius=radius1})
local disp_lat = circle[math.random(1,45)].Latitude
local disp_lon = circle[math.random(1,45)].Longitude

local radius2 = math.random(10,40)
local disp_circle = World_GetCircleFromPoint({latitude=disp_lat, longitude=disp_lon,radius=radius2})
local rp1_lat = disp_circle[15].Latitude
local rp1_lon = disp_circle[15].Longitude

local rp2_lat = disp_circle[30].Latitude
local rp2_lon = disp_circle[30].Longitude

local rp3_lat = disp_circle[45].Latitude
local rp3_lon = disp_circle[45].Longitude

msgtime = DTG()

ScenEdit_AddReferencePoint({side="United States", name="PROBSUB " .. desig[i] .. " " .. msgtime .. " A", latitude=rp1_lat, longitude=rp1_lon, highlighted=1})

ScenEdit_AddReferencePoint({side="United States", name="PROBSUB " .. desig[i] .. " " .. msgtime .. " B", latitude=rp2_lat, longitude=rp2_lon, highlighted=1})

ScenEdit_AddReferencePoint({side="United States", name="PROBSUB " .. desig[i] .. " " .. msgtime .. " C", latitude=rp3_lat, longitude=rp3_lon, highlighted=1})

local conflist = {"CONFIDENCE HIGH - INVESTIGATE AND PROSECUTE", "CONFIDENCE MEDIUM - INVESTIGATE", "CONFIDENCE LOW - INFORMATION ONLY"}

local radius_total = radius1 + radius2

if radius_total < 30 then 
	conf = conflist[1]
elseif radius_total <= 55 then 
	conf = conflist[2]
elseif radius_total > 55 then 
	conf = conflist[3] 
end

print (radius_total .. desig[i])
print (conf)

ScenEdit_SpecialMessage
('United States',
'<P><FONT face=Consolas>' .. '\\'..'\\'..'FLASH'..'\\'..'\\'..'FLASH'..'\\'..'\\'..'FLASH'..'<BR>' .. 
'FROM: NAVAL INTELLIGENCE<BR>' .. 
'TO: COMSOLANT<BR>' .. --could be changed
'RE: PROBSUB DETECTED' .. 
'<BR>'.. msgtime.. '</FONT></P>' ..
'<P><FONT face=Consolas>CLASSIC BULLSEYE INDICATES PROBABLE SOVIET SUBMARINE IVO COORDINATES MARKED PROBSUB ' .. desig[i] .. ' ' .. msgtime .. ' A-C<BR>'..
'<BR>'..
conf .. '<BR>'..
'</P>'..


'<P><FONT face=Consolas>TOP SECRET'..'\\'..'\\'..'</FONT></P>')
end
end
end

*************************** MAKE A REPEATING EVENT INACTIVE


ScenEdit_SetEvent('US_SovNucClassified',{isactive=false}) --make the event inactive
******************************RANDOM EXPLOSIONS AROUND A RADIUS
us_ship = ScenEdit_UnitX()
hostile = ScenEdit_GetKeyValue('USSR_Hostile')
tension = GetTension()

ChangeTension(math.random(2,8))

if hostile == true then
	ship_lat = us_ship.latitude
	ship_lon = us_ship.longitude
	circle = World_GetCircleFromPoint({latitude=ship_lat,longitude=ship_lon,radius=math.random(0,2)})
	exp_pos = circle[math.random(0,45)]
	ScenEdit_AddExplosion({warheadid=50,lat=exp_pos.Latitude,lon=exp_pos.Longitude,altitude=-5,})
	ScenEdit_KillUnit({side='Soviet Union',name='B-130'})
	ScenEdit_SetEvent('USSR_B4_Tension',{isactive=false})
	SetDefcon(1)
elseif tension >50 then
chance=math.random(1,100)
	if chance <= 5 then
	ship_lat = us_ship.latitude
	ship_lon = us_ship.longitude
	circle = World_GetCircleFromPoint({latitude=ship_lat,longitude=ship_lon,radius=math.random(0,2)})
	exp_pos = circle[math.random(0,45)]
	ScenEdit_AddExplosion({warheadid=50,lat=exp_pos.Latitude,lon=exp_pos.Longitude,altitude=-5,})
	ScenEdit_KillUnit({side='Soviet Union',name='B-130'})
	ScenEdit_SetEvent('USSR_B4_Tension',{isactive=false})
	ScenEdit_SetSidePosture('Cuba','United States','H')
	ScenEdit_SetSidePosture('United States','Cuba','H')
	SetDefcon(1)
	end
end
**************************** odd little shuffle table function
local function shuffleTable( t )
    local rand = math.random 
    assert( t, "shuffleTable() expected a table, got nil" )
    local iterations = #t
    local j
    
    for i = iterations, 2, -1 do
        j = rand(i)
        t[i], t[j] = t[j], t[i]
    end
end
***********************************
************* places random boats in ports from a list and checks to see which has been placed already
--US_Ships_Ready

--Newport Naval Base

ctr = tonumber(ScenEdit_GetKeyValue('ship_ctr'))
ctr = ctr + 1
ScenEdit_SetKeyValue('ship_ctr',tostring(ctr))

if ctr >= 5 then
ScenEdit_SetEvent('US_Ships_Ready',{isactive=false})
print ('Event US_Ships_Ready terminated')
end

ships_list={
{name='DD 872 Forrest Royal',dbid='1622',keyval='DD872',base='Newport Naval Base'},
{name='DD 850 Joseph P. Kennedy',dbid='1622',keyval='DD850',base='New York Naval Base'},
{name='AE 17 Great Sitkin',dbid='565',keyval='AE17',base='New York Naval Base'},
{name='EDD 848 Witek',dbid='96',keyval='DD697',base='New York Naval Base'},
{name='DD 701 John W. Weeks',dbid='659',keyval='DD701',base='Norfolk Naval Base'},
{name='DD 704 Borie',dbid='659',keyval='DD704',base='Norfolk Naval Base'},
{name='DD 707 Soley',dbid='659',keyval='DD707',base='Norfolk Naval Base'},
{name='DD 753 John R. Pierce',dbid='659',keyval='DD753',base='Norfolk Naval Base'},
{name='DD 775 Willard Keith',dbid='659',keyval='DD775',base='Norfolk Naval Base'},
{name='DDG 11 Sellers',dbid='1254',keyval='DDG11',base='Norfolk Naval Base'},
{name='DDG 4 Lawrence',dbid='1254',keyval='DDG4',base='Norfolk Naval Base'},
{name='DD 942 Bigelow',dbid='1251',keyval='DD942',base='Norfolk Naval Base'},
{name='AO 55 Elkomin',dbid='667',keyval='AO55',base='Norfolk Naval Base'},
{name='DDR 863 Steinaker',dbid='592',keyval='DDR863',base='Norfolk Naval Base'},
{name='DDR 879 Leary',dbid='592',keyval='DDR879',base='Norfolk Naval Base'},
{name='CA 148 Newport News',dbid='139',keyval='CA148',base='Norfolk Naval Base'},
{name='DLG 14 Dewey',dbid='2070',keyval='DLG14',base='Norfolk Naval Base'},
{name='CAG 2 Canberra',dbid='1226',keyval='CAG2',base='Norfolk Naval Base'},
{name='DD 710 Gearing',dbid='1622',keyval='DD710',base='Norfolk Naval Base'},
{name='DLG 8 MacDonough',dbid='1255',keyval='DLG8',base='Charleston Naval Base'},
{name='DD 878 Vesole',dbid='592',keyval='DD878',base='Norfolk Naval Base'},
{name='DD 763 William C. Lawe',dbid='1622',keyval='DD763',base='Mayport Naval Base'},
{name='AO 27 Kaskaskia',dbid='667',keyval='AO27',base='Mayport Naval Base'},
--{name='DD 692 Allen M Sumner',dbid='XXX',keyval='XXX',base='Mayport Naval Base'}, --needs DBID & KeyValue
}

for i = 1,#ships_list do 

print ('Checking '..ships_list[i].name)
key = ScenEdit_GetKeyValue(ships_list[i].keyval)

	if key == 'false' then --check if already spawned
	print ('Not yet spawned, checking probability...')
		roll = math.random(1,5)
		if roll <= ctr then --check probability
		print('Probability check made')
		local x = ScenEdit_AddUnit({side='United States',type='ship',name=ships_list[i].name,dbid=ships_list[i].dbid,latitude='0', longitude='0'})
		ScenEdit_HostUnitToParent({HostedUnitNameOrID=x.guid,SelectedHostNameOrID=ships_list[i].base})

		ScenEdit_SetKeyValue(ships_list[i].keyval,'msg')
		end
	end
end

msgtime = DTG()

ships_ready={}
ships_ready_base={}
counter = 0
for i=1,#ships_list do
key = ScenEdit_GetKeyValue(ships_list[i].keyval)
if key == 'msg' then
counter = counter+1
ships_ready[counter]=ships_list[i].name
ships_ready_base[counter]=ships_list[i].base
key = ScenEdit_SetKeyValue(ships_list[i].keyval,'true')
end
end

ships_list = ""
for i = 1,#ships_ready do
ships_list = string.upper(ships_list..ships_ready[i].. " - " .. ships_ready_base[i] .. " <BR>")
end
print (ships_list)

if ships_list ~= "" then
ScenEdit_SpecialMessage
('United States',
'<P><FONT face=Consolas>' .. '\\'..'\\'..'ROUTINE <BR>' .. 
'FROM: CNO<BR>' .. 
'TO: COMSOLANT<BR>' .. 
'RE: SHIPS READY FOR DEPLOYMENT <BR>'.. 
msgtime ..
'<P><FONT face=Consolas>THE FOLLOWING SURFACE UNITS ARE REPORTING READY TO GET UNDERWAY: <BR>'.. 
'<BR>'..
ships_list ..
'<BR>'..
'</P>'..
'<P><FONT face=Consolas>CONFIDENTIAL'..'\\'..'\\'..'</FONT></P>')
end
************************************RANDOM WEATHER     DEPRECATED
local valz = tonumber(ScenEdit_GetKeyValue('weath'))

***********************************************************************************************************************************DYNAMIC WEATHER GENERATOR fortyporkpies original code, work in progress, use it and abuse it
--Sorta Dynamic Weather 
--SDW Mk2 mod 1 Console or Repeatedly Fired Event Version
--Lua in Notepad++  date090317 Weighted Weather Simulator created by Nick G aka fortyporkpies
--weighted more towards clear weather 
--change if then statements to alter weighting for now


--todo
--make a master weight keyvar
--clean up diagnostic layout but not maj priority
--adjust wx deltas proportionally to the interval at which this event is being fired important
--make functions for improved efficiency and make sure they init every startup

--these set parameters of entire script
specmsg = false --set to true to enable text boxes every time there is a weather change


wxhistoryt = ScenEdit_GetKeyValue('wxht')--this is all diagnostic
if wxhistoryt == nil then 
	wxhistoryt = {}
	wxhistoryr = {}
	wxhistoryc = {}
	wxhistorys = {}
	wxctr = 0
	ScenEdit_SetKeyValue('wxht',wxhistoryt)
	ScenEdit_SetKeyValue('wxhr',wxhistoryr)
	ScenEdit_SetKeyValue('wxhc',wxhistoryc)
	ScenEdit_SetKeyValue('wxhs',wxhistorys)
	ScenEdit_SetKeyValue('wxcounter','0')
else
	wxhistoryr = ScenEdit_GetKeyValue('wxhr')
	wxhistoryc = ScenEdit_GetKeyValue('wxhc')
	wxhistorys = ScenEdit_GetKeyValue('wxhs')
	wxctr = tonumber(ScenEdit_GetKeyValue('wxcounter'))
end
if wxctr==nil then wxctr=0 end

oldtemp = tonumber(ScenEdit_GetKeyValue('otemp'))
if oldtemp == nil then  --init	
	math.randomseed(os.time())
	print ('INIT THAT SHITE')
	local q=ScenEdit_GetWeather()
	oldtemp = q.temp
	oldrain = q.rainfall 
	oldcloud = q.undercloud
	oldsea = q.seastate
	ScenEdit_SetKeyValue('otemp',tostring(oldtemp))
	ScenEdit_SetKeyValue('orain',tostring(oldrain))
	ScenEdit_SetKeyValue('ocloud',tostring(oldcloud))
	ScenEdit_SetKeyValue('osea',tostring(oldsea))
else
	oldrain = tonumber(ScenEdit_GetKeyValue('orain'))
	oldcloud = tonumber(ScenEdit_GetKeyValue('ocloud'))
	oldsea = tonumber(ScenEdit_GetKeyValue('osea'))
end

valz = tonumber(ScenEdit_GetKeyValue('weath')) --a very key variable bc this tracks both good and bad and boring weather streaks 
if valz == nil then --initialize
	valz = 0
	ScenEdit_SetKeyValue('weath',tostring(valz))
end

stag = tonumber(ScenEdit_GetKeyValue('stagmod')) --weather stagnation roll modifier
if stag == nil then --initialize
	stag = 0
	ScenEdit_SetKeyValue('stagmod',tostring(stag))
end

local q=ScenEdit_GetWeather()

wxctr = wxctr + 1
ScenEdit_SetKeyValue('wxcounter',tostring(wxctr))


wxhistoryt = wxhistoryt..'{t'..tostring(wxctr)..':'..tostring(oldtemp)..' Val:'..tostring(valz)..' Stg:'..tostring(stag)..'}'
wxhistoryr = wxhistoryr..'{r'..tostring(wxctr)..':'..tostring(oldrain)..'}'
wxhistoryc = wxhistoryc..'{c'..tostring(wxctr)..':'..tostring(oldcloud)..'}'
wxhistorys = wxhistorys..'{s'..tostring(wxctr)..':'..tostring(oldsea)..'}'
ScenEdit_SetKeyValue('wxht',wxhistoryt)
ScenEdit_SetKeyValue('wxhr',wxhistoryr)
ScenEdit_SetKeyValue('wxhc',wxhistoryc)
ScenEdit_SetKeyValue('wxhs',wxhistorys)



print (' ') 
print ('XXXXXXX DIAGNOSTIC START XXXXXX') 
print (wxhistoryt)
print (wxhistoryr)
print (wxhistoryc)
print (wxhistorys)


print ('old weather keyvalues are oldtemp  '..oldtemp..' oldrain '..oldrain..' oldcloud '..oldcloud..' oldsea '..oldsea)
print ('And the current weather should match')
print (q)

rando=(math.random(1,100)) --percent roll
print ('initial roll:'..rando)

if ((stag > 1) and (stag < 7)) then --stagnant weather modifiers 
	print ('minus this value '..stag*stag) --so either subtract 4, 9, 16, 25, 36 off of initial roll
	rando=rando - (stag*stag)
	print ('Roll modified because stag is >1 and <7 this is stag:'..stag..' and the roll is now '..rando)
elseif stag >= 7 then
	stag = 0
	ScenEdit_SetKeyValue('stagmod',tostring(stag))
	print ('Stagnant key is Reset because it was 7 or greater')
end

print (' ')
print ('valz the counter is '..valz..' and the stagnation counter is '..stag..' and the final roll is '..rando)
print (' ')

if ((valz <= 12) and (rando < 20)) then --change for weighting this is the wx deteriorate block
	print ('Worsening because valz is 12 or less and percent roll is less than 20  ADD ONE TO VALZ')
	valz = valz + 1 --increase weather counter by one
	ScenEdit_SetKeyValue('weath',tostring(valz))
	local temp=oldtemp - (math.random(1,3)) --the following four are the wx deltas
	local rain=oldrain + (math.random(1,8))
	local cloud=oldcloud + ((math.random(1,2))/10.0)
	local sea=oldsea + (math.random(1,2))
	print ('worsening initial calc temp rain cloud sea  '..temp..' '..rain..' '..cloud..' '..sea)
	if ((temp < -2) or (temp > 20)) then temp = oldtemp end --adjust for out of range values but those need to be verified and changed
	if rain > 35 then rain = 35 end
	if cloud > 1 then cloud = 1 end
	if sea > 6 then --above sea state six is bad news lets increase that weather counter again 
		valz = valz + 1
		ScenEdit_SetKeyValue('weath',tostring(valz))
		sea = 6 --and go no higher than sea state six because we are not going to battle in a moderate gale or worse
	end
	ScenEdit_SetWeather(temp,rain,cloud,sea) 
	print ('worsening adjusted set temp rain cloud sea  '..temp..' '..rain..' '..cloud..' '..sea) 

	if ((rain ~= oldrain) or (cloud ~= oldcloud) or (sea ~= oldsea)) then 
		print ('WORSENING WEATHER MESSAGE PRINTED BC OF DELTA') 
		if specmsg == true then
			--ScenEdit_MsgBox('Rain is currently '..oldrain, 1)
			--ScenEdit_SpecialMessage('USSTRATCOM', '<P><FONT size=2 face="Courier New">SIR,</P><P>WX REPORT WORSENING,</P> TEMPERATURE: ' .. temp .. ' DEGREES CELSIUS, RAIN STATE: ' .. rain .. ' CLOUD LEVEL: ' .. cloud .. ' AND SEA STATE: ' .. sea)
		end
		
	end

	ScenEdit_SetKeyValue('otemp',tostring(temp))
	ScenEdit_SetKeyValue('orain',tostring(rain))
	ScenEdit_SetKeyValue('ocloud',tostring(cloud))
	ScenEdit_SetKeyValue('osea',tostring(sea))
	

	elseif rando < 51 then -- change for weighting this is the wx improve block
	print ('improving because percentile roll is less than 51 and possibly also because valz is greater than 12')
	local temp=oldtemp + (math.random(1,2)) --the following four are the wx deltas
	local rain=oldrain - (math.random(1,8))
	local cloud=oldcloud - ((math.random(1,2))/10.0)
	local sea=oldsea - (math.random(1,2))
	print ('improving initial calc temp rain cloud sea  '..temp..' '..rain..' '..cloud..' '..sea)
	if ((temp < -2) or (temp > 20)) then temp = oldtemp end --adjust for out of range values but those need to be verified 
	if cloud < 0 then cloud = 0 end
	if ((rain < 0) or (cloud < 0.21)) then rain = 0 end
	if sea < 0 then sea = 0 end
	ScenEdit_SetWeather(temp,rain,cloud,sea)
	print ('improving ajusted set temp rain cloud sea  '..temp..' '..rain..' '..cloud..' '..sea)
	if ((rain ~= oldrain) or (cloud ~= oldcloud) or (sea ~= oldsea)) then --if this DOES NOT get fired enough throw bad weather in there peut etre je crois
		print ('IMPROVING WEATHER MESSAGE PRINTED BC OF DELTA') --can be replaced with special msg 
		if specmsg == true then
			--ScenEdit_SpecialMessage('USSTRATCOM', '<P><FONT size=2 face="Courier New">COMMANDER,</P><P>WX REPORT IMPROVING,</P> TEMPERATURE: ' .. temp .. ' DEGREES CELSIUS, RAIN STATE: ' .. rain .. ' CLOUD LEVEL: ' .. cloud .. ' AND SEA STATE: ' .. sea)
		end
	else
		stag = stag + 1
		print ('stagnant weather counter fired1 stag counter is '..stag)
		ScenEdit_SetKeyValue('stagmod',tostring(stag))
	end
	
	if valz >= 13 then -- we start counting back towards reset
		local woot=(math.random(1,100))
		print ('SPECIAL     Valz is between 13 and 21 and the percent roll is '..woot) 
		if woot < 79 then -- decent chance weather counter will increment   
			valz = valz + 1
			print ('SPECIAL     AND since the roll was less than 79 we increase valz which is now '..valz) 
			ScenEdit_SetKeyValue('weath',tostring(valz))
		end
	end

	ScenEdit_SetKeyValue('otemp',tostring(temp))
	ScenEdit_SetKeyValue('orain',tostring(rain))
	ScenEdit_SetKeyValue('ocloud',tostring(cloud))
	ScenEdit_SetKeyValue('osea',tostring(sea))

	elseif rando > 91 then 
		valz = valz + 1
		ScenEdit_SetKeyValue('weath',tostring(valz))
		print ('SPECIAL     because stagnation is boring AND since the roll was greater than 91 we increase valz which is now '..valz) 
	
	elseif ((math.random(1,100)) < 31) then
		stag = stag + 1
		print ('stagnant weather counter fired2 30 percent chance RANDOMMMM stag counter is '..stag) --this should rarely increment the stagnation counter
		ScenEdit_SetKeyValue('stagmod',tostring(stag))
	
	else --therefore rando landed btwn 51 and 91 and 70 percent chance of nothing happening 20sometin percent chance of this event i think
		print ('Nothing Happened because roll landed btwn 51 and 91 and 70 percent chance ')
end

--change perhaps
local ti=ScenEdit_GetWeather()
if ((ti.seastate >= 6) or (ti.rainfall >= 30) or (ti.undercloud >= 0.8)) then --bad conditions so increase that counter
	valz = tonumber(ScenEdit_GetKeyValue('weath'))
	valz = valz + 1 
	print ('SPECIAL     Since either seastate is >=6 or rain is >=30 or clouds are >=0.9 then valz goes up by one:'..valz) 
	ScenEdit_SetKeyValue('weath',tostring(valz))
end


print (' ')
print ('new current weather is')
print (ti)
valz = tonumber(ScenEdit_GetKeyValue('weath'))
if valz > 21 then --reset weather counter and allow deteriorating conditions again
	print ('SPECIAL SPECIAL   valz is greater than 21 so valz is being reset to 0')
	valz = 0
	ScenEdit_SetKeyValue('weath',tostring(valz))
end
print ('XXXXXXX DIAGNOSTIC ENDED XXXXXX')