#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <math.h>
#include <time.h>

#ifdef _WIN32
    #include <windows.h>
    #include <wininet.h>
    #define OS_WINDOWS 1
#else
    #include <sys/utsname.h>
    #include <sys/stat.h>
    #include <unistd.h>
    #define OS_WINDOWS 0
#endif

#define VERSION "4.0.1-BetaN(+AU)"
#define MAX_TOKENS 4096
#define MAX_VARS 256
#define MAX_LINE 4096
#define MAX_STRING 1024

typedef enum {
    TOKEN_EOF,
    TOKEN_IDENTIFIER,
    TOKEN_STRING,
    TOKEN_NUMBER,
    TOKEN_PRINT,
    TOKEN_VAR,
    TOKEN_IF,
    TOKEN_WHILE,
    TOKEN_FOR,
    TOKEN_FUNCTION,
    TOKEN_RETURN,
    TOKEN_ELSE,
    TOKEN_LPAREN,
    TOKEN_RPAREN,
    TOKEN_LBRACE,
    TOKEN_RBRACE,
    TOKEN_COMMA,
    TOKEN_SEMICOLON,
    TOKEN_ASSIGN,
    TOKEN_PLUS,
    TOKEN_MINUS,
    TOKEN_MULTIPLY,
    TOKEN_DIVIDE,
    TOKEN_EQUAL,
    TOKEN_NOT_EQUAL,
    TOKEN_GREATER,
    TOKEN_LESS,
    TOKEN_AND,
    TOKEN_OR,
    TOKEN_NOT,
    TOKEN_GREATER_EQUAL,
    TOKEN_LESS_EQUAL,
    TOKEN_MODULO
} TokenType;

typedef struct {
    TokenType type;
    char value[MAX_STRING];
    int line;
} Token;

typedef struct {
    char name[64];
    double num_value;
    char str_value[MAX_STRING];
    int is_string;
} Variable;

Token tokens[MAX_TOKENS];
int token_count = 0;
int current_token = 0;
Variable vars[MAX_VARS];
int var_count = 0;
int print_newline = 1;
int current_line = 1;
int in_for_loop_update = 0;

static const struct {
    const char* name;
    TokenType type;
} keywords[] = {
    {"print", TOKEN_PRINT},
    {"var", TOKEN_VAR},
    {"if", TOKEN_IF},
    {"else", TOKEN_ELSE},
    {"while", TOKEN_WHILE},
    {"for", TOKEN_FOR},
    {"function", TOKEN_FUNCTION},
    {"return", TOKEN_RETURN},
    {NULL, TOKEN_EOF}
};

void error(const char* msg, ...) {
    va_list args;
    va_start(args, msg);
    fprintf(stderr, "[Error at line %d] ", current_line);
    vfprintf(stderr, msg, args);
    fprintf(stderr, "\n");
    va_end(args);
    exit(1);
}

static void skip_whitespace_and_comments(const char** p) {
    while (**p) {
        if (**p == ' ' || **p == '\t' || **p == '\r') {
            (*p)++;
        } else if (**p == '\n') {
            (*p)++;
            current_line++;
        } else if (**p == '#') {
            while (**p && **p != '\n') (*p)++;
        } else {
            break;
        }
    }
}

static void add_token(TokenType type, const char* value) {
    if (token_count >= MAX_TOKENS) {
        error("Too many tokens (max %d)", MAX_TOKENS);
    }
    tokens[token_count].type = type;
    strncpy(tokens[token_count].value, value, MAX_STRING - 1);
    tokens[token_count].value[MAX_STRING - 1] = '\0';
    tokens[token_count].line = current_line;
    token_count++;
}

