code refactored. only change remaining will be on comments