gc.sh: refactor some code into functions