refine the code and add integration tests