refactored and bugfixes