refactored download function