Refactor dithering code