Refactor and fix lock-up