Refined logging and cleaned the code