One way that springs to mind is to set all handles to zero when freeing them. For example, replace FreeEntity by adding this function to your code :
Function MyFreeEntity(ent)
FreeEntity(ent)
Return 0
End Function
And replace all FreeEntity(ent) calls with ent=FreeEntity(ent)
Function MyFreeEntity(ent)
FreeEntity(ent)
Return 0
End Function
And replace all FreeEntity(ent) calls with ent=FreeEntity(ent)