void tokenize(const char* source) {
    token_count = 0;
    current_line = 1;
    const char* p = source;

    while (1) {
        skip_whitespace_and_comments(&p);
        if (!*p) break;

        // String literal
        if (*p == '"') {
            p++;
            char buf[MAX_STRING];
            int i = 0;
            while (*p && *p != '"' && i < MAX_STRING - 1) {
                if (*p == '\\' && *(p+1)) {
                    p++;
                    switch (*p) {
                        case 'n': buf[i++] = '\n'; break;
                        case 't': buf[i++] = '\t'; break;
                        case 'r': buf[i++] = '\r'; break;
                        case '\\': buf[i++] = '\\'; break;
                        case '"': buf[i++] = '"'; break;
                        default: buf[i++] = *p; break;
                    }
                } else {
                    buf[i++] = *p;
                }
                p++;
            }
            buf[i] = '\0';
            if (*p != '"') error("Unterminated string literal");
            p++;
            add_token(TOKEN_STRING, buf);
            continue;
        }

        // Number
        if (isdigit(*p) || (*p == '.' && isdigit(*(p+1)))) {
            char buf[64];
            int i = 0;
            int dot_count = 0;
            while ((isdigit(*p) || (*p == '.' && dot_count < 1)) && i < 63) {
                if (*p == '.') dot_count++;
                buf[i++] = *p++;
            }
            buf[i] = '\0';
            add_token(TOKEN_NUMBER, buf);
            continue;
        }

        // Identifier or keyword
        if (isalpha(*p) || *p == '_') {
            char buf[64];
            int i = 0;
            while ((isalnum(*p) || *p == '_') && i < 63) {
                buf[i++] = *p++;
            }
            buf[i] = '\0';

            int j;
            for (j = 0; keywords[j].name; j++) {
                if (strcmp(buf, keywords[j].name) == 0) {
                    add_token(keywords[j].type, buf);
                    break;
                }
            }
            if (!keywords[j].name) {
                add_token(TOKEN_IDENTIFIER, buf);
            }
            continue;
        }

        // Two-character operators
        if (*p == '=' && *(p+1) == '=') { add_token(TOKEN_EQUAL, "=="); p += 2; continue; }
        if (*p == '!' && *(p+1) == '=') { add_token(TOKEN_NOT_EQUAL, "!="); p += 2; continue; }
        if (*p == '&' && *(p+1) == '&') { add_token(TOKEN_AND, "&&"); p += 2; continue; }
        if (*p == '|' && *(p+1) == '|') { add_token(TOKEN_OR, "||"); p += 2; continue; }
        if (*p == '>' && *(p+1) == '=') { add_token(TOKEN_GREATER_EQUAL, ">="); p += 2; continue; }
        if (*p == '<' && *(p+1) == '=') { add_token(TOKEN_LESS_EQUAL, "<="); p += 2; continue; }

        // Single-character tokens
        switch (*p) {
            case '(': add_token(TOKEN_LPAREN, "("); break;
            case ')': add_token(TOKEN_RPAREN, ")"); break;
            case '{': add_token(TOKEN_LBRACE, "{"); break;
            case '}': add_token(TOKEN_RBRACE, "}"); break;
            case ',': add_token(TOKEN_COMMA, ","); break;
            case ';': add_token(TOKEN_SEMICOLON, ";"); break;
            case '=': add_token(TOKEN_ASSIGN, "="); break;
            case '>': add_token(TOKEN_GREATER, ">"); break;
            case '<': add_token(TOKEN_LESS, "<"); break;
            case '+': add_token(TOKEN_PLUS, "+"); break;
            case '-': add_token(TOKEN_MINUS, "-"); break;
            case '*': add_token(TOKEN_MULTIPLY, "*"); break;
            case '/': add_token(TOKEN_DIVIDE, "/"); break;
            case '%': add_token(TOKEN_MODULO, "%"); break;
            case '!': add_token(TOKEN_NOT, "!"); break;
            default: error("Unknown character: '%c'", *p);
        }
        p++;
    }

    add_token(TOKEN_EOF, "");
}

Token peek() { return tokens[current_token]; }
Token advance() { return tokens[current_token++]; }

int match(TokenType type) {
    if (peek().type == type) {
        if (tokens[current_token].line > 0) {
            current_line = tokens[current_token].line;
        }
        advance();
        return 1;
    }
    return 0;
}

void consume(TokenType type, const char* msg) {
    if (!match(type)) {
        error("%s (got '%s')", msg, peek().value);
    }
}

// Forward declarations
double evaluate();
void execute_statement();
int update_oraset(const char* target_version);

// Expression parsing
double parse_primary();

