Refactoring

Improved state handling.