Refractor cleanup routines and fix bugs