Refactor download code