Refactoring stage 1

cleaning code; modularizing into methods.