refactored, commented and polished