Cleaned up solve function