/* Lex code to count and list total number of tokens */

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

int n = 0;    // Counter for total tokens
char* tokens[1000];   // Array to store tokens (up to 1000 tokens)
int tokenIndex = 0;    // Index to store tokens
%}

/* Rule Section */
%%

"while"|"if"|"else" {
    n++; 
    printf("\tkeyword: %s\n", yytext); 
    tokens[tokenIndex++] = yytext;  // Store the token
}

"int"|"float" {
    n++; 
    printf("\tkeyword: %s\n", yytext); 
    tokens[tokenIndex++] = yytext;  // Store the token
}

[a-zA-Z_][a-zA-Z0-9_]* {
    n++; 
    printf("\tidentifier: %s\n", yytext); 
    tokens[tokenIndex++] = yytext;  // Store the token
}

"<="|"=="|"="|"++"|"-"|"*"|"+" {
    n++; 
    printf("\toperator: %s\n", yytext); 
    tokens[tokenIndex++] = yytext;  // Store the token
}

[(){}|,;] {
    n++; 
    printf("\tseparator: %s\n", yytext); 
    tokens[tokenIndex++] = yytext;  // Store the token
}

[0-9]*"."[0-9]+ {
    n++; 
    printf("\tfloat: %s\n", yytext); 
    tokens[tokenIndex++] = yytext;  // Store the token
}

[0-9]+ {
    n++; 
    printf("\tinteger: %s\n", yytext); 
    tokens[tokenIndex++] = yytext;  // Store the token
}

. ;  // Ignore unrecognized characters

%%

/* Main function */
int main() {
    yylex();   // Start lexical analysis
    
    printf("\nTotal number of tokens = %d\n", n);  // Print total token count
    
    // Print the list of tokens
    printf("\nList of tokens:\n");
    for (int i = 0; i < tokenIndex; i++) {
        printf("%s\n", tokens[i]);  // Print each token
    }
    
    return 0;
}
