bugfixed and refactored