/*
 * slowcat.c - enlentece la presentacion de un fichero
 * copyright (c) 2001,2002,2007  dave w capella   Todos los derechos reservados
 *
 * distribuido bajo los terminos de la GNU Public license
 *
 * There is NO WARRANTY, and NO SUPPORT WHATSOEVER.
 *
 * compilacion: make slowcat && mv slowcat $HOME/bin
 * (asumiendo que tiene un directorio personal bin)
 *
 * uso: slowcat [-d usecs] fichero
 * siendo usecs el numero de microsegundos de retraso.
 *
 * feedback welcome. enjoy!
 * ...dave
 *
 *
 * 09/24/07 - modificaciones para incluir nanosleep, brian at landsberger.com
 */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int debug = 0;

int main(int argc, char **argv) {
    int c;
    unsigned long usecs,s;
    FILE *fp;
    char *fnam;
        struct timespec ts;

    if(argc != 2 && argc != 4) {
        fprintf(stderr,"uso: %s [-d usecs] fichero\n",argv[0]);
        exit(1);
    }

    if(argc == 4 ) {
         if( !strncmp(argv[1],"-d",2) ) {
            usecs = strtoul(argv[2],NULL,10);
            if(usecs<=0 || usecs>500000L) {
                usecs = 1;
            }
        }
        if(debug) {
            fprintf(stderr,"usecs: %lu\nCualquier tecla para continuar.\n",usecs);
            c = getchar();
        }
        fnam = argv[3];
    }
    /* set timespec */
    ts.tv_sec=0;
    ts.tv_nsec=usecs;

    if(argc == 2 ) {
        fnam = argv[1];
    }
    fp = fopen(fnam,"r");
    if(fp == NULL) {
        fprintf(stderr,"uso: %s [-d usecs] fichero\n",argv[0]);
        exit(2);
    }

    while( (c = fgetc(fp)) != EOF) {
        putchar(c);
#ifdef _POSIX_C_SOURCE // assuming >= 199309L
        if (debug) {
            fprintf(stderr,"durmiendo usando nanosleep\n");
        }
        nanosleep(&ts,NULL);
#else
        if (debug) {
            fprintf(stderr,"durimiendo usando for\n");
        }
        for(s=0;s<usecs;s++)
            ;
#endif
    }

    fclose(fp);
    return (0);
}