Refactor download logic