double parse_call(const char* func_name) {
    consume(TOKEN_LPAREN, "Expected '(' after function name");
    
    if (strcmp(func_name, "abs") == 0) {
        double val = evaluate();
        consume(TOKEN_RPAREN, "Expected ')'");
        return fabs(val);
    } else if (strcmp(func_name, "sqrt") == 0) {
        double val = evaluate();
        consume(TOKEN_RPAREN, "Expected ')'");
        return sqrt(val);
    } else if (strcmp(func_name, "sin") == 0) {
        double val = evaluate();
        consume(TOKEN_RPAREN, "Expected ')'");
        return sin(val);
    } else if (strcmp(func_name, "cos") == 0) {
        double val = evaluate();
        consume(TOKEN_RPAREN, "Expected ')'");
        return cos(val);
    } else if (strcmp(func_name, "rand") == 0) {
        consume(TOKEN_RPAREN, "Expected ')'");
        return (double)rand() / RAND_MAX;
    } else if (strcmp(func_name, "len") == 0) {
        consume(TOKEN_STRING, "Expected string argument");
        const char* str = tokens[current_token - 1].value;
        consume(TOKEN_RPAREN, "Expected ')'");
        return strlen(str);
    } else if (strcmp(func_name, "num") == 0) {
        consume(TOKEN_STRING, "Expected string argument");
        const char* str = tokens[current_token - 1].value;
        consume(TOKEN_RPAREN, "Expected ')'");
        double val = atof(str);
        return val;
    } else if (strcmp(func_name, "str") == 0) {
        double val = evaluate();
        consume(TOKEN_RPAREN, "Expected ')'");
        char buf[32];
        sprintf(buf, "%g", val);
        for (int i = 0; i < var_count; i++) {
            if (strcmp(vars[i].name, "__tmp_str_result") == 0) {
                strncpy(vars[i].str_value, buf, MAX_STRING - 1);
                vars[i].str_value[MAX_STRING - 1] = '\0';
                vars[i].is_string = 1;
                return 0;
            }
        }
        strncpy(vars[var_count].name, "__tmp_str_result", 63);
        strncpy(vars[var_count].str_value, buf, MAX_STRING - 1);
        vars[var_count].str_value[MAX_STRING - 1] = '\0';
        vars[var_count].is_string = 1;
        var_count++;
        return 0;
    } else {
        error("Undefined function: %s", func_name);
    }
    return 0;
}

double parse_primary() {
    if (match(TOKEN_NUMBER)) {
        return atof(tokens[current_token - 1].value);
    }
    if (match(TOKEN_STRING)) {
        error("Cannot use string in expression");
    }
    if (match(TOKEN_IDENTIFIER)) {
        const char* name = tokens[current_token - 1].value;
        if (peek().type == TOKEN_LPAREN) {
            return parse_call(name);
        }
        for (int i = 0; i < var_count; i++) {
            if (strcmp(vars[i].name, name) == 0) {
                return vars[i].num_value;
            }
        }
        error("Undefined variable: %s", name);
    }
    if (match(TOKEN_LPAREN)) {
        double val = evaluate();
        consume(TOKEN_RPAREN, "Expected ')'");
        return val;
    }
    error("Expected expression (got '%s')", peek().value);
    return 0;
}

double parse_unary() {
    if (match(TOKEN_NOT)) {
        return parse_unary() == 0 ? 1 : 0;
    }
    if (match(TOKEN_MINUS)) {
        return -parse_unary();
    }
    return parse_primary();
}

double parse_factor() {
    double left = parse_unary();
    while (match(TOKEN_MULTIPLY) || match(TOKEN_DIVIDE) || match(TOKEN_MODULO)) {
        TokenType op = tokens[current_token - 1].type;
        double right = parse_unary();
        if (op == TOKEN_MULTIPLY) left *= right;
        else if (op == TOKEN_DIVIDE) {
            if (right == 0) error("Division by zero");
            left /= right;
        } else {
            if (right == 0) error("Modulo by zero");
            left = fmod(left, right);
        }
    }
    return left;
}

double parse_term() {
    double left = parse_factor();
    while (match(TOKEN_PLUS) || match(TOKEN_MINUS)) {
        TokenType op = tokens[current_token - 1].type;
        double right = parse_factor();
        if (op == TOKEN_PLUS) left += right;
        else left -= right;
    }
    return left;
}

double parse_comparison() {
    double left = parse_term();
    while (1) {
        if (match(TOKEN_EQUAL)) {
            double right = parse_term();
            left = (left == right) ? 1 : 0;
        } else if (match(TOKEN_NOT_EQUAL)) {
            double right = parse_term();
            left = (left != right) ? 1 : 0;
        } else if (match(TOKEN_GREATER)) {
            double right = parse_term();
            left = (left > right) ? 1 : 0;
        } else if (match(TOKEN_LESS)) {
            double right = parse_term();
            left = (left < right) ? 1 : 0;
        } else if (match(TOKEN_GREATER_EQUAL)) {
            double right = parse_term();
            left = (left >= right) ? 1 : 0;
        } else if (match(TOKEN_LESS_EQUAL)) {
            double right = parse_term();
            left = (left <= right) ? 1 : 0;
        } else {
            break;
        }
    }
    return left;
}

double parse_logic_and() {
    double left = parse_comparison();
    while (match(TOKEN_AND)) {
        double right = parse_comparison();
        left = (left != 0 && right != 0) ? 1 : 0;
    }
    return left;
}

double parse_logic_or() {
    double left = parse_logic_and();
    while (match(TOKEN_OR)) {
        double right = parse_logic_and();
        left = (left != 0 || right != 0) ? 1 : 0;
    }
    return left;
}

double evaluate() {
    return parse_logic_or();
}

