Lots of refactoring and internal fixes.