Some code refactoring and commenting

Some minor code fixes. Still more refactoring and commenting to do