Finished refactoring code: is now working