Generalize code and tidy up a bit