void execute_input() {
    consume(TOKEN_LPAREN, "Expected '(' after input");
    const char* prompt = "";
    
    if (match(TOKEN_STRING)) {
        prompt = tokens[current_token - 1].value;
    }
    consume(TOKEN_RPAREN, "Expected ')'");
    
    printf("%s", prompt);
    fflush(stdout);
    
    char input[MAX_STRING];
    if (fgets(input, MAX_STRING, stdin) == NULL) {
        error("Failed to read input");
    }
    
    input[strcspn(input, "\n")] = '\0';
    
    strncpy(vars[var_count].name, "__input_result", 63);
    strncpy(vars[var_count].str_value, input, MAX_STRING - 1);
    vars[var_count].str_value[MAX_STRING - 1] = '\0';
    vars[var_count].is_string = 1;
    var_count++;
}

void execute_str() {
    consume(TOKEN_LPAREN, "Expected '(' after str");
    double val = evaluate();
    consume(TOKEN_RPAREN, "Expected ')'");
    
    char buf[MAX_STRING];
    sprintf(buf, "%g", val);
    
    strncpy(vars[var_count].name, "__str_result", 63);
    strncpy(vars[var_count].str_value, buf, MAX_STRING - 1);
    vars[var_count].str_value[MAX_STRING - 1] = '\0';
    vars[var_count].is_string = 1;
    var_count++;
}

// Execute print statement
void execute_print() {
    consume(TOKEN_LPAREN, "Expected '(' after print");
    int first = 1;
    int newline = print_newline;

    while (!match(TOKEN_RPAREN)) {
        if (!first) consume(TOKEN_COMMA, "Expected ',' between arguments");

        if (match(TOKEN_STRING)) {
            const char* str = tokens[current_token - 1].value;
            if (strcmp(str, "nel") == 0) {
                newline = 0;
                first = 0;
                continue;
            }
            if (!first) printf(" ");
            printf("%s", str);
        } else if (match(TOKEN_NUMBER)) {
            if (!first) printf(" ");
            printf("%s", tokens[current_token - 1].value);
        } else if (match(TOKEN_IDENTIFIER)) {
            const char* name = tokens[current_token - 1].value;
            if (peek().type == TOKEN_PLUS || peek().type == TOKEN_MINUS || 
                peek().type == TOKEN_MULTIPLY || peek().type == TOKEN_DIVIDE ||
                peek().type == TOKEN_MODULO) {
                double val = atof(tokens[current_token - 1].value);
                for (int i = 0; i < var_count; i++) {
                    if (strcmp(vars[i].name, name) == 0) {
                        if (!vars[i].is_string) {
                            val = vars[i].num_value;
                        }
                        break;
                    }
                }
                while (peek().type == TOKEN_PLUS || peek().type == TOKEN_MINUS ||
                       peek().type == TOKEN_MULTIPLY || peek().type == TOKEN_DIVIDE ||
                       peek().type == TOKEN_MODULO) {
                    TokenType op = peek().type;
                    advance();
                    double right = evaluate();
                    if (op == TOKEN_PLUS) val += right;
                    else if (op == TOKEN_MINUS) val -= right;
                    else if (op == TOKEN_MULTIPLY) val *= right;
                    else if (op == TOKEN_DIVIDE) val /= right;
                    else if (op == TOKEN_MODULO) val = fmod(val, right);
                }
                if (!first) printf(" ");
                printf("%g", val);
            } else {
                int found = 0;
                for (int i = 0; i < var_count; i++) {
                    if (strcmp(vars[i].name, name) == 0) {
                        if (!first) printf(" ");
                        if (vars[i].is_string) {
                            printf("%s", vars[i].str_value);
                        } else {
                            printf("%g", vars[i].num_value);
                        }
                        found = 1;
                        break;
                    }
                }
                if (!found) error("Undefined variable: %s", name);
            }
        } else {
            error("Unexpected token in print: '%s'", peek().value);
        }
        first = 0;
    }

    if (newline) {
        printf("\n");
    }
    fflush(stdout);
}

// Execute var declaration
void execute_var() {
    consume(TOKEN_IDENTIFIER, "Expected variable name");
    const char* name = tokens[current_token - 1].value;
    consume(TOKEN_ASSIGN, "Expected '=' after variable name");

    if (var_count >= MAX_VARS) {
        error("Too many variables (max %d)", MAX_VARS);
    }

    Variable* v = &vars[var_count];
    strncpy(v->name, name, 63);
    v->name[63] = '\0';

    if (match(TOKEN_STRING)) {
        strncpy(v->str_value, tokens[current_token - 1].value, MAX_STRING - 1);
        v->str_value[MAX_STRING - 1] = '\0';
        v->is_string = 1;
        v->num_value = 0;
    } else {
        v->num_value = evaluate();
        v->is_string = 0;
        v->str_value[0] = '\0';
    }
    var_count++;
    consume(TOKEN_SEMICOLON, "Expected ';' after variable declaration");
}

