/*
 * crt0.c
 *
 * Copyright (C) 2017 Aleksandar Andrejevic <theflash@sdf.lonestar.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <stdlib.h>
#include <string.h>
#include <monolithium.h>

int __crt_initialize_heap(void);
int __crt_initialize_files(process_params_t *params);
int main(int argc, char **argv);

void process_startup(process_params_t *params)
{
    int argc = 1;
    char *ptr;
    int space = 1;

    if (__crt_initialize_heap() < 0) syscall_terminate(INVALID_HANDLE, 255);
    if (__crt_initialize_files(params) < 0) syscall_terminate(INVALID_HANDLE, 255);

    for (ptr = params->command_line; *ptr; ptr++)
    {
        if (space != (isspace(*ptr) != 0))
        {
            argc++;
            space = !space;
        }
    }

    char **argv = (char**)__builtin_alloca(argc * sizeof(char*));
    argc = 0;

    for (ptr = strtok(params->command_line, " \t\r\n\v\f"); ptr != NULL; ptr = strtok(NULL, " \t\r\n\v\f"))
    {
        if (*ptr) argv[argc++] = ptr;
    }

    argv[argc] = NULL;

    int exit_code = main(argc, argv);
    exit(exit_code);
}
