Lots of cleanup and more util functions