#include <ctype.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/poll.h>

int main(void)
{
    int i, ret;
    unsigned char buf[4096];
    struct pollfd pollfd = {0, POLLIN};

    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);

    while (1) {
        ret = poll(&pollfd, 1, -1);

        if (ret == -1) {
            perror("poll");
            return EXIT_FAILURE;
        } else if (ret == 0) {
            continue;
        } else {
            /* Fall through. */
        }

        ret = read(0, buf, 4096);

        if (ret == -1) {
            perror("read");
            return EXIT_FAILURE;
        } else if (ret == 0) {
            return EXIT_SUCCESS;
        } else {
            /* Fall through. */
        }

        for (i = 0; i < ret; ++i) {
            switch (buf[i]) {
            case 'a' ... 'm': case 'A' ... 'M': buf[i] += 13; break;
            case 'n' ... 'z': case 'N' ... 'Z': buf[i] -= 13; break;
            default:;                  /* Leave buf[i] untouched. */
            }
        }

        ret = write(1, buf, i);

        if (ret == -1) {
            perror("write");
            return EXIT_FAILURE;
        } else if (ret < i) {
            fprintf(stderr, "Failed to flush output buffer. :^(\n");
            return EXIT_FAILURE;
        } else {
            /* Fall through to loop again. */
        }
    }

    return EXIT_SUCCESS;
}

/* vim: set ts=4 sts=4 sw=4 tw=80 et: */

