print();

BeetHarvestAddon = Mod:init()

-- BeetHarvestAddon:enableDebugMode()

function BeetHarvestAddon:initMission()
    if g_storeManager ~= nil then
        local success = g_storeManager:addCategory("SELLSTATIONS", g_i18n:getText("store_category_sellPoints"), "store_category_sellpoints.dds", "PLACEABLE", self.dir);
    end
end

function BeetHarvestAddon:loadMap()
    -- self:registerFillTypes()
    self:registerMaterials()
end

function BeetHarvestAddon:initSettings()
    local settings = self.settings:init("beetHarvestAddon", "defaultSettings.xml", "beetHarvestAddon.xml");

    -- Set initial/fallback values for settings
    settings.useMonochromeIcons = true
    settings.unclampPrices = false
    settings.autoAddToSellpoints = true
    -- settings.enableDumpToGround = true --TODO: default should be false

    -- Load actual settings from both the default settings file from the mod and user settings from the modsSettings-folder
    settings:load(function(xmlReader)
        settings.useMonochromeIcons = xmlReader:readBool(nil, "useMonochromeIcons", settings.useMonochromeIcons)
        settings.unclampPrices = xmlReader:readBool(nil, "unclampPrices", settings.unclampPrices)
        settings.autoAddToSellpoints = xmlReader:readBool(nil, "autoAddToSellpoints", settings.autoAddToSellpoints)
        settings.excludePulpFromBGA = xmlReader:readBool(nil, "excludePulpFromBGA", settings.excludePulpFromBGA)
        -- settings.enableDumpToGround = xmlReader:readBool(nil, "enableDumpToGround", settings.enableDumpToGround)
    end)

    -- This will auto-save all default settings to the user settings file (in modsSettings-folder) on the first run
    self.settings:save(function(xmlWriter)
        xmlWriter:saveBool(nil, "useMonochromeIcons", settings.useMonochromeIcons)
        -- xmlWriter:saveBool(nil, "unclampPrices", settings.unclampPrices)
        xmlWriter:saveBool(nil, "autoAddToSellpoints", settings.autoAddToSellpoints)
        xmlWriter:saveBool(nil, "excludePulpFromBGA", settings.excludePulpFromBGA)
        -- xmlWriter:saveBool(nil, "enableDumpToGround", settings.enableDumpToGround)
    end);

end

function BeetHarvestAddon:missionLoaded()
    BeetHarvestAddon:printDebug("Mission loaded")
end

function BeetHarvestAddon:beforeLoadMap()
    BeetHarvestAddon:printDebug("Before Load Map")  
end

function BeetHarvestAddon:startMission()
    BeetHarvestAddon:printDebug("Start mission")

--    BeetHarvestAddon:prepareFoodMixtures()
--     BeetHarvestAddon:appendFoodGroups()

end

function BeetHarvestAddon:afterLoadMap()
    -- Only append food groups if MaizePlus FE/AFA is inactive, otherwise we cause issues
    -- if not BeetHarvestAddon:getIsMaizePlusAnimalFoodAdditionsActive() and not BeetHarvestAddon:getIsMaizePlusForageActive() then
    if not BeetHarvestAddon:getIsMaizePlusForageActive() then
        BeetHarvestAddon:appendFoodGroups()
    else
        BeetHarvestAddon:printInfo("Disabled the food group additions due to MaizePlus Forage Extension/Animal Food Additions being active")
    end

    -- BeetHarvestAddon:printDebugVar("getIsMaizePlusActive", BeetHarvestAddon:getIsMaizePlusActive())
    -- BeetHarvestAddon:printDebugVar("getIsMaizePlusForageActive", BeetHarvestAddon:getIsMaizePlusForageActive())
    -- BeetHarvestAddon:printDebugVar("getIsMaizePlusAnimalFoodAdditionsActive", BeetHarvestAddon:getIsMaizePlusAnimalFoodAdditionsActive())
    
end


