All kinds of code cleanup, mostly to get some mess detection fixed.