lots of cleanup and separated downsample function