function BeetHarvestAddon:beforeStartMission()
    BeetHarvestAddon:printDebug("Before Start mission")

    --TODO: Moved here as a quick fix for M+ FE
    -- BeetHarvestAddon:appendFoodGroups()
    -- -- BeetHarvestAddon:prepareFoodMixtures()


    
end

-- function BeetHarvestAddon:loadMapFinished()
--     BeetHarvestAddon:printDebug("Map finish")
-- end

--- Do some late fixes, especially to align mod with StrawHarvest Addon
function BeetHarvestAddon:afterLoadMapFinished()
    
    local molassesFillType = g_fillTypeManager:getFillTypeByName("MOLASSES")

    if molassesFillType ~= nil then

        if self:getIsStrawHarvestActive() then -- Re-align prices with the buyable molasses from StrawHarvest and with production from SugarBeetHarvest
            BeetHarvestAddon:printInfo("StrawHarvest Addon is active, adjusting pricing to align mods")
        end
    
        molassesFillType.showOnPriceTable = true -- Make sure molasses is visible even with straw harvest addon

        -- self:printDebugVar("molassesFillType.pricePerLiter:before", molassesFillType.pricePerLiter)

        if molassesFillType.pricePerLiter ~= self.priceLevels.molasses then
            molassesFillType.pricePerLiter = self.priceLevels.molasses
            -- startPricePerLiter
        end

        -- Special fix to replace the default straw harvest icon with our colorful option when colorful icons is enabled
        if not self.settings.useMonochromeIcons and self:getIsStrawHarvestActive() then
            local hudFilename, hudFilenameSmall = self:getHudFileNames("molasses")
            molassesFillType.hudOverlayFilename = Utils.getFilename(hudFilename, self:getFullHudDir())
            molassesFillType.hudOverlayFilenameSmall = Utils.getFilename(hudFilenameSmall, self:getFullHudDir())
        end
        -- self:printDebugVar("molassesFillType.pricePerLiter:after", molassesFillType.pricePerLiter)
    end    
end

-- function BeetHarvestAddon:prepareGlobalCompanyIcons()

-- end

FillTypeManager.loadMapData = Utils.appendedFunction(FillTypeManager.loadMapData, function()
    BeetHarvestAddon:initSettings()
    BeetHarvestAddon:registerFillTypes()
end)

function BeetHarvestAddon:prepareFoodMixtures(foodManager)
    -- Special case to handle MaizePlus 1.5+, from now on M+ will always add feedPellets, beetPulp etc regrdless of map (M+ enabled or not) so no need to mess with the feed mixtures
    -- if BeetHarvestAddon:getIsMaizePlusAnimalFoodAdditionsActive() or BeetHarvestAddon:getIsMaizePlusForageActive() then
    if BeetHarvestAddon:getIsMaizePlusForageActive() then
        BeetHarvestAddon:printError("This should never happen, we should not mess with the feed mixes when MaizePlus FE is active!")
        return -- No need to do anything, we rely on M+ to handle things... exiting
    end

    foodManager = foodManager or g_animalFoodManager

    if foodManager.foodMixtures[FillType.SUPAFEEDPELLETS] == nil then

        local function getFeedPelletMixtureIngredients()

            return {
                { weight = 0.8, fillTypes = { FillType.SUPAFEEDPELLETS } },
                { weight = 0.2, fillTypes = { FillType.BEETPULP } },
            }

            -- if not BeetHarvestAddon:getIsMaizePlusForageActive() then
            --     return {
            --         { weight = 0.8, fillTypes = { FillType.FEEDPELLETS } },
            --         { weight = 0.2, fillTypes = { FillType.BEETPULP } },
            --     }
            -- else  -- Special case only for Maize+ with Forage extension
            --     return {
            --         { weight = 0.4, fillTypes = { FillType.FEEDPELLETS } },
            --         { weight = 0.4, fillTypes = { FillType.BEETPULP } },
            --         { weight = 0.2, fillTypes = { FillType.MOLASSES } },
            --     }
            -- end
        end

        foodManager.foodMixtures = foodManager.foodMixtures or {}

        foodManager.foodMixtures[FillType.SUPAFEEDPELLETS] = {
            ingredients = getFeedPelletMixtureIngredients()
        }
    end

    local function addFoodMixtureToAnimal(animalType, feedMixtureFilltype)
        local foodMix = foodManager.animalFoodMixtures[animalType] or {}
        table.insert( foodMix, feedMixtureFilltype )
        foodManager.animalFoodMixtures[animalType] = foodMix
    end

    addFoodMixtureToAnimal("COW", FillType.SUPAFEEDPELLETS)
    addFoodMixtureToAnimal("PIG", FillType.SUPAFEEDPELLETS)
