Cleanup code and optimize