Unflatten images & clean up code