end

function BeetHarvestAddon:registerMaterials()
    local function loadMaterialHolder(fillTypeName)
        fillTypeName = tostring(fillTypeName)
        local filename = Utils.getFilename(string.format( "fillTypes/%s_materialHolder.i3d", fillTypeName ), self.dir)
        return loadI3DFile(filename, false, true, false)
    end

    local function addHeightTypeToMission(fillTypeName, heapAngle, allowSmoothing, soundFillTypeName, fillToGroundScale, collisionScale, baseOffset, minOffset, maxOffset)
        local fillTypeIndex = g_fillTypeManager:getFillTypeIndexByName(fillTypeName)
    
        g_fillTypeManager.fillTypeToSample[fillTypeIndex] = g_fillTypeManager.fillTypeToSample[g_fillTypeManager:getFillTypeIndexByName(soundFillTypeName)]

        local function textureFilename(fillTypeName, typeName)
            fillTypeName = tostring(fillTypeName)
            return Utils.getFilename(string.format( "fillTypes/%s_%s.dds", fillTypeName:lower(), typeName ), self.dir)
        end
    
        local diffuseTextureFilename = Utils.getFilename("fillTypes/" .. fillTypeName .. "_diffuse.dds", self.dir)
        local normalTextureFilename = Utils.getFilename("fillTypes/" .. fillTypeName .. "_normal.dds", self.dir)
        local specularTextureFilename = Utils.getFilename("fillTypes/" .. fillTypeName .. "_specular.dds", self.dir)
        local distanceTextureFilename = Utils.getFilename("fillTypes/" .. fillTypeName .. "_distance_diffuse.dds", self.dir)

        -- Defaults
        fillToGroundScale = fillToGroundScale or 1.0 -- 1.0
        collisionScale = collisionScale or 0.8 --0.8 -- 1.0
        baseOffset = baseOffset or 0.1 -- 0.1
        minOffset = minOffset or 0.1 -- 0.1
        maxOffset = maxOffset or 1.2 -- 1.2 
        soundFillTypeName = soundFillTypeName or fillTypeName
    
        local heightType = g_densityMapHeightManager:addDensityMapHeightType(fillTypeName, math.rad(heapAngle), collisionScale, baseOffset, minOffset, maxOffset, fillToGroundScale, allowSmoothing, diffuseTextureFilename, normalTextureFilename, distanceTextureFilename, false)

        if heightType == nil then
            self:printWarning("HeightType '" .. tostring(fillTypeName).."' could not be added to the current mission")
        end
    end


    -- Check if it is possible to add our three new heightTypes
    local tooManyHeightTypes = (g_densityMapHeightManager.numHeightTypes + 2 > (2 ^ g_currentMission.terrainDetailHeightTypeNumChannels) - 1)

    if not tooManyHeightTypes then
        self:printDebug("Adding new height types - dump to ground will be enabled for sugar, beetPulp and feedPellets")

        addHeightTypeToMission("sugar", 35, false, "LIME", 1.0, 1.0 )
        addHeightTypeToMission("beetPulp", 45, true, "CHAFF", 1.0, 0.8 )
        addHeightTypeToMission("supaFeedPellets", 38, false, "WOODCHIPS", 1.0, 0.9 )

        -- g_currentMission.hud.fillLevelsDisplay:refreshFillTypes(g_fillTypeManager)

    else
        self:printWarning("Too many height types - dump to ground is disabled for sugar, beetPulp and feedPellets")
    end

    self.materialSugar = loadMaterialHolder("sugar")
    self.materialBeetPulp = loadMaterialHolder("beetPulp")
    -- self.materialFeedPellets = loadMaterialHolder("feedPellets")
    self.materialSupaFeedPellets = loadMaterialHolder("supaFeedPellets")

    
