Refactor

Refactor for stability, testability, etc.