loadBales = {}

local modDirectory = g_currentModDirectory

function loadBales.loadMapData(self, superFunc, val1, val2, val3)

    local returnValue = superFunc(self, val1, val2, val3)

    if fileExists(modDirectory.."bales/bales.xml") then
        local xml = loadXMLFile("bales", modDirectory.."bales/bales.xml")

		-- add bales
        local i = 0
        while true do
            local bale = getXMLString(xml, "bales.bale("..i..")#filename")
            if bale ~= nil and bale ~= "" then
                g_baleManager:loadBaleFromXML(xml, "bales.bale("..i..")", modDirectory)
            else
                break
            end
            i = i + 1
        end
		
	    delete(xml)
    else
        print("Warning: Can't load '"..tostring(modDirectory.."bales/bales.xml").."' no custom Bales will be loaded!")
    end
	
    return returnValue 
end
BaleManager.loadMapData = Utils.overwrittenFunction(BaleManager.loadMapData, loadBales.loadMapData)

function loadBales.getBaleIndex(self, superFunc, fillTypeIndex, isRoundbale, width, height, length, diameter, customEnvironment)
	if customEnvironment ~= nil then
	
		local baleIndex = #self.bales
		while true do
			local bale = self.bales[baleIndex]

			if bale.isAvailable and customEnvironment == bale.customEnvironment and self:getIsBaleMatching(bale, fillTypeIndex, isRoundbale, width, height, length, diameter) then
				return baleIndex
			end		
			
			baleIndex = baleIndex - 1
			if baleIndex == 0 then
				break
			end
		end
	end
	
	local baleIndex = #self.bales
	while true do	
		local bale = self.bales[baleIndex]

		if bale.isAvailable and bale.customEnvironment == nil and self:getIsBaleMatching(bale, fillTypeIndex, isRoundbale, width, height, length, diameter) then
			return baleIndex
		end
		
		baleIndex = baleIndex - 1
		if baleIndex == 0 then
			break
		end		
	end

	return nil
end
BaleManager.getBaleIndex = Utils.overwrittenFunction(BaleManager.getBaleIndex, loadBales.getBaleIndex)