#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <errno.h>

void printLinePair(const char *line)
{
    size_t size = 0;
    while (line[size] != ' ' && line[size] != '\0') {
        size++;
    }

    if (size > 0) {
        fwrite(line, sizeof(char), size, stdout);
    }

    printf(" : ");

    line += size;
    size = 0;

    while (*line == ' ' && *line != '\0') {
        line++;
    }

    while (line[size] != ' ' && line[size] != '\0') {
        size++;
    }

    if (size > 0) {
        fwrite(line, sizeof(char), size, stdout);
    }

    printf("\n");
}

#define BUFFER_SIZE 6
int main()
{
    static char buffer[BUFFER_SIZE] = { 0 };
    static size_t bufIdx = 0;
    static size_t readBytes = 0;
    int ret = EXIT_SUCCESS;
    char *lineBuffer = NULL;
    char *lineBufPtr = lineBuffer;
    size_t lineBufferSize = 0;
    size_t lineBufferCapacity = BUFFER_SIZE + 1;
    size_t newLineBufferCapacity = 0;
    FILE *file = stdin; // fopen("1.txt", "r");  // <========= FILE HERE

    if (!file) {
        printf("Couldn't open file: %d\n", errno);
        ret = EXIT_FAILURE;
        goto fail_open_file;
    }

    lineBuffer = malloc(lineBufferCapacity);
    if (!lineBuffer) {
        printf("Couldn't allocate the line buffer.");
        ret = EXIT_FAILURE;
        goto fail_allocate_line_buffer;
    }

    while ((readBytes = fread(buffer, sizeof(char), BUFFER_SIZE, file))) {
        if (lineBufferCapacity - lineBufferSize < readBytes + 1) {
            newLineBufferCapacity = lineBufferCapacity * 2;
            lineBufPtr = realloc(lineBuffer, newLineBufferCapacity);
            if (!lineBufPtr) {
                printf("Couldn't realloc the line buffer (%zu to %zu bytes).\n",
                       lineBufferCapacity, newLineBufferCapacity);
                ret = EXIT_FAILURE;
                goto fail_realloc_line_buf;
            } else {
                lineBuffer = lineBufPtr;
                lineBufferCapacity = newLineBufferCapacity;
            }
        }

        while (bufIdx < readBytes && buffer[bufIdx] != '\0') {
            while (bufIdx < readBytes && buffer[bufIdx] != '\n' && buffer[bufIdx] != '\0') {
                lineBuffer[lineBufferSize++] = buffer[bufIdx++];
            }

            if (bufIdx < readBytes && buffer[bufIdx] != '\0') {
                lineBuffer[lineBufferSize++] = '\0';
                printLinePair(lineBuffer);
                lineBufferSize = 0;
                lineBuffer[0] = '\0';
                bufIdx++;
            }
        }

        bufIdx = 0;
    }

    if (lineBufferSize > 0) {
        lineBuffer[lineBufferSize++] = '\0';
        printLinePair(lineBuffer);
    }

fail_realloc_line_buf:
    free(lineBuffer);
fail_allocate_line_buffer:
    fclose(file);
fail_open_file:
    return ret;
}
