refactored algebra code