end


function BeetHarvestAddon:getHudFileNames(fillTypeName)
    local normalHudFile = string.format( "hud_fill_%s.dds", fillTypeName )
    local smallHudFile = string.format( "hud_fill_%s_sml.dds", fillTypeName )
    return normalHudFile, smallHudFile
end

function BeetHarvestAddon:getHudDir()
    local hudDirExtra = (self.settings.useMonochromeIcons == true and "monochrome/") or ""
    return "hud/" .. hudDirExtra
end

function BeetHarvestAddon:getFullHudDir()
    return Utils.getFilename(self:getHudDir(), self.dir)
end

function BeetHarvestAddon:registerFillTypes()

    ---@param fillTypeName string
    ---@param price float Price (€/$/£) per liter
    ---@param mass float Mass (kg) per liter
    ---@param heapAngle float Maximum heap angle (degrees)
    local function addFillTypeToCurrentMission(fillTypeName, price, mass, heapAngle)
            if fillTypeName == nil or type(fillTypeName) ~= "string" then
                return
            end

            local normalHudFile, smallHudFile = self:getHudFileNames(fillTypeName)
            local fillPlaneColors = { 1, 1, 1 }
            -- local hudDirExtra = (self.settings.useMonochromeIcons == true and "monochrome/") or ""
            -- local hudDir = "hud/" .. hudDirExtra
            local hudDir = self:getFullHudDir()

            local fillType = g_fillTypeManager:addFillType(fillTypeName:upper(), g_i18n:getText(fillTypeName), true, price, mass, math.rad(heapAngle), normalHudFile, smallHudFile, hudDir, nil, fillPlaneColors, nil, false)

            if fillType == nil then
                self:printWarning("Failed to add filltype '" .. tostring(fillTypeName).."' to current mission")
            end
    end

    local function addFillTypeToCategories(fillTypeName, categoryNames)
		local fillTypeIndex = g_fillTypeManager:getFillTypeIndexByName(fillTypeName)

        if fillTypeIndex == nil then
            self:printWarning("Filltype '" .. tostring(fillTypeName).."' was not found")
            return
        end

        for _, category in pairs(categoryNames) do
			g_fillTypeManager:addFillTypeToCategory(fillTypeIndex, g_fillTypeManager.nameToCategoryIndex[category])
		end
    end

    local function getCalculatedFillTypePrice(referenceFillTypeName, priceFactor, fallbackPrice)
        local referenceFilltype = g_fillTypeManager:getFillTypeByName(referenceFillTypeName:upper())

        if referenceFilltype == nil then
            self:printWarning(string.format( "Filltype '%s' not found, using fallback price", tostring(referenceFillTypeName) ))
            return fallbackPrice
        else
            return referenceFilltype.pricePerLiter * priceFactor
        end

    end

    local sugarPrice = getCalculatedFillTypePrice("sugarBeet", (5*1.35), 823/1000) -- 5x beet price (due to 20% sugar volume) adjusted with 35% sugar price premium
    local pulpPrice = getCalculatedFillTypePrice("silage", 0.25, 42/1000) -- Silage base price is 0.171.. 25% of that is 0.04275 ~ €42/1000L
    local molassesPrice = (760/480) * 0.8 -- 80% of reference value from StrawHarvest
    local feedPelletPrice = ((molassesPrice * 0.05) + (pulpPrice * 0.95)) * 3.47 * 2 -- (80/20 pulp+molasses) * (adj for compaction) * (sell price premium)

    addFillTypeToCurrentMission("sugar", sugarPrice, 0.85/1000, 35)
    -- addHeightTypeToMission("sugar", 35, false, "LIME" )
    addFillTypeToCategories("sugar", {"BULK", "TRAINWAGON", "AUGERWAGON", "LOADINGVEHICLE"})

    addFillTypeToCurrentMission("beetPulp", pulpPrice, 0.30/1000, 45)
    -- addHeightTypeToMission("beetPulp", 45, true, "CHAFF" )
    addFillTypeToCategories("beetPulp", {"BULK", "TRAINWAGON", "AUGERWAGON", "FORAGEWAGON", "SILAGETRAILER", "FORK", "LOADINGVEHICLE"})

    addFillTypeToCurrentMission("supaFeedPellets", feedPelletPrice, 0.65/1000, 30)
    -- addHeightTypeToMission("feedPellets", 30, false, "WOODCHIPS" )
    addFillTypeToCategories("supaFeedPellets", {"BULK", "TRAINWAGON", "AUGERWAGON", "FORAGEWAGON", "SILAGETRAILER", "FORK", "LOADINGVEHICLE"})

    addFillTypeToCurrentMission("molasses", molassesPrice, (1.38/1000), 30)
    -- addHeightTypeToMission("feedPellets", 30, false, "WOODCHIPS" )
    addFillTypeToCategories("molasses", {"LIQUID"})


    self.priceLevels = {
        sugar = sugarPrice,
        pulp = pulpPrice,
        -- pulpBiogas = pulpBiogasPrice,
        molasses = molassesPrice,
        feedPellets = feedPelletPrice,
    }

    g_currentMission.hud.fillLevelsDisplay:refreshFillTypes(g_fillTypeManager)
