Reformat, cleanup, remove duplicate code