refactored into functions. fixed indent bug (thanks emacs)