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

int main(int argc, char *argv[])
{
	int c,c2,i,len,sf;
	char cc,f,*p,*fname,*s=NULL,*prg;
	FILE *fp;

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

	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) {
		sf = 1;
		if (f == 'w') {		/* change to '\r\n' */
			if (c == '\r') {
				if ((c=getc(fp)) != '\n') ungetc(c,fp);
			}
			else if (c != '\n') sf = 0;
		}
		else if (f == 'u') {	/* change to '\n' */
			if (c == '\r') {
				if ((c=getc(fp)) != '\n') ungetc(c,fp);
			}
			else sf = 0;
		}
		else if (f == 'm') {	/* change to '\r' */
			if (c == '\r') {
				if ((c=getc(fp)) != '\n') ungetc(c,fp);
			}
			else if (c != '\n') sf = 0;
		}
		if (sf) for (i=0;i<len;i++) putchar(s[i]);
		else putchar(c);
	}
	exit(0);
}
