#include "cmd_private.h"

void Cmd_TokenizeString2(const char *text, int maxTokens)
{
    char *token;

    cmd_argc = 0;

    if (text == NULL) {
        return;
    }

    token = cmd_tokenBuffer;

    /* ORIGINAL_BINARY_BUG: all three token-copy paths are bounded only by
     * syntax or source NUL, not by the 8,704-byte destination. */
    while (cmd_argc != CODUO_CMD_MAX_ARGS) {
        --maxTokens;
        if (maxTokens == 0) {
            if (*text == '\0') {
                return;
            }

            cmd_argv[cmd_argc] = token;
            ++cmd_argc;

            while (*text != '\0') {
                *token = *text;
                ++text;
                ++token;
            }

            *token = '\0';
            ++token;
            return;
        }

        for (;;) {
            while ((*text != '\0') && ((signed char)*text <= ' ')) {
                ++text;
            }

            if (*text == '\0') {
                return;
            }

            if ((text[0] == '/') && (text[1] == '/')) {
                return;
            }

            if ((text[0] != '/') || (text[1] != '*')) {
                break;
            }

            while ((*text != '\0') &&
                   ((text[0] != '*') || (text[1] != '/'))) {
                ++text;
            }

            if (*text == '\0') {
                return;
            }

            text += 2;
        }

        if (*text == '"') {
            cmd_argv[cmd_argc] = token;
            ++cmd_argc;

            ++text;
            while ((*text != '\0') && (*text != '"')) {
                *token = *text;
                ++text;
                ++token;
            }

            *token = '\0';
            ++token;

            if (*text == '\0') {
                return;
            }

            ++text;
            if (*text == '\0') {
                return;
            }

            if ((signed char)*text <= ' ') {
                ++text;
            }
        } else {
            cmd_argv[cmd_argc] = token;
            ++cmd_argc;

            while (((signed char)*text > ' ') && (*text != '"') &&
                   ((text[0] != '/') || (text[1] != '/')) &&
                   ((text[0] != '/') || (text[1] != '*'))) {
                *token = *text;
                ++text;
                ++token;
            }

            *token = '\0';
            ++token;

            if (*text == '\0') {
                return;
            }

            if ((signed char)*text <= ' ') {
                ++text;
            }
        }
    }
}
