#include <stdint.h>
#include <string.h>

#include "cmd_private.h"

void Cmd_ExecuteString(const char *text)
{
    cmd_function_t **link;
    cmd_function_t *cmd;

    Cmd_TokenizeString(text);
    if (Cmd_Argc() == 0) {
        return;
    }

    link = &cmd_functions;
    for (;;) {
        cmd = *link;
        if (cmd == NULL) {
            break;
        }

        if (Q_stricmp(cmd_argv[0], cmd->name) == 0) {
            *link = cmd->next;
            cmd->next = cmd_functions;
            cmd_functions = cmd;

            if (cmd->handler == NULL) {
                break;
            }

            cmd->handler();
            return;
        }

        link = &cmd->next;
    }

    if (Q_strncmp(text, "pb_", 3) == 0) {
        if (Q_strncmp(text + 3, "sv_", 3) == 0) {
            PB_CallServerSbGlobal(0xe, -1,
                                  (uint32_t)strlen(text) + UINT32_C(1), text);
        }
        return;
    }

    if (Cvar_Command() != 0) {
        return;
    }

    if ((cl_running != NULL) && (cl_running->integer != 0) &&
        (CL_GameCommand() != 0)) {
        return;
    }

    if ((sv_running != NULL) && (sv_running->integer != 0) &&
        (SV_GameConsoleCommand() != 0)) {
        return;
    }

    if ((cl_running != NULL) && (cl_running->integer != 0) &&
        (UI_GameCommand() != 0)) {
        return;
    }

    CL_ForwardCommandToServer(text);
}
