Refactor scripts into functions