Refactored reusable code
Bugfixes and cleanup