Refactoring and Improved logging. Moved common functionality to functions.sh