Complete code refactoring, bugfixes, enhancements