major refactoring, cleaning, and commenting