Bugfixes and Major refactor