#!/bin/sh

# validate expression
originalEquation=$(echo "$2" | sed "s/\[/\(/g" | sed "s/\]/\)/g")
parsedExpression=$(echo "$2" | sed "s/\[/\(/g" | sed "s/\]/\)/g" | grep -Eo "[0-9 + -- / * ^ . a-z A-Z ~ : ( ) ]*")
if [ "$parsedExpression" != "$originalEquation" ]; then
  echo "Error: Expression contains invalid characters"
  return 1
fi

equation=$(echo "$originalEquation" | sed "s:/:(over):g" | sed "s/~/|/g" | sed "s/-/%2D/g")
operation=$(echo "$1" | tr "[[:upper:]]" "[[:lower:]]")

curl -s https://newton.now.sh/api/v2/$operation/"$equation" | grep -Eo '"result":"[a-z A-Z 0-9 ( ) \^ / -- + , ]*' | sed s/'"result":"'//g | tr '"' " "

# Usage: newton [operation] [expression]
# Examples:
#  ===================================================
# |Operations     Sample Expression      Sample Result|
# |---------------------------------------------------|
# |Simplify       [[2x^2]+7]*[4x^2]    8 x^4 + 28 x^2 |
# |Factor             x^2 + 2x             x (x + 2)  |
# |Derive              x^2+2x               2 x + 2   |
# |Integrate           x^2+2x         1/3 x^3 + x^2 +C|
# |Roots/Zeroes        x^2+2x                2, 0     |
# |Tangent             2~x^3              12 x + -16  | (Finding tangent line when x=2 for expression x^3)
# |Area               2:4~x^3                 60      | (Finding area under curve from 2 to 4 for expression x^3)
# |Cos                   pi                   -1      |
# |Sin                   pi                    0      |
# |Tan                  pi/4                   1      |
# |ArcCos                 1                    0      |
# |ArcSin                 0                    0      |
# |ArcTan                pi                arcsin(pi) |
# |Abs                   -2                    2      |
# |Log                   2~8                   3      | (Log base 2 of eight)
#  ===================================================
# Valid Symbols:
 #  + add
 #  - subtract
 #  [ left parenthesis (you must use brackets bash has a bultin for parenthesis)
 #  ] right parenthesis (you must use brackets bash has a bultin for parenthesis)
 #  * multiply
 #  / divide
 #  ^ power
 #  : between the range of left and right side (only for area under curve)
 #  ~ parameter on right side (only for area, tangent line and log)
