cleanup code and add unittest