end


-- function SugarBeetHarvest:delete()
-- end

SellingStation.load = Utils.appendedFunction(SellingStation.load, function(sellStation, xmlFile, key,customEnvironment)
    if sellStation == nil then -- Should never happen, but let's do the check just in case anyway
        return
    end

    if BeetHarvestAddon.settings.autoAddToSellpoints then
        local hasEggs = sellStation.acceptedFillTypes[FillType.EGG]
        local hasSugar = sellStation.acceptedFillTypes[FillType.SUGAR]
        local hasHay = sellStation.acceptedFillTypes[FillType.DRYGRASS_WINDROW]
        local hasFeedPellets = sellStation.acceptedFillTypes[FillType.SUPAFEEDPELLETS]

        local needsUpdate = false

        if hasEggs and not hasSugar then
            local fillTypeIndexToAdd = g_fillTypeManager:getFillTypeIndexByName("SUGAR")
            local price = g_fillTypeManager:getFillTypeByName("SUGAR").pricePerLiter
            sellStation:addAcceptedFillType(fillTypeIndexToAdd, price, true, false)
            local priceMultiplier = sellStation.priceMultipliers[ g_fillTypeManager:getFillTypeIndexByName("EGG")] * 0.99585
            sellStation.priceMultipliers[ g_fillTypeManager:getFillTypeIndexByName("SUGAR")] = MathUtil.clamp(priceMultiplier, 0.1, 1.0)
            needsUpdate = true
        end

        local function addRelatedFilltypeToSellstation(fillTypeToAdd, relatedFillType)
            local hasRelatedFilltype = sellStation.acceptedFillTypes[relatedFillType]
            local hasNewFilltype = sellStation.acceptedFillTypes[fillTypeToAdd]

            if hasRelatedFilltype and not hasNewFilltype then

                local price = g_fillTypeManager:getFillTypeByIndex(fillTypeToAdd).pricePerLiter
                local priceMultiplier = sellStation.priceMultipliers[ relatedFillType ] * 0.99765
                sellStation:addAcceptedFillType(fillTypeToAdd, price, true, false)
                sellStation.priceMultipliers[ fillTypeToAdd ] = MathUtil.clamp(priceMultiplier, 0.1, 1.0)
                needsUpdate = true
            end
        end


        addRelatedFilltypeToSellstation(FillType.SUPAFEEDPELLETS, FillType.DRYGRASS_WINDROW)
        addRelatedFilltypeToSellstation(FillType.MOLASSES, FillType.SUGARBEET)

        if needsUpdate then 
            sellStation:initPricingDynamics()
        end
    end

    return true
end)

