/*
 *----------------------------------------------------------------------
 *           "THE BEER-WARE LICENSE" (Revision 42):
 * <jeang3nie@HitchHiker-Linux.org> wrote this file. As long as you
 * retain this notice you can do whatever you want with this stuff. If
 * we meet some day, and you think this stuff is worth it, you can buy
 * me a beer in return.
 * ---------------------------------------------------------------------
 *            ______   _______  _          _________
 *           (  __  \ (  ___  )( (    /|( )\__   __/
 *           | (  \  )| (   ) ||  \  ( ||/    ) (
 *           | |   ) || |   | ||   \ | |      | |
 *           | |   | || |   | || (\ \) |      | |
 *           | |   ) || |   | || | \   |      | |
 *           | (__/  )| (___) || )  \  |      | |
 *           (______/ (_______)|/    )_)      )_(
 *
 *         _______  _______  _       _________ _______
 *        (  ____ )(  ___  )( \    /|\__   __/(  ____ \
 *        | (    )|| (   ) ||  \  ( |   ) (   | (    |/
 *        | (____)|| (___) ||   \ | |   | |   | |
 *        |  _____)|  ___  || (\ \) |   | |   | |
 *        | (      | (   ) || | \   |   | |   | |
 *        | )      | )   ( || )  \  |___) (___| (____|\
 *        |/       |/     \||/    \_)\_______/(_______/
 *
 */

#define _GNU_SOURCE // getline, getopt

#include <ctype.h>    // isascii
#include <inttypes.h> // uint*_t
#include <libgen.h>   // basename
#include <stdio.h>    // fclose, fopen, getline, perror, printf
#include <stdlib.h>   // exit
#include <string.h>   // strcmp
#include <unistd.h>   // getopt

static const char *__progname;
uint32_t ln = 1;

static void usage() {
  fprintf(stderr, "Usage: %s [-h] [FILE1]... [FILE2]...\n", __progname);
}

int rev(char *file) {
  FILE *fp;
  char *line = NULL;
  size_t len = 0;
  ssize_t nread;
  // Open file
  if (strcmp(file, "-") != 0) {
    fp = fopen(file, "r");
    if (fp == NULL) {
      perror("fopen");
      exit(EXIT_FAILURE);
    }
  } else {
    fp = stdin;
  }

  // Read contents from file
  while ((nread = getline(&line, &len, fp)) != -1) {
    int i, u8c;
    for (i = nread - 2; i >= 0; i--) {
      if ((line[i] & 0xC0) == 0x80) {
        continue;
      } else {
        putchar(line[i]);
        u8c = i + 1;
        while ((line[u8c] & 0xC0) == 0x80) {
          putchar(line[u8c]);
          u8c++;
        }
      }
    }
    putchar('\n');
  }
  if (strcmp(file, "-") != 0)
    fclose(fp);
  free(line);
  return 0;
}

int main(int argc, char *argv[]) {
  int c, index;
  __progname = basename(argv[0]);
  while ((c = getopt(argc, argv, "fh")) != -1)
    switch (c) {
    case 'h':
      usage();
      exit(EXIT_SUCCESS);
    default:
      usage();
      exit(EXIT_FAILURE);
    }

  if (argv[optind] == NULL)
    rev("-");

  for (index = optind; index < argc; index++)
    rev(argv[index]);
  return 0;
}
