import math
import sys

def factorial(n):
    if n == int(n):
        return math.factorial(int(n))
    else:
        raise ValueError("Factorial is only defined for integers.")

def safe_eval(expression):
    safe_dict = {
        'log10':        math.log10,
        'log':          math.log,
        'exp':          math.exp,
        'abs':          abs,
        'round':        round,
        'int':          int,
        'float':        float,
        'pi':           math.pi,
        'e':            math.e,
        'sin':          math.sin,
        'cos':          math.cos,
        'tan':          math.tan,
        'sqrt':         math.sqrt,
        'factorial':    factorial,
        'mod':          lambda x, y: x % y,
        'sindeg':       lambda x: math.sin(math.radians(x)),
        'cosdeg':       lambda x: math.cos(math.radians(x)),
        'tandeg':       lambda x: math.tan(math.radians(x))
    }

    try:
        return eval(expression, {"__builtins__": None}, safe_dict)
    except Exception as e:
        return f"Error: {str(e)}"

def format_result(result):
    if isinstance(result, (int, float)):
        if abs(result) > 100000:
            return f'{result}  ({result:.2E})'
        else:
            return result
    return result

def print_help():
    help_text = """
+------------------------+------------------------------+-------------------------------------------+
|        Operator        |         Description          |               Example                    |
+------------------------+------------------------------+-------------------------------------------+
| +, -, *, /, %, **, ^   | Basic arithmetic operations  | 3 + 5 * 2, 10 ^ 2, 5 % 2                 |
| log10, log, ln         | Logarithmic functions        | log10(100), log(100), ln(100)            |
| exp                    | Exponential function         | exp(1), exp(2)                           |
| abs, sqrt              | Absolute value & Square root | abs(-5), sqrt(16)                        |
| int, float             | Type conversion              | int(3.5), float(2)                       |
| round                  | Rounding function            | round(3.14159, 2)                        |
| pi, e                  | Mathematical constants       | pi, e                                    |
| sin, cos, tan          | Trigonometric functions      | sin(pi/2), cos(0), tan(pi/4)             |
| sindeg, cosdeg, tandeg | Trig. functions (degrees)    | sindeg(90), cosdeg(0), tandeg(45)        |
| factorial (!)          | Factorial function           | factorial(5), 5!                         |
| mod                    | Modulo operation             | 10 mod 3                                 |
+------------------------+------------------------------+-------------------------------------------+
    """
    print(help_text)

def main():
    print_help()
    
    while True:
        if sys.stdin.isatty():
            if len(sys.argv) != 1:
                print("Please provide a mathematical expression through standard input.")
                sys.exit(1)
            expression = input('>  ').strip()
        else:
            expression = sys.stdin.read().strip()
    
        if expression == "exit": 
            sys.exit(1)

        # Replacing custom notations with safe equivalents
        expression = expression.replace('^', '**')
        expression = expression.replace('log', 'log10')
        expression = expression.replace('ln', 'log')
        expression = expression.replace('!', ' factorial')
        expression = expression.replace('mod', '%')

        result = safe_eval(expression)
        formatted_result = format_result(result)

        print(f'\n     {formatted_result}\n')

if __name__ == "__main__":
    main()