-- Append to BGA
Bga.load = Utils.overwrittenFunction(Bga.load, function (self, superFunc, xmlFile, key, customEnvironment)
    local returnValue = superFunc(self, xmlFile, key, customEnvironment)

    if not BeetHarvestAddon.settings.excludePulpFromBGA then
        BeetHarvestAddon:printInfo("Extending BGA with support for beetPulp")

		if self ~= nil then -- Can this even be possible?

			local silageFilltypeIndex = g_fillTypeManager:getFillTypeIndexByName("SILAGE")
			local beetPulpFilltypeIndex = g_fillTypeManager:getFillTypeIndexByName("BEETPULP")

            -- go through all BGA slots and check their fillTypes for "silage"
			for _, slot in pairs(self.bunker.slots) do

				if slot.fillTypes[silageFilltypeIndex] then
					local fillType = {}
					fillType.fillLevel = 0
					fillType.scale = slot.fillTypes[silageFilltypeIndex].scale * 0.8
					fillType.pricePerLiter = slot.fillTypes[silageFilltypeIndex].pricePerLiter * 0.8

					-- add new fillType to fillTypes
					slot.fillTypes[beetPulpFilltypeIndex] = fillType

					-- add slot to fillType-to-slot table
					if self.bunker.fillTypeToSlot[beetPulpFilltypeIndex] == nil then
						self.bunker.fillTypeToSlot[beetPulpFilltypeIndex] = slot
					end
				end
			end

		end
	end
	
    return returnValue
end)

-- ### EXTEND OTHER OBJECTS/VEHICLES ###

