Some good refactoring but implemented some hard to find bugs.

Fix later.