although it works, but still should move the 'totalBytesWritten += bytesWritten;' line down here.