// this script was compiled with wurst 1.8.1.0-jenkins-Wurst-1367
globals
integer array test_cs
integer test_count=0
integer array C_nextFree
integer C_firstFree=0
integer C_maxIndex=0
integer array C_typeId
integer array C_alive
endglobals
native testFail takes string msg returns nothing
native testSuccess takes nothing returns nothing
function initGlobals takes nothing returns nothing
endfunction

function error takes string msg returns nothing
	call BJDebugMsg(msg + "\n" + "")
endfunction

function dispatch_C_destroyC takes integer this returns nothing
	if C_typeId[this] == 0 then
		if this == 0 then
			call error("Nullpointer exception when calling C.C")
		else
			call error("Called C.C on invalid object.")
		endif
	endif
	set C_alive[this] = 2
	if C_typeId[this] == 0 then
		call error("Double free: object of type C")
	else
		set C_nextFree[C_firstFree] = this
		set C_firstFree = C_firstFree + 1
		set C_typeId[this] = 0
	endif
endfunction

function new_C takes nothing returns integer
	local integer this
	if C_firstFree == 0 then
		if C_maxIndex < 32768 then
			set C_maxIndex = C_maxIndex + 1
			set this = C_maxIndex
			set C_typeId[this] = 1
		else
			call error("Out of memory: Could not create C.")
			set this = 0
		endif
	else
		set C_firstFree = C_firstFree - 1
		set this = C_nextFree[C_firstFree]
		set C_typeId[this] = 1
	endif
	if C_alive[this] == 1 then
		call testFail("already alive")
	endif
	set C_alive[this] = 1
	return this
endfunction

function init_test takes nothing returns nothing
	local integer i
	local integer j
	set test_count = 0
	set i = 0
	loop
		exitwhen i > 1000
		if test_count < 100 and GetRandomReal(0., 1.) <= 0.5 then
			set test_cs[test_count] = new_C()
			set test_count = test_count + 1
		endif
		if test_count > 0 and GetRandomReal(0., 1.) <= 0.1 then
			set j = GetRandomInt(0, test_count - 1)
			call dispatch_C_destroyC(test_cs[j])
			set test_count = test_count - 1
			set test_cs[j] = test_cs[test_count]
		endif
		set i = i + 1
	endloop
	call testSuccess()
endfunction

function main takes nothing returns nothing
	call initGlobals()
	call init_test()
endfunction

function config takes nothing returns nothing
endfunction