%{
#undef yywrap
#define yywrap() 1
#include <math.h>
#include <stdio.h>
#include <stdlib.h>

int f1 = 0, f2 = 0;
char oper;
float op1 = 0, op2 = 0, ans = 0;

void eval();
float deg_to_rad(float degrees); // Function to convert degrees to radians
%}

DIGIT [0-9]
NUM {DIGIT}+(\.{DIGIT}+)?
OP [*/+\-]

%%

{NUM} {
    if (f1 == 0) {
        op1 = atof(yytext);
        f1 = 1;
    } else if (f2 == -1) {
        op2 = atof(yytext);
        f2 = 1;
    }

    if (f1 == 1 && f2 == 1) {
        eval();
        f1 = 0;
        f2 = 0;
    }
}

{OP} {
    oper = (char)*yytext;
    f2 = -1;
}

[sS][il][nN]|[cC][oO][sS]|[tT][aA][nN] {
    oper = *yytext;  // Correctly assigns the operation based on the first character
    f2 = -1;
}

[0-9](\.[0-9]+)?[lL][oO][gG] {
    oper = 'l'; // Recognizes log as a valid operation
    f2 = -1;
}

\n {
    if (f1 == 1 && f2 == 1) {
        eval();
        f1 = 0;
        f2 = 0;
    }
}

%%

int main() {
    yylex();
    return 0;
}

float deg_to_rad(float degrees) {
    return degrees * (M_PI / 180.0); // Convert degrees to radians
}

void eval() {
    switch (oper) {
        case '+':
            ans = op1 + op2;
            break;
        case '-':
            ans = op1 - op2;
            break;
        case '*':
            ans = op1 * op2;
            break;
        case '/':
            if (op2 == 0) {
                printf("ERROR: Division by zero\n");
                return;
            } else {
                ans = op1 / op2;
            }
            break;
        case 's':  // sin
        case 'S':
            ans = sin(deg_to_rad(op1));  // Convert input to radians
            break;
        case 'c':  // cos
        case 'C':
            ans = cos(deg_to_rad(op1));  // Convert input to radians
            break;
        case 't':  // tan
        case 'T':
            ans = tan(deg_to_rad(op1));  // Convert input to radians
            break;
        case 'l':  // log
        case 'L':
            ans = log(op1);
            break;
        default:
            printf("Operation not available\n");
            break;
    }
    printf("The answer is = %f\n", ans);
}