aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
blob: b2a61ece23d842fd795b75882cef41a66faf7d7a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "globals.h"

bool restricted = false;

/*** utility functions ***/

void quit_handler(struct player_t *player)
{
    (void) player;
    exit(EXIT_SUCCESS);
}

void quicksave_handler(struct player_t *player)
{
    if(restricted)
    {
        output("Saving forbidden in restricted mode.\n");
        return;
    }

    if(!player->filename)
    {
        save_handler(player);
        return;
    }

    output("Saving to '%s'.\n", player->filename);

    save_portfolio(player, player->filename);
}

int main(int argc, char *argv[])
{
    curl_global_init(CURL_GLOBAL_DEFAULT);

    struct player_t *player = malloc(sizeof(struct player_t));
    memset(player, 0, sizeof(struct player_t));

    char *save_file;
    char **save_file_p = &save_file;

    uint args_status = parse_args(argc, argv, save_file_p);

    if(args_status & ARG_FAILURE)
        return EXIT_FAILURE;

    if(!(args_status & ARG_NOCURSES) && !(args_status & ARG_BATCHMODE))
        curses_init();

    if(args_status & ARG_BATCHMODE)
        batch_init();

    atexit(cleanup);

    const struct sigaction handler = {
        .sa_handler = sig_handler
    };

    sigaction(SIGINT, &handler, NULL);

    heading("Market Simulator " PROGRAM_VERSION);

    if(args_status & ARG_RESTRICTED)
        restricted = true;

    if(args_status & ARG_HTML)
        html_out = true;

    if(args_status & ARG_LOADED)
    {
        /* save_file must be allocated with malloc(), make it so */
        char *filename = malloc(strlen(save_file) + 1);
        strcpy(filename, save_file);

        load_portfolio(player, filename);
    }
    else
        player->cash.cents = 1000 * 100;

    if(args_status & ARG_VERBOSE)
    {
        output("Verbose operation enabled.\n");
    }

    while(1)
    {
        const struct command_t commands[] = {
            { "[B]uy", "buy", buy_handler },
            { "[S]ell", "sell", sell_handler },
            { "[P]rint portfolio", "print", print_handler },
            { "[U]pdate stock prices", "update", update_handler },
            { "Stock [i]nfo", "info", info_handler },
            { "[L]oad portfolio from disk", "load", load_handler },
            { "[W]rite portfolio to disk", "write", save_handler },
            { "[Q]uick save", "quicksave", quicksave_handler },
            { "[E]xit", "exit", quit_handler },
        };

        do_menu(player, commands, ARRAYLEN(commands),
                "What would you like to do? ");
    }
}