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

/* Global variable to track the current line number for errors */
int line_num = 1;
%}

/* DEFINITIONS */
/* Added underscore to letter as it is standard in C identifiers */
letter      [A-Za-z_] 
digit       [0-9]
id          {letter}({letter}|{digit})*

%%

    /* TRANSLATION RULES */

    /* 1. Multi-line Comment */
"/*"([^*]|\*+[^*/])*\*+"/" { 
    /* We must count newlines inside the comment to keep our line_num accurate */
    for (int i = 0; yytext[i] != '\0'; i++) {
        if (yytext[i] == '\n') {
            line_num++;
        }
    }
}

    /* 2. Single-line Comment */
"//".*      { /* Ignore */ }

    /* 3. Ignore Spaces, Tabs, and Carriage Returns */
[ \t\r]+    { /* Ignore */ }

    /* 4. New Line */
\n          { line_num++; }

    /* 5. Keywords (Must be placed before the {id} rule) */
"int"	    { printf("KEYWORD: %s\n", yytext); }
"if"        { printf("KEYWORD: %s\n", yytext); }
"while"     { printf("KEYWORD: %s\n", yytext); }

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

    /* 7. Parentheses, Braces, and Semicolons */
"("         { 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); }

    /* 8. Identifiers and Numbers */
{id}        { printf("IDENTIFIER: %s\n", yytext); }
{digit}+    { printf("NUMBER: %s\n", yytext); }

    /* 9. Lexical Error Catch-All */
.           { printf("LEXICAL ERROR [Line %d]: Unrecognized token '%s'\n", line_num, yytext); }

%%

/* USER ROUTINES */

int yywrap(void) {
    return 1;
}

int main(int argc, char **argv) {
    /* If a filename is passed when running the program, read from it */
    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; /* yyin is Flex's built-in file pointer */
        printf("Analyzing file: %s\n", argv[1]);
        printf("--------------------------------------\n");
    } else {
        printf("No file provided. Type your input (Ctrl+D to exit):\n");
    }

    /* Start lexical analysis */
    yylex();
    
    return 0;
}