M6: finish task 2, and small refactoring