aboutsummaryrefslogtreecommitdiff
path: root/src/sell.c
blob: 1a04adcc602de684fb7fab7ce329b6f13b4ed889 (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
#include "globals.h"

void sell_handler(struct player_t *player)
{
    char *sym = malloc(16);
    printf("Enter the ticker symbol of the stock you wish to sell: ");
    scanf("%15s", sym);
    all_upper(sym);

    printf("Getting stock information...\n");

    struct stock_t *stock = NULL;
    uint stock_idx;

    for(stock_idx = 0; stock_idx < player->portfolio_len; ++stock_idx)
    {
        if(strcmp(player->portfolio[stock_idx].symbol, sym) == 0)
        {
            stock = player->portfolio + stock_idx;
            break;
        }
    }

    if(!stock)
    {
        printf("Couldn't find '%s' in portfolio.\n", sym);
        return;
    }

    update_handler(player);

    printf("You currently own %llu shares of '%s' (%s) valued at $%llu.%02llu each.\n",
           stock->count, stock->fullname, stock->symbol, stock->current_price.cents / 100, stock->current_price.cents % 100);

    ullong sell = 0;
    printf("How many shares do you wish to sell? ");
    scanf("%llu", &sell);

    if(!sell)
    {
        printf("Sale cancelled.\n");
        return;
    }

    if(stock->count < sell)
    {
        printf("You don't own enough shares!\n");
        return;
    }

    ullong sell_total = stock->current_price.cents * sell;

    printf("This will sell %llu shares for $%llu.%02llu total. Proceed? ", sell, sell_total / 100, sell_total % 100);

    char response[16];
    scanf("%15s", response);
    all_lower(response);

    if(response[0] == 'y')
    {
        stock->count -= sell;

        if(stock->count == 0)
        {
            /* remove this item from the portfolio */
            memmove(player->portfolio + stock_idx, player->portfolio + stock_idx + 1, sizeof(struct stock_t) * (player->portfolio_len - stock_idx - 1));
            player->portfolio_len -= 1;
            player->portfolio = realloc(player->portfolio, sizeof(struct stock_t) * player->portfolio_len);
        }

        player->cash.cents += sell_total;

        printf("%llu shares sold for $%llu.%02llu total.\n", sell, sell_total / 100, sell_total % 100);
    }
    else
    {
        printf("Not confirmed.\n");
    }
}