heavily refactored and documented