Fixed the formatting and refactored to avoid infinite loop & deadlocks