%{
#include <stdio.h>
#include <stdlib.h>

int line_num = 1;
%}

letter      [A-Za-z_] 
digit       [0-9]
id          {letter}({letter}|{digit})*

%%

"/*"([^*]|\*+[^*/])*\*+"/" { 
    for (int i = 0; yytext[i] != '\0'; i++) {
        if (yytext[i] == '\n') {
            line_num++;
        }
    }
}

"//".*      { }

[ \t\r]+    { }

\n          { line_num++; }

"int"	    { printf("KEYWORD: %s\n", yytext); }
"if"        { printf("KEYWORD: %s\n", yytext); }
"while"     { printf("KEYWORD: %s\n", yytext); }

"+"|"-"|"*"|"/"|"%" { printf("ARITHMETIC: %s\n", yytext); }

"("         { printf("LEFT_PAREN: %s\n", yytext); }
")"         { printf("RIGHT_PAREN: %s\n", yytext); }
"{"         { printf("LEFT_BRACE: %s\n", yytext); }
"}"         { printf("RIGHT_BRACE: %s\n", yytext); }
";"         { printf("SEMICOLON: %s\n", yytext); }

{id}        { printf("IDENTIFIER: %s\n", yytext); }
{digit}+    { printf("NUMBER: %s\n", yytext); }

.           { printf("LEXICAL ERROR [Line %d]: Unrecognized token '%s'\n", line_num, yytext); }

%%

int yywrap(void) {
    return 1;
}

int main(int argc, char **argv) {
    if (argc > 1) {
        FILE *file = fopen(argv[1], "r");
        if (!file) {
            fprintf(stderr, "Error: Could not open file '%s'\n", argv[1]);
            return 1;
        }
        yyin = file;
        printf("Analyzing file: %s\n", argv[1]);
        printf("--------------------------------------\n");
    } else {
        printf("No file provided. Type your input (Ctrl+D to exit):\n");
    }

    yylex();
    
    return 0;
}