Bugfixes and rewrite parts of code