refactoring code and adding lots o comments