function BeetHarvestAddon:appendFoodGroups(foodManager)

    --if BeetHarvestAddon:getIsMaizePlusAnimalFoodAdditionsActive() or BeetHarvestAddon:getIsMaizePlusForageActive() then
    if BeetHarvestAddon:getIsMaizePlusForageActive() then
        BeetHarvestAddon:printError("This should never happen, we shall not touch the food groups when MaizePlus FE is active!")
        return -- Escape to prevent issues with M+ FE/AFA
    end

    foodManager = foodManager or g_animalFoodManager

    -- Just for logging/information purposes
    if not BeetHarvestAddon:getIsMaizePlusForageActive() then
        BeetHarvestAddon:printDebug("Using default feed settings")
    else  -- Special case only for Maize+ with Forage extension
        BeetHarvestAddon:printInfo("Maize+ Forage Extension is active, using special Maize+ Forage Extension settings for feed filltype mappings")
        return -- Escape to prevent issues with M+ FE/AFA
    end

    for animalType, group in pairs(foodManager.foodGroups) do
        -- BeetHarvestAddon:printDebugVar("foodGroup", key)
        local list = group.content
        if list ~= nil then

            local pelletsFoodGroupIndex
            local pulpFoodGroupIndex
            local molassesFoodGroupIndex


            -- Default fill type mapping for animals in vanilla game, with Seasons and with Maize+ (w/o Forage extension)
            if not BeetHarvestAddon:getIsMaizePlusForageActive() then
                if animalType == "COW" then
                    pelletsFoodGroupIndex = 1
                    pulpFoodGroupIndex = 2
                elseif animalType == "PIG" then
                    pelletsFoodGroupIndex = 1
                    pulpFoodGroupIndex = 2
                elseif animalType == "SHEEP" then
                    pelletsFoodGroupIndex = 1
                    pulpFoodGroupIndex = 1
                elseif animalType == "HORSE" then
                    pelletsFoodGroupIndex = 2
                    pulpFoodGroupIndex = 1
                end
    

            else  -- Special case only for Maize+ with Forage extension

                if animalType == "COW" then
                    pelletsFoodGroupIndex = (#list > 3 and 4) or 1 -- Make sure we actually have a fourth food group to prevent errors
                    pulpFoodGroupIndex = 2
                    molassesFoodGroupIndex = 3
                elseif animalType == "PIG" then
                    pelletsFoodGroupIndex = 2
                    pulpFoodGroupIndex = (#list > 3 and 4) or 3 -- Make sure we actually have a fourth food group to prevent errors
                    molassesFoodGroupIndex = 1
                elseif animalType == "SHEEP" then
                    pelletsFoodGroupIndex = (#list > 2 and 3) or 1 -- Make sure we actually have a fourth food group to prevent errors
                    pulpFoodGroupIndex = (#list > 1 and 2) or 1 -- Make sure we actually have a fourth food group to prevent errors
                    molassesFoodGroupIndex = (#list > 3 and 4) or 1 -- Make sure we actually have a fourth food group to prevent errors
                elseif animalType == "HORSE" then
                    pelletsFoodGroupIndex = (#list > 2 and 3) or 2 -- Make sure we actually have a fourth food group to prevent errors
                    pulpFoodGroupIndex = (#list > 1 and 2) or 1 -- Make sure we actually have a fourth food group to prevent errors
                    molassesFoodGroupIndex = (#list > 1 and 2) or 1 -- Make sure we actually have a fourth food group to prevent errors
                end

            end

            --- Adds a filltype to a specific food group for the current animal type
            local function addFilltypeToFoodgroup(foodGroupIndex, fillType)
                if foodGroupIndex == nil then return end -- Escape if we have no list index value

                local foodGroup = list[foodGroupIndex]

                if foodGroup ~= nil then
                    table.insert( foodGroup.fillTypes, fillType )
                end
            end

            -- If we have a pellet food group index and that list item is found (not nil), try to add the filltype
            addFilltypeToFoodgroup(pelletsFoodGroupIndex, FillType.SUPAFEEDPELLETS)
            addFilltypeToFoodgroup(pulpFoodGroupIndex, FillType.BEETPULP)
            addFilltypeToFoodgroup(molassesFoodGroupIndex, FillType.MOLASSES)

        end
    end    
end

AnimalFoodManager.loadFoodGroups = Utils.overwrittenFunction(AnimalFoodManager.loadFoodGroups, function(foodManager, superFunc, xmlFile)
    if not superFunc(foodManager, xmlFile) then
        return false
    end

    -- BeetHarvestAddon:appendFoodGroups(foodManager)

    return true
end)


AnimalFoodManager.loadMixtures = Utils.overwrittenFunction(AnimalFoodManager.loadMixtures, function(foodManager, superFunc, xmlFile)
    local retVal = superFunc(foodManager, xmlFile)

    -- Only add feed mixes if MaizePlus FE is inactive, otherwise we cause issues
    -- if not BeetHarvestAddon:getIsMaizePlusAnimalFoodAdditionsActive() and not BeetHarvestAddon:getIsMaizePlusForageActive() then
    if not BeetHarvestAddon:getIsMaizePlusForageActive() then
        BeetHarvestAddon:prepareFoodMixtures(foodManager)
    else
        BeetHarvestAddon:printInfo("Disabled the feed mix additions due to MaizePlus FE/AFA being active")
    end

    return retVal
end)

-- MixerWagon.onLoad = Utils.appendedFunction(MixerWagon.onLoad, function (vehicle, savegame)
--     local spec = vehicle.spec_mixerWagon

--     -- Add hay and straw pellets to the supportedFillTypes.
--     for _, fillUnit in pairs(vehicle:getFillUnits()) do
--         if fillUnit.supportedFillTypes[FillType.FORAGE] then
--             fillUnit.supportedFillTypes[FillType.FEEDPELLETS] = true
--         end

--     end

--     -- Add hay and straw pellets to the mix entries that have straw and dry grass.
--     for _, mixerWagonFillType in ipairs(spec.mixerWagonFillTypes) do
--         if mixerWagonFillType.fillTypes[FillType.DRYGRASS_WINDROW] ~= nil then
--             mixerWagonFillType.fillTypes[FillType.BEETPULP] = true
--         end
--     end
-- end)

-- --- Compensate for the material compaction in feed pellets
-- MixerWagon.addFillUnitFillLevel = Utils.overwrittenFunction(MixerWagon.addFillUnitFillLevel, function(vehicle, injSuperFunc, superFunc, farmId, fillUnitIndex, fillLevelDelta, fillTypeIndex, toolType, fillPositionData)
--     if fillTypeIndex == FillType.FEEDPELLETS then
--         fillTypeIndex = FillType.BEETPULP
--     end

--     local x = {
--         vehicle, injSuperFunc, superFunc, farmId, fillUnitIndex, fillLevelDelta, fillTypeIndex, toolType, fillPositionData
--     }

--     -- spec_mixerWagon
--     --fillUnitIndex
--     --mixerWagonFillTypes
--     --fillTypeToMixerWagonFillType
--     --

--     local delta = injSuperFunc(vehicle, superFunc, farmId, fillUnitIndex, fillLevelDelta, fillTypeIndex, toolType, fillPositionData)
--     -- if fillTypeIndex == FillType.FEEDPELLETS then
--     --     delta = delta * 0.25 -- compensate with the pelletizer.
--     -- end
--     return delta
-- end)

-- ---Compensate feed pellet pallets on the animal husbandry modules.
-- HusbandryModuleFood.addFillLevelFromTool = Utils.overwrittenFunction(HusbandryModuleFood.addFillLevelFromTool, function(module, superFunc, farmId, deltaFillLevel, fillTypeIndex)
--     local delta = superFunc(module, farmId, deltaFillLevel, fillTypeIndex)
--     -- if fillTypeIndex == FillType.STRAWPELLETS or fillTypeIndex == FillType.HAYPELLETS then
--     --     delta = delta * 0.25 -- compensate with the pelletizer.
--     -- end
--     return delta
-- end)

-- Files referenced by script, explicitly stated here to avoid false positives with the TestRunner
function TestRunnerDummy()
    -- hud/hud_fill_sugar.dds
    -- hud/hud_fill_sugar_sml.dds
    -- hud/hud_fill_beetPulp.dds
    -- hud/hud_fill_beetPulp_sml.dds
    -- hud/hud_fill_feedPellets.dds
    -- hud/hud_fill_feedPellets_sml.dds
    -- hud/hud_fill_supaFeedPellets.dds
    -- hud/hud_fill_supaFeedPellets_sml.dds
    -- hud/hud_fill_molasses.dds
    -- hud/hud_fill_molasses_sml.dds

    -- fillTypes/beetPulp_distance_diffuse.dds
    -- fillTypes/feedPellets_distance_diffuse.dds
    -- fillTypes/supaFeedPellets_distance_diffuse.dds
    -- fillTypes/sugar_distance_diffuse.dds

    -- fillTypes/feedPellets_normal.dds
    -- fillTypes/beetPulp_normal.dds
    -- fillTypes/sugar_normal.dds
    -- fillTypes/supaFeedPellets_normal.dds

    -- hud/monochrome/hud_fill_sugar.dds
    -- hud/monochrome/hud_fill_sugar_sml.dds
    -- hud/monochrome/hud_fill_beetPulp.dds
    -- hud/monochrome/hud_fill_beetPulp_sml.dds
    -- hud/monochrome/hud_fill_feedPellets.dds
    -- hud/monochrome/hud_fill_feedPellets_sml.dds
    -- hud/monochrome/hud_fill_supaFeedPellets.dds
    -- hud/monochrome/hud_fill_supaFeedPellets_sml.dds
    -- hud/monochrome/hud_fill_molasses.dds
    -- hud/monochrome/hud_fill_molasses_sml.dds
end