Refactor writeImages()