Fixed glitch in chunked-download code.

Could (and probably will) cause non-terminating loops. General refactors.