Clean-up some code and split common functions