Refactored the script into functions and adding locking