// Skip block (for else branch)
static void skip_block() {
    int depth = 1;
    while (depth > 0 && peek().type != TOKEN_EOF) {
        Token t = advance();
        if (t.type == TOKEN_LBRACE) depth++;
        if (t.type == TOKEN_RBRACE) depth--;
    }
}

// Execute if statement
void execute_if() {
    consume(TOKEN_LPAREN, "Expected '(' after 'if'");
    double cond = evaluate();
    consume(TOKEN_RPAREN, "Expected ')' after condition");
    consume(TOKEN_LBRACE, "Expected '{' after if condition");

    if (cond != 0) {
        while (!match(TOKEN_RBRACE) && peek().type != TOKEN_EOF) {
            execute_statement();
        }
    } else {
        skip_block();
    }
    
    if (match(TOKEN_ELSE)) {
        consume(TOKEN_LBRACE, "Expected '{' after 'else'");
        if (cond == 0) {
            while (!match(TOKEN_RBRACE) && peek().type != TOKEN_EOF) {
                execute_statement();
            }
        } else {
            skip_block();
        }
    }
}

// Execute while statement
void execute_while() {
    consume(TOKEN_LPAREN, "Expected '(' after 'while'");
    int cond_start = current_token;

    evaluate(); // Parse once to skip condition
    consume(TOKEN_RPAREN, "Expected ')' after condition");
    consume(TOKEN_LBRACE, "Expected '{' after while condition");

    int body_start = current_token;
    skip_block(); // Skip body to find end
    int body_end = current_token;

    while (1) {
        current_token = cond_start;
        current_line = tokens[cond_start].line;
        double cond = evaluate();
        consume(TOKEN_RPAREN, "Expected ')'");
        consume(TOKEN_LBRACE, "Expected '{'");

        if (cond == 0) {
            current_token = body_end;
            break;
        }

        current_token = body_start;
        while (current_token < body_end - 1 && peek().type != TOKEN_EOF) {
            execute_statement();
        }
    }
}

// Execute for statement
void execute_for() {
    consume(TOKEN_LPAREN, "Expected '(' after 'for'");
    
    int init_start = current_token;
    int init_end = current_token;
    if (match(TOKEN_VAR)) {
        while (peek().type != TOKEN_SEMICOLON && peek().type != TOKEN_EOF) {
            advance();
        }
        init_end = current_token;
    } else if (peek().type == TOKEN_IDENTIFIER && tokens[current_token + 1].type == TOKEN_ASSIGN) {
        while (peek().type != TOKEN_SEMICOLON && peek().type != TOKEN_EOF) {
            advance();
        }
        init_end = current_token;
    } else {
        init_end = current_token;
    }
    consume(TOKEN_SEMICOLON, "Expected ';' in for loop");
    
    int cond_start = current_token;
    int cond_end = current_token;
    if (peek().type != TOKEN_SEMICOLON && peek().type != TOKEN_EOF) {
        while (peek().type != TOKEN_SEMICOLON && peek().type != TOKEN_EOF) {
            advance();
        }
        cond_end = current_token;
    } else {
        cond_end = current_token;
    }
    consume(TOKEN_SEMICOLON, "Expected ';' in for loop");
    
    int update_start = current_token;
    int update_end = current_token;
    if (peek().type != TOKEN_RPAREN && peek().type != TOKEN_EOF) {
        while (peek().type != TOKEN_RPAREN && peek().type != TOKEN_EOF) {
            advance();
        }
        update_end = current_token;
    } else {
        update_end = current_token;
    }
    consume(TOKEN_RPAREN, "Expected ')'");
    consume(TOKEN_LBRACE, "Expected '{'");
    
    int body_start = current_token;
    skip_block();
    int body_end = current_token;
    
    if (init_start != init_end) {
        current_token = init_start;
        while (current_token < init_end) {
            execute_statement();
        }
    }
    
    while (1) {
        if (cond_start != cond_end) {
            current_token = cond_start;
            current_line = tokens[cond_start].line;
            double cond = evaluate();
            
            if (cond == 0) {
                current_token = body_end;
                break;
            }
        } else {
            break;
        }
        
        current_token = body_start;
        while (current_token < body_end - 1 && peek().type != TOKEN_EOF) {
            execute_statement();
        }
        
        if (update_start != update_end) {
            in_for_loop_update = 1;
            current_token = update_start;
            while (current_token < update_end) {
                execute_statement();
            }
            in_for_loop_update = 0;
        }
    }
}

extern int in_for_loop_update;

