package me.nallar.tickthreading.minecraft.patched;

import cpw.mods.fml.common.FMLLog;
import net.minecraft.entity.Entity;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.EntityEvent;

public abstract class PatchChunk extends Chunk {
	public PatchChunk(World par1World, int par2, int par3) {
		super(par1World, par2, par3);
	}

	@Override
	public void addEntity(Entity par1Entity) {
		int var2 = MathHelper.floor_double(par1Entity.posX / 16.0D);
		int var3 = MathHelper.floor_double(par1Entity.posZ / 16.0D);

		if (var2 != this.xPosition || var3 != this.zPosition) {
			FMLLog.warning("Entity %s added to the wrong chunk - expected x%d z%d, got x%d z%d", this.xPosition, this.zPosition, var2, var3);
			return;
		}

		this.hasEntities = true;

		int var4 = MathHelper.floor_double(par1Entity.posY / 16.0D);

		if (var4 < 0) {
			var4 = 0;
		}

		if (var4 >= this.entityLists.length) {
			var4 = this.entityLists.length - 1;
		}
		MinecraftForge.EVENT_BUS.post(new EntityEvent.EnteringChunk(par1Entity, this.xPosition, this.zPosition, par1Entity.chunkCoordX, par1Entity.chunkCoordZ));
		par1Entity.addedToChunk = true;
		par1Entity.chunkCoordX = this.xPosition;
		par1Entity.chunkCoordY = var4;
		par1Entity.chunkCoordZ = this.zPosition;
		this.entityLists[var4].add(par1Entity);
	}
}

@@ -47,16 +47,71 @@
 hed;%0D%0A%0D%0A
+import java.util.ArrayList;%0D%0Aimport java.util.List;%0D%0A%0D%0A
 import c
@@ -392,16 +392,67 @@
 yEvent;%0D
+%0Aimport net.minecraftforge.event.world.ChunkEvent;%0D
 %0A%0D%0Apubli
@@ -496,16 +496,48 @@
 hunk %7B%0D%0A
+%09private List%3CEntity%3E toAdd;%0D%0A%0D%0A
 %09public 
@@ -631,62 +631,622 @@
 %0A%0D%0A%09
-@Override%0D%0A%09public void addEntity(Entity par1Entity) %7B
+public void construct() %7B%0D%0A%09%09toAdd = new ArrayList%3CEntity%3E();%0D%0A%09%7D%0D%0A%0D%0A%09@Override%0D%0A%09public void onChunkLoad() %7B%0D%0A%09%09this.worldObj.addTileEntity(this.chunkTileEntityMap.values());%0D%0A%0D%0A%09%09for (int var1 = 0; var1 %3C this.entityLists.length; ++var1) %7B%0D%0A%09%09%09this.worldObj.addLoadedEntities(this.entityLists%5Bvar1%5D);%0D%0A%09%09%7D%0D%0A%09%09MinecraftForge.EVENT_BUS.post(new ChunkEvent.Load(this));%0D%0A%09%09this.isChunkLoaded = true;%0D%0A%09%09for (Entity entity : toAdd) %7B%0D%0A%09%09%09addEntity(entity);%0D%0A%09%09%7D%0D%0A%09%09toAdd.clear();%0D%0A%09%7D%0D%0A%0D%0A%09@Override%0D%0A%09public void addEntity(Entity par1Entity) %7B%0D%0A%09%09if (!this.isChunkLoaded) %7B%0D%0A%09%09%09toAdd.add(par1Entity);%0D%0A%09%09%09return;%0D%0A%09%09%7D
 %0D%0A%09%09

Fix entity already tracked IllegalStateException, fixes #96