aboutsummaryrefslogtreecommitdiffstats
path: root/src/main.c
blob: 1dbfe4ca21feea2bcf2025c3295e2503ce3a13c0 (plain) (blame)
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
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>

#include "linebuffer.h"
#include "word.h"

#define DEFAULT_LINEBUFFER_CAPACITY 72

void print_usage(const char *prog) {
    fprintf(stderr, "Usage: %s [-w WIDTH]\n", prog);
}

int main(int argc, char *argv[]) {
    int opt;
    size_t linebuffer_capacity = DEFAULT_LINEBUFFER_CAPACITY;

    while ((opt = getopt(argc, argv, "w:h")) != -1) {
        switch (opt) {
            case 'w':
                linebuffer_capacity = (size_t)atoi(optarg);
                if (linebuffer_capacity == 0) {
                    print_usage(argv[0]);
                    return EXIT_FAILURE;
                }
                break;
            case 'h':
            default:
                print_usage(argv[0]);
                return EXIT_FAILURE;
        }
    }

    const size_t MAX_WORD_LENGTH = linebuffer_capacity;
    char word[MAX_WORD_LENGTH + 2];
    size_t word_length;
    int read_word_result;
    LineBuffer *lb = linebuffer_create(linebuffer_capacity);

    while ((read_word_result = read_word(stdin, word, MAX_WORD_LENGTH + 1)) ==
           READ_WORD_SUCCESS) {
        word_length = strlen(word);
        if (word_length == 0) {
            linebuffer_write(lb, stdout);
            linebuffer_destroy(lb);
            return EXIT_SUCCESS;
        }
        if (word_length > MAX_WORD_LENGTH) {
            // TODO: If the word is too long for a given line,
            // we should wrap it to the next line.
            word[MAX_WORD_LENGTH] = '*';
        }
        if (!linebuffer_append_word(lb, word)) {
            linebuffer_write_justified(lb, stdout);
            linebuffer_clear(lb);
            linebuffer_append_word(lb, word);
        }
        memset(word, 0, MAX_WORD_LENGTH + 2);
    }
    if (read_word_result == READ_WORD_ERR_READ) {
        fprintf(stderr, "Error reading word\n");
        return EXIT_FAILURE;
    }
    if (lb->_num_words > 0) {
        linebuffer_write(lb, stdout);
    }
    linebuffer_destroy(lb);
    return EXIT_SUCCESS;
}