Refactoring working code. Fixing issues #1, #2, #3 and #4