Add tests and clean up flash code