/*
Slowdown - (C) Richard Whitty 2009

ever yearn for those days when you could actually see the text
scrolling across your terminal? Want to be able to rewatch the old VT100
animations?

Well the wait is over! Emulates any baud speed within reason.
example:
$ slowdown 2400 < inputfile
*/
// needed for usleep()
#define _BSD_SOURCE

#include <stdio.h>
#include <string.h>
#include <unistd.h>

// get rid of the warning for the unused parameter.
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
int main(UNUSED int argc,char** argv) {
	int baud=2400;	// the baud rate to emulate.
	int delay=-1;	// how long to sleep between chars.
	int x=-1;		// current character.
	if(argv[1]) {	// if there's a parameter passed
		if(strncmp("--help",argv[1],6)) {
	// we have a default if it's not valid.
	// no need to check the return value ;)
			sscanf(argv[1],"%d",&baud);
		} else {
			printf("Usage: %s [--help] [baud]\n"
					"--help:\tDisplay this help message\n"
					"baud:\tThe baud rate to emulate\n",*argv);
			return 0;
		}
		if(baud<1||baud>1000000) {
			printf("Bad baud rate: %d\n",baud);
			return 1;
		}
	}
	delay = 1000000/baud;
	while( (x=getchar()) != EOF) {
		if(putchar(x)==EOF) {
			perror("\nwrite character");
			return 1;
		}
		if(fflush(stdout)==EOF) {
			perror("\nflush stream");
			return 1;
		}
		if(usleep(delay)==-1) {
			perror("\nusleep fail");
			return 1;
		}
	}
	return 0;
}

