/**********************************************/
/*                                            */
/*   改行コ−ド変換プログラム (LF to CRLF)    */
/*                                            */
/*      coded by A.Kobayashi 2003.2.22        */
/*                                            */
/**********************************************/
/*
	cc f2rf.c -o f2rf
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

main(int argc, char *argv[])
{
	int c,c2;
	char f,*p,*fname;
	FILE *fp;

	f = 'w';
	fname = NULL;
	while (argc >= 2) {
		p = argv[1];
		if (*p++ == '-') {
			f = *p;
			if ((f == 'w') || (f == 'u') || (f == 'm')) ;
			else {
				fprintf(stderr,"usage: f2rf [-[h|w|u|m]] [in_file|<in_file] [>out_file]\n");
				exit(1);
			}
		}
		else {
			if (fname) {
				fprintf(stderr,"too file [%s] !!\n",fname);
				exit(1);
			}
			fname = argv[1];
		}
		argc--;
		argv++;
	}

	if (fname) {
		if (!(fp=fopen(fname,"r"))) {
			fprintf(stderr,"file [%s] open error!!\n",fname);
			exit(1);
		}
	}
	else fp = stdin;

	while ((c=getc(fp))!=EOF) {
		if (f == 'w') {		/* change to '\r\n' */
			if (c == '\r') {
				putchar(c);
				if ((c=getc(fp)) == '\n') putchar(c);
				else {
					putchar('\n');
					ungetc(c,fp);
				}
			}
			else if (c == '\n') {
				putchar('\r');
				putchar(c);
			}
			else  putchar(c);
		}
		else if (f == 'u') {	/* change to '\n' */
			if (c == '\r') {
				if ((c=getc(fp)) == '\n') putchar(c);
				else {
					putchar('\n');
					ungetc(c,fp);
				}
			}
			else  putchar(c);
		}
		else if (f == 'm') {	/* change to '\r' */
			if (c == '\r') {
				if ((c=getc(fp)) == '\n') putchar('\r');
				else {
					putchar('\r');
					ungetc(c,fp);
				}
			}
			else if (c == '\n') putchar('\r');
			else  putchar(c);
		}
	}
	exit(0);
}
