#include "types.h"
#include "user.h"

int main(int argc, char *argv[]) {    
    int pid;
    int selopt = getpid() % 10;
    int bgcol = 0x4F00;
    char title[20];
    int accepttitle = 0;
    int currenttitlelen = 0;
    
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i],  "-bg") == 0) 
        {
            accepttitle = 0;
            selopt = atoi(argv[i + 1]);            
        }
        else if (strcmp(argv[i], "-t") == 0)
        {
            accepttitle = 1;
        }
        else if (strcmp(argv[i],  "-help") == 0)
        {
            printf(1, "Creates a new virtual console.\n");
            printf(1, "Options:\n");
            printf(1, "-bg [0 - 9] : Sets a background preset for the title bar.\n");
            printf(1, "-t [String] : Sets a custom title for the console.\n");
            exit();
            return 0;
        }
        // Setup the title, it adds the space seperated strings to the title
        else
        {
            if (accepttitle)
            {
                if (currenttitlelen > 0) 
                {
                    title[currenttitlelen] = ' ';
                    currenttitlelen++;
                }

                char *sx;
                for (sx = argv[i]; *sx != '\0'; sx++)
                {
                    title[currenttitlelen] = *sx;
                    currenttitlelen++;
                    if (currenttitlelen >= 20)
                    {
                        accepttitle = 0;
                        break;
                    }
                }                
            }
        }
    }

    // Set the variable to the selected bg/fg preset option
    switch(selopt)
    {
        case 1:
            bgcol = 0x1F00;
            break;
        case 2:
            bgcol = 0x2F00;
            break;
        case 3:
            bgcol = 0x3F00;
            break;
        case 4:
            bgcol = 0x5F00;
            break;
        case 5:
            bgcol = 0xF000;
            break;
        case 6:
            bgcol = 0x8F00;
            break;
        case 7:
            bgcol = 0x9F00;
            break;
        case 8:
            bgcol = 0xAF00;
            break;
        case 9:
            bgcol = 0xCF00;
            break;
    }

    // Fork into a new process and create the screen
    pid = fork();    
    if (pid < 0) {
        printf(1, "screen: fork failed\n");
    }
    if (pid == 0) {
        if (screen(title, bgcol) != 0)
        {   
            exec("sh", argv);                                    
            printf(1, "screen: exec sh failed\n");            
        }
        else
        {
            
        }
    }    
    exit();
} 