#!python
# ##############################################################################
# The contents of this file are subject to the PyTis Public License Version		 #
# 1.0 (the "License"); you may not use this file except in compliance with		 #
# the License. You may obtain a copy of the License at												 #
#																																							 #
#	 http://www.PyTis.com/License/																							 #
#																																							 #
#	 Copyright (c) 2009 Josh Lee																								 #
#																																							 #
# Software distributed under the License is distributed on an "AS IS" basis,	 #
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License		 #
# for the specific language governing rights and limitations under the				 #
# License.																																		 #
#																																							 #
# @auto-generated by the PyTis Copyright Tool on 08:05 11 Nov, 2009						 #
############################################################################## #
"""===============================================================================
to80
====

Just like wordwrap it will reformat text to a maximum width, default of 80.

Examples:
	to80 file.txt > new.txt 
		(new.txt is reformatted file.txt with lines up to 80 characters long)

	to80 -w50 file.txt > nex.txt 
		(new.txt is reformatted file.txt with lines up to 50 characters long)

	WARNING! Do not attempt:
		to80 SOMEFILE > SOMEFILE
	This will leave your file EMPTY!
"""

import optparse
import os
import sys

__author__ = 'Josh Lee'
__created__ = '06:38pm 11 Nov, 2009'
__copyright__ = 'PyTis.com'
__version__ = '2.0'

def version():
	print(__version__)

def tolen(instr, i=80):
	""" Reads the input string :instr: and reformatts to an specified length :i:
	"""

	lines = []; line = []
	for word in instr.split(' '):
		
		while len(word) >= 1 and word[0:2] in ("\\n","\n",'\n'):
			lines.append("\n")
			word = word[2:]

		if len('%s %s' % (' '.join(line), word)) > i:
			lines.append(' '.join(line))
			line = [word]
		else:
			if word.startswith('\n'):
				lines.append(' '.join(line))
				line = [word]
			else:
				line.append(word)
	if line:
		lines.append(' '.join(line))
	return '\n'.join(lines)

def run(opts, args):
	""" determins if input is a file, or text, then runs tolen
	"""

	if len(args) == 1 and os.path.isfile(os.path.abspath(args[0])) and os.path.exists(os.path.abspath(args[0])):
		handle = open(os.path.abspath(args[0]), 'r')
		contents = handle.read(-1)
		handle.close()
		return tolen(contents, opts.width)
	else:
		return tolen(" ".join(args), opts.width)

def main():
	"""usage: to80 FILE_WITH_TEXT.txt """
	parser = optparse.OptionParser(description=__doc__)
	parser.set_usage(main.__doc__)
	parser.formatter.format_description = lambda s:s


	parser.add_option("-v", "--version", action="store_true",
						default=False, 
						help="Display Version")

	parser.add_option("-w", "--width", action="store", type='int',
						default=80, metavar='[INT]',
						help="Set width (default 80)")

	(opts, args) = parser.parse_args()

	# Logging Configuration

	if opts.version:
		return version()

	try:
		if len(args) < 1:
			parser.print_help()
			print('ERROR: No file or text provided')
		else:
			print(run(opts,args))
	except KeyboardInterrupt as e:
		print('bye!')
		sys.exit(1)
	sys.exit(0)

if __name__ == '__main__':
	main()
