/*
 * Soubor:  20110211-Fri-mytee.c
 * Datum:   11.02.2011
 * Autor:   Marek Nožka, nozka <@t> spseol <d.t> cz
 * Licence: GNU/GPL 
 * Úloha: 
 * Popis:   
 */

#define _ISOC99_SOURCE
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdbool.h>
#include <limits.h>
#include <math.h>
#include <unistd.h>

/**
 * Vytiskne na stdout text s nápovědou.
 */
void printHelp()
{
    printf("Program mytee bere stdin a vypisuje na stdout.\n\n"
           " mytee [-a] <soubor>\n\n"
           "-a   <soubor> se nepřepisuje ale stream"
           "     se zařadí na konec\n\n"
           "-h   vypíše tento help\n\n");
}

/////////////////////////////////////////////////////
/**
 * Hlavní program.
 */
int main(int argc, char *argv[])
{
    char mode[]="w"; // mode pro fopen
    FILE *fout; 
    int stream;
    /* 
     * Zpracování parametrů příkazového řádku 
     */
    int c;
    while ((c = getopt(argc, argv, ":ah")) != -1) {
        switch (c) {
        case 'h':
            printHelp();
            return 0;
            break;
        case 'a':
            sprintf(mode,"%s","a"); // mode pro fopen
            break;
        case '?':
            printf("neplatná volba: %c\n", optopt);
            break;
        }
    }

    /* patametry, které nejsou přepínači */
    //printf("%d %d\n",optind,argc);
    if ( optind < argc ) {
        fout = fopen(argv[optind],mode);
        while ( (stream=getchar()) != EOF) {
            putchar(stream);
            fputc(stream,fout);
        }
        fclose(fout);
        return 0;
    } else {
        fprintf(stderr,"ERROR: zadej vystupni soubor\n");
        printHelp();
        return 1;
    }

}

