#include <stdio.h>
#include <ctype.h>
#include <string.h>

typedef struct {
    char lexeme[100];
    char type[20];
} Token;

const char* keywords[] = {"int", "float", "if", "else", "while", "return", "void", "char", "for", "double"};
const int num_keywords = sizeof(keywords) / sizeof(keywords[0]);

int isKeyword(const char* token) {
    for (int i = 0; i < num_keywords; i++) {
        if (strcmp(token, keywords[i]) == 0) return 1;
    }
    return 0;
}

Token classifyToken(const char *token) {
    Token t;
    strcpy(t.lexeme, token);

    if (isKeyword(token))
        strcpy(t.type, "KEYWORD");
    else if (isdigit(token[0]))
        strcpy(t.type, "NUMBER");
    else if (isalpha(token[0]) || token[0] == '_')
        strcpy(t.type, "IDENTIFIER");
    else if (strchr("+-*/=<>!", token[0]))
        strcpy(t.type, "OPERATOR");
    else if (strchr(";(),{}", token[0]))
        strcpy(t.type, "DELIMITER");
    else
        strcpy(t.type, "UNKNOWN");

    return t;
}

void lexicalAnalyzer(const char *input) {
    char token[100];
    int index = 0;

    for (int i = 0; i < strlen(input); i++) {
        char ch = input[i];

        if (isspace(ch)) {
            if (index > 0) {
                token[index] = '\0';
                Token t = classifyToken(token);
                printf("%s: %s\n", t.type, t.lexeme);
                index = 0;
            }
        }
        // Multi-character operators check
        else if ((ch == '+' && input[i+1] == '=') ||
                 (ch == '-' && input[i+1] == '=') ||
                 (ch == '*' && input[i+1] == '=') ||
                 (ch == '/' && input[i+1] == '=') ||
                 (ch == '=' && input[i+1] == '=') ||
                 (ch == '!' && input[i+1] == '=') ||
                 (ch == '>' && input[i+1] == '=') ||
                 (ch == '<' && input[i+1] == '=')) {
            token[0] = ch;
            token[1] = input[i+1];
            token[2] = '\0';
            Token t = classifyToken(token);
            printf("%s: %s\n", t.type, t.lexeme);
            i++; // skip next char
        }
        // Single-character operators or delimiters
        else if (strchr("+-*/=<>!;(),{}", ch)) {
            if (index > 0) {
                token[index] = '\0';
                Token t = classifyToken(token);
                printf("%s: %s\n", t.type, t.lexeme);
                index = 0;
            }
            token[0] = ch;
            token[1] = '\0';
            Token t = classifyToken(token);
            printf("%s: %s\n", t.type, t.lexeme);
        }
        else {
            token[index++] = ch;
        }
    }

    if (index > 0) {
        token[index] = '\0';
        Token t = classifyToken(token);
        printf("%s: %s\n", t.type, t.lexeme);
    }
}

int main() {
    char input[200];
    printf("Enter a simple C code snippet: ");
    fgets(input, sizeof(input), stdin);

    printf("\nTokens Found:\n");
    lexicalAnalyzer(input);

    return 0;
}
