refactor to reduce redundancy a bit, and support writing Memory > 2Gb