// Execute statement
void execute_statement() {
    Token t = peek();

    switch (t.type) {
        case TOKEN_PRINT:
            advance();
            execute_print();
            consume(TOKEN_SEMICOLON, "Expected ';' after print");
            break;

        case TOKEN_VAR:
            advance();
            execute_var();
            break;

        case TOKEN_IF:
            advance();
            execute_if();
            break;

        case TOKEN_WHILE:
            advance();
            execute_while();
            break;

        case TOKEN_FOR:
            advance();
            execute_for();
            break;

        case TOKEN_IDENTIFIER: {
            advance();
            if (match(TOKEN_ASSIGN)) {
                const char* name = tokens[current_token - 2].value;
                for (int i = 0; i < var_count; i++) {
                    if (strcmp(vars[i].name, name) == 0) {
                        if (match(TOKEN_STRING)) {
                            strncpy(vars[i].str_value, tokens[current_token - 1].value, MAX_STRING - 1);
                            vars[i].str_value[MAX_STRING - 1] = '\0';
                            vars[i].is_string = 1;
                        } else {
                            vars[i].num_value = evaluate();
                            vars[i].is_string = 0;
                        }
                        if (!in_for_loop_update) {
                            consume(TOKEN_SEMICOLON, "Expected ';' after assignment");
                        }
                        return;
                    }
                }
                error("Undefined variable: %s", name);
            } else if (peek().type == TOKEN_LPAREN) {
                const char* name = tokens[current_token - 1].value;
                if (strcmp(name, "input") == 0) {
                    execute_input();
                    consume(TOKEN_SEMICOLON, "Expected ';' after input");
                    return;
                } else if (strcmp(name, "str") == 0) {
                    execute_str();
                    consume(TOKEN_SEMICOLON, "Expected ';' after str");
                    return;
                }
            }
            error("Unexpected identifier: %s", tokens[current_token - 1].value);
            break;
        }

        case TOKEN_EOF:
            break;

        default:
            error("Unexpected token: %s", t.value);
    }
}

// Parse sg<...> config at start of file
void parse_config(const char* source) {
    print_newline = 1;
    const char* p = source;

    while (*p) {
        if (*p == ' ' || *p == '\t' || *p == '\r') {
            p++;
            continue;
        }
        if (*p == '\n') break;
        if (*p == '#') {
            while (*p && *p != '\n') p++;
            continue;
        }
        if (*p == 's' && *(p+1) == 'g' && *(p+2) == '<') {
            p += 3;
            while (*p && *p != '>') {
                if (strncmp(p, "nel", 3) == 0) {
                    print_newline = 0;
                    break;
                }
                p++;
            }
            break;
        }
        break;
    }
}

// Strip config line from source
char* strip_config(const char* source) {
    const char* p = source;

    while (*p) {
        if (*p == ' ' || *p == '\t' || *p == '\r') {
            p++;
            continue;
        }
        if (*p == '\n') {
            return strdup(source);
        }
        if (*p == '#') {
            while (*p && *p != '\n') p++;
            if (*p == '\n') p++;
            continue;
        }
        if (*p == 's' && *(p+1) == 'g' && *(p+2) == '<') {
            const char* start = p;
            while (*p && *p != '\n') p++;
            if (*p == '\n') p++;

            size_t prefix_len = start - source;
            size_t suffix_len = strlen(p);
            char* result = malloc(prefix_len + suffix_len + 1);
            if (!result) error("Out of memory");

            memcpy(result, source, prefix_len);
            memcpy(result + prefix_len, p, suffix_len + 1);
            return result;
        }
        return strdup(source);
    }
    return strdup(source);
}

void run(const char* source) {
    static int rand_seeded = 0;
    if (!rand_seeded) {
        srand(time(NULL));
        rand_seeded = 1;
    }
    
    parse_config(source);
    char* clean_source = strip_config(source);
    tokenize(clean_source);
    current_token = 0;

    while (peek().type != TOKEN_EOF) {
        execute_statement();
    }

    free(clean_source);
}

void run_file(const char* path) {
    FILE* f = fopen(path, "r");
    if (!f) {
        error("Cannot open file: %s", path);
    }

    fseek(f, 0, SEEK_END);
    long size = ftell(f);
    if (size < 0) {
        fclose(f);
        error("Cannot read file: %s", path);
    }
    fseek(f, 0, SEEK_SET);

    char* source = malloc(size + 1);
    if (!source) {
        fclose(f);
        error("Out of memory");
    }

    size_t read = fread(source, 1, size, f);
    fclose(f);
    source[read] = '\0';

    run(source);
    free(source);
}

// Update functionality
#define VERSION_URL "https://oraset.parlz.com/download/version.txt"
#define DOWNLOAD_BASE "https://oraset.parlz.com/download"

