/*
unix2dos: Converts UNIX linebreaks to MS-DOS/MS-Windows linebreaks.
Anders Brander <anders@brander.dk>
2001-12-09
*/

#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

#define POOLSIZE 64*1024

void bail(char *);

int
main(int argc, char **argv)
{
	int inf=STDIN_FILENO, outf=STDOUT_FILENO;

	if (argc>1)
		inf = open(argv[1], O_NONBLOCK | O_RDONLY);
			if (inf==-1)
				bail("Cannot open input file\n");

	if (argc>2)
		outf = open(argv[2], O_CREAT | O_WRONLY | S_IRUSR | S_IWUSR);
			if (outf==-1)
				bail("Cannot open output file\n");

/* Yearh, i know, it's a mess - but it's damned fast :-) */
	{
		int poolpos, pooloffset, poolsize;
		char pool[POOLSIZE];
		while(poolsize = read(inf, &pool, POOLSIZE))
		{
			pooloffset = poolpos = 0;
			for(poolpos=0; poolpos<poolsize; ++poolpos)
				switch(pool[poolpos])		/* Yep, it IS faster than if() */
				{
					case '\r':
						write(outf, &pool[pooloffset], poolpos-pooloffset);
						pooloffset = poolpos+1;
					break;
				}
			write(outf, &pool[pooloffset], poolpos-pooloffset);
		}
	}

	close(inf);
	close(outf);
	return(EXIT_SUCCESS);
}

void
bail(char *text)
{
	write(STDERR_FILENO, text, strlen(text));
	exit(EXIT_FAILURE);
}

