#include <string.h>

#include "cmd_private.h"

void Cbuf_Execute(void)
{
    char line[4096];
    int32_t quotes;
    char *text;
    int32_t i;

    for (;;) {
        if (cbuf_cmd_text.cursize == 0) {
            return;
        }

        /* ORIGINAL_BINARY_BUG: negative values installed by Cmd_Wait_f are
         * decremented rather than clamped or treated as already elapsed. */
        if (cbuf_wait != 0) {
            --cbuf_wait;
            return;
        }

        text = cbuf_cmd_text.data;
        quotes = 0;

        for (i = 0; i < cbuf_cmd_text.cursize; ++i) {
            if (text[i] == '"') {
                ++quotes;
            }

            if ((((quotes & 1) == 0) && (text[i] == ';')) ||
                (text[i] == '\n') || (text[i] == '\r')) {
                break;
            }
        }

        if (i > (int32_t)(sizeof(line) - 2U)) {
            i = (int32_t)(sizeof(line) - 1U);
        }

        memcpy(line, text, (size_t)i);
        line[i] = '\0';

        if (i == cbuf_cmd_text.cursize) {
            cbuf_cmd_text.cursize = 0;
        } else {
            ++i;
            cbuf_cmd_text.cursize -= i;
            /*
             * The original memmove extent is the resulting dword cursize;
             * do not sign-extend corrupt or wrapped state on native64.
             */
            memmove(text, text + i,
                    (size_t)(uint32_t)cbuf_cmd_text.cursize);
        }

        Cmd_ExecuteString(line);
    }
}
