#! /usr/bin/python
"""
#+
# NAME:
#	splat
# PURPOSE:
#	Converts ascii files between Unix and DOS format.
# CALLING SEQUENCE:
#	splat.py file_name
# INPUTS:
#	file_name	name of ascii file or directory name
#			If a directory is specified all files in
#			the directory are converted.
# PROCEDURE:
#	The script will overwrite the input file
# MODIFICATION HISTORY:
#	MAY-2002, Paul Hick (UCSD/CASS)
#	APR-2005, Paul Hick (UCSD/CASS; pphick@ucsd.edu)
#		Removed dependence on 'string' module.
#		Files are now only overwritten if contents changes.
#-
"""
import sys, os
import tiny

if __name__ == '__main__':

	args = tiny.args( sys.argv)
	cr2nl = tiny.is_there('-cr2nl',sys.argv)

	narg = len(args)-1

	if narg != 1:
		file = raw_input('File or directory : ')
	else:
		file = args[1]

	if os.path.isdir(file):
		files = os.listdir(file)

		for i in range( len(files) ):
			files[i] = os.path.join(file,files[i])

	else:
		if not os.path.exists(file):
			print 'file does not exist, ',file
			sys.exit()

		files = [file]


	for file in files:

		if os.path.isfile(file):

			print file

			old_lines = (open(file, 'r')).read()

			lines = old_lines.split('\n')
			nline = len(lines)

			for n in range(nline):

				line = lines[n]

				if len(line) > 0:
					if line[-1] == '\r':
						line = line[0:-1]

				lines[n] = line

			lines = ('\n').join(lines)

			# Check for isolated carriage returns; remove them if present
			# Not sure yet whether this works on Windows

			if sys.platform != 'win32':
				n = lines.count('\r')
				if n != 0:
					print n, ' isolated CRs'
					if cr2nl:
						join_char = '\n'
					else:
						join_char = ''
					lines = join_char.join( lines.split('\r') )

			if lines != old_lines:			# Overwrite the input file
				(open(file, 'w')).write(lines)

	print 'done'
