-- FIRE SPREAD MODELS
-- (C) 2010 INPE AND UFOP

-- automaton states
NO_DATA     = 0
INACTIVE1	= 1
INACTIVE2	= 2
INACTIVE3	= 3
INACTIVE4	= 4
INACTIVE5	= 5
RIVER       = 6
ACEIRO    	= 7
BURNING 	= 8
BURNED  	= 9


-- global variables
STEPS 	  		= 20      -- numero de iteracoes do modelo
burned_total 	= 0   -- estatística
OUTPUT_PATH 	= "c:\\TerraME\\Results\\Emas\\"


-- matriz de probabilidades
I = {{0.100, 0.250, 0.261, 0.273, 0.285}, 
     {0.113, 0.253, 0.264, 0.276, 0.288},
     {0.116, 0.256, 0.267, 0.279, 0.291},
     {0.119, 0.259, 0.270, 0.282, 0.294},
     {0.122, 0.262, 0.273, 0.285, 0.297}}
     
-- define e carrega o espaco celular
cs = CellularSpace{
	dbType = "ADO",
	database = "c:\\TerraME\\Database\\db_emas.mdb", 
	theme = "cells1000x1000", 
	select = {"aceiro","river","accumulation","fire", "state"}
}
cs:load();

-- Create a Moore Neighborhood
createMooreNeighborhood(cs)

-- create and calculate the "state" cell's attribute 
--for i, cell in pairs(cs.cells) do
forEachCell( cs, 
	function(cell)
		if 	cell.aceiro == 1 then
			cell.state = ACEIRO
		elseif cell.river == 1 then
			cell.state = RIVER
		elseif cell.fire == 1 then
			cell.state = BURNING
		else
			cell.state = cell.accumulation
		end
	end
)	

-- save initial state
--cs:save(0,"state",{"state"})

-- model execution
for t = 1, STEPS do

	itF = Trajectory{cs, function(cell) return cell.state == BURNING end}
	forEachCell(itF, function(cell)
		forEachNeighbor(cell, function(cell,neigh)
			if (neigh ~= cell and neigh.state < INACTIVE5) then
				p = math.random()
				if p < I[cell.accumulation][neigh.accumulation] then
					neigh.state = BURNING
				end
			end
		end)
		cell.state = BURNED
		burned_total = burned_total + 1
	end)

	--cs:save(t,"state",{"state"})	
	save2PNGd(	cs, t, OUTPUT_PATH, "state", 
				{NO_DATA, 	INACTIVE1, 		INACTIVE2, 		INACTIVE3, 		INACTIVE4, 		INACTIVE5, 	RIVER, 	ACEIRO, BURNING, 	BURNED }, 
				{WHITE,		{192,255,192},	{128,255,128},	{64,255,64},	{32,255,32},	GREEN, 		BLUE,	BROWN, 	RED, 		BLACK}
	)
	
end

print("<> The end - burned cells:",burned_total," <>")


print("Please, press <ENTER> to quit.")
io.read()