Restructure as library and clean up code.