refactored and added more logging