clean up the code and add a batch of useful tests