Merged two almost equal functions and other cleanups