static char* http_get(const char* url) {
#ifdef _WIN32
    HINTERNET hInternet = InternetOpenA("Oraset", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
    if (!hInternet) return NULL;
    
    HINTERNET hUrl = InternetOpenUrlA(hInternet, url, NULL, 0, INTERNET_FLAG_RELOAD, 0);
    if (!hUrl) {
        InternetCloseHandle(hInternet);
        return NULL;
    }
    
    char* buffer = malloc(4096);
    if (!buffer) {
        InternetCloseHandle(hUrl);
        InternetCloseHandle(hInternet);
        return NULL;
    }
    
    DWORD total_read = 0;
    DWORD bytes_read;
    char temp[1024];
    
    while (InternetReadFile(hUrl, temp, sizeof(temp), &bytes_read) && bytes_read > 0) {
        if (total_read + bytes_read >= 4095) {
            char* new_buf = realloc(buffer, total_read + bytes_read + 4096);
            if (!new_buf) {
                free(buffer);
                InternetCloseHandle(hUrl);
                InternetCloseHandle(hInternet);
                return NULL;
            }
            buffer = new_buf;
        }
        memcpy(buffer + total_read, temp, bytes_read);
        total_read += bytes_read;
    }
    buffer[total_read] = '\0';
    
    InternetCloseHandle(hUrl);
    InternetCloseHandle(hInternet);
    return buffer;
#else
    char cmd[512];
    snprintf(cmd, sizeof(cmd), "curl -s \"%s\" 2>/dev/null", url);
    FILE* fp = popen(cmd, "r");
    if (!fp) return NULL;
    
    char* buffer = malloc(4096);
    if (!buffer) {
        pclose(fp);
        return NULL;
    }
    
    size_t total_read = 0;
    size_t bytes_read;
    char temp[1024];
    
    while ((bytes_read = fread(temp, 1, sizeof(temp), fp)) > 0) {
        if (total_read + bytes_read >= 4095) {
            char* new_buf = realloc(buffer, total_read + bytes_read + 4096);
            if (!new_buf) {
                free(buffer);
                pclose(fp);
                return NULL;
            }
            buffer = new_buf;
        }
        memcpy(buffer + total_read, temp, bytes_read);
        total_read += bytes_read;
    }
    buffer[total_read] = '\0';
    pclose(fp);
    return buffer;
#endif
}

static int download_file(const char* url, const char* dest_path) {
#ifdef _WIN32
    HINTERNET hInternet = InternetOpenA("Oraset", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
    if (!hInternet) return -1;
    
    HINTERNET hUrl = InternetOpenUrlA(hInternet, url, NULL, 0, INTERNET_FLAG_RELOAD, 0);
    if (!hUrl) {
        InternetCloseHandle(hInternet);
        return -1;
    }
    
    FILE* fp = fopen(dest_path, "wb");
    if (!fp) {
        InternetCloseHandle(hUrl);
        InternetCloseHandle(hInternet);
        return -1;
    }
    
    char temp[4096];
    DWORD bytes_read;
    
    while (InternetReadFile(hUrl, temp, sizeof(temp), &bytes_read) && bytes_read > 0) {
        fwrite(temp, 1, bytes_read, fp);
    }
    
    fclose(fp);
    InternetCloseHandle(hUrl);
    InternetCloseHandle(hInternet);
    return 0;
#else
    char cmd[1024];
    snprintf(cmd, sizeof(cmd), "curl -L -o \"%s\" \"%s\" 2>/dev/null", dest_path, url);
    return system(cmd);
#endif
}

static void get_system_info(char* os, char* ext) {
#ifdef _WIN32
    strcpy(os, "windows");
    strcpy(ext, ".exe");
#elif defined(__APPLE__)
    strcpy(os, "macos");
    strcpy(ext, ".pkg");
#elif defined(__linux__)
    strcpy(os, "linux");
    strcpy(ext, ".tar.gz");
#else
    strcpy(os, "unknown");
    strcpy(ext, ".tar.gz");
#endif
}

static int compare_versions(const char* v1, const char* v2) {
    int major1, minor1, patch1, major2, minor2, patch2;
    char suffix1[64] = "", suffix2[64] = "";
    
    sscanf(v1, "%d.%d.%d-%63s", &major1, &minor1, &patch1, suffix1);
    sscanf(v2, "%d.%d.%d-%63s", &major2, &minor2, &patch2, suffix2);
    
    if (major1 != major2) return major1 - major2;
    if (minor1 != minor2) return minor1 - minor2;
    if (patch1 != patch2) return patch1 - patch2;
    
    // Release > Beta > Alpha
    int s1 = (strstr(suffix1, "Release") || strlen(suffix1) == 0) ? 3 : 
             (strstr(suffix1, "Beta") ? 2 : 1);
    int s2 = (strstr(suffix2, "Release") || strlen(suffix2) == 0) ? 3 : 
             (strstr(suffix2, "Beta") ? 2 : 1);
    return s1 - s2;
}

static void trim_newline(char* str) {
    int len = strlen(str);
    while (len > 0 && (str[len-1] == '\n' || str[len-1] == '\r')) {
        str[--len] = '\0';
    }
}

int update_oraset(const char* target_version) {
    printf("Checking for updates...\n");
    
    // Get latest version
    char* version_info = http_get(VERSION_URL);
    if (!version_info) {
        fprintf(stderr, "Error: Cannot fetch version information.\n");
        fprintf(stderr, "Please check your internet connection.\n");
        return 1;
    }
    
    trim_newline(version_info);
    char latest_version[128];
    strncpy(latest_version, version_info, sizeof(latest_version) - 1);
    free(version_info);
    
    printf("Current version: %s\n", VERSION);
    printf("Latest version: %s\n", latest_version);
    
    const char* version_to_install = target_version ? target_version : latest_version;
    
    if (target_version) {
        printf("Target version specified: %s\n", version_to_install);
    }
    
    // Get system info
    char os[32], ext[16];
    get_system_info(os, ext);
    printf("Detected OS: %s\n", os);
    
    // Build download URL
    char download_url[512];
    char filename[128];
    
    if (strcmp(os, "windows") == 0) {
        snprintf(filename, sizeof(filename), "Oraset-Re+%s%s", version_to_install, ext);
        snprintf(download_url, sizeof(download_url), "%s/exe/%s", DOWNLOAD_BASE, filename);
    } else if (strcmp(os, "macos") == 0) {
        snprintf(filename, sizeof(filename), "Oraset-Re+%s%s", version_to_install, ext);
        snprintf(download_url, sizeof(download_url), "%s/pkg/%s", DOWNLOAD_BASE, filename);
    } else {
        snprintf(filename, sizeof(filename), "Oraset-Re+%s%s", version_to_install, ext);
        snprintf(download_url, sizeof(download_url), "%s/deb/%s", DOWNLOAD_BASE, filename);
    }
    
    printf("Downloading: %s\n", download_url);
    
    // Download to temp directory
    char temp_path[512];
#ifdef _WIN32
    char temp_dir[MAX_PATH];
    GetTempPathA(MAX_PATH, temp_dir);
    snprintf(temp_path, sizeof(temp_path), "%s%s", temp_dir, filename);
#else
    snprintf(temp_path, sizeof(temp_path), "/tmp/%s", filename);
#endif
    
    if (download_file(download_url, temp_path) != 0) {
        fprintf(stderr, "Error: Failed to download update.\n");
        return 1;
    }
    
    printf("Downloaded to: %s\n", temp_path);
    
    // Install based on OS
#ifdef _WIN32
    printf("Please run the installer: %s\n", temp_path);
#else
    if (strcmp(os, "macos") == 0) {
        printf("Installing package...\n");
        char cmd[1024];
        snprintf(cmd, sizeof(cmd), "sudo installer -pkg \"%s\" -target /", temp_path);
        system(cmd);
    } else if (strcmp(os, "linux") == 0) {
        printf("Extracting...\n");
        char cmd[1024];
        snprintf(cmd, sizeof(cmd), "cd /tmp && tar -xzf \"%s\" && sudo cp oraset /usr/local/bin/", temp_path);
        system(cmd);
    }
    printf("Installation complete!\n");
#endif
    
    return 0;
}

int main(int argc, char** argv) {
    if (argc == 1) {
        printf("Oraset Re+%s\n", VERSION);
        printf("Usage: oraset [options] <script>\n");
        printf("Options:\n");
        printf("  -v, --version   Show version information\n");
        printf("  -u [version]    Update to latest or specified version\n");
        printf("  <script.ora>    Run an Oraset script file\n");
        return 0;
    }

    if (argc == 2) {
        if (strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "--version") == 0) {
            printf("Oraset Re+%s\n", VERSION);
            printf("A simple interpreted programming language\n");
            return 0;
        }
        if (strcmp(argv[1], "-u") == 0) {
            return update_oraset(NULL);
        }
        run_file(argv[1]);
        return 0;
    }

    if (argc >= 3 && strcmp(argv[1], "-u") == 0) {
        return update_oraset(argv[2]);
    }

    printf("Oraset Re+%s\n", VERSION);
    printf("Usage: oraset [options] <script>\n");
    printf("Options:\n");
    printf("  -v, --version   Show version information\n");
    printf("  -u [version]    Update to latest or specified version\n");
    printf("  <script.ora>    Run an Oraset script file\n");
    return 1;
}
