Refactor and split common code into multiple helper scripts