Fix spacing, formatting issues.

Remove unnecessary const_cast.
Factor out common code into helper function.