#! /usr/local/bin/python

import sys
import os

def usage ():
	print 'frob.py file1 [file2]'
	sys.exit()

if len(sys.argv) < 2:
	usage()
	
fin = open(sys.argv[1], 'r')

if len(sys.argv) == 2:
	outname = 'tmp.'+str(os.getpid())
else:
	outname = sys.argv[2]

fout = open(outname, 'w')

# dir == 1 dos->unix, dir == 2 unix->dos
dir = 0

while 1:
	line = fin.readline()
	if line == '':
		break
	if dir == 0:
		if len(line) > 1 and line[-2:]=='\r\n':
			dir = 1
			print 'converting dos->unix'
		else:
			dir = 2
			print 'converting unix->dos'
	# dos -> unix
	if dir == 1:
		fout.write (line[:-2]+'\n')
	else:
		fout.write (line[:-1]+'\r\n')

fin.close()
fout.close()

if len(sys.argv) == 2:
	os.unlink (sys.argv[1])
	os.rename (outname, sys.argv[1])
	
