Added logging + refactored logic