some refactoring, added helper functions and improved readability