#!/usr/bin/env python
#coding: utf-8
#
# ycat 横ＣＡＴ（Open usp Tukubai版）
# 
# designed by Nobuaki Tounaka
# written by Yoshio Katayama
#
# The MIT License
#
# Copyright (C) 2011 Universal Shell Programming Laboratory
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

_usage = "ycat [-n] file1 file2..."
_version = "Fri Oct 21 11:26:06 JST 2011"
_code = "Open usp Tukubai (LINUX+FREEBSD/PYTHON2.4/UTF-8)"

import re
import os
import sys
import stat
import tempfile

def error(msg, *arg):
	print >> sys.stderr, 'Error[ycat] :', msg % arg
	sys.exit(1)

def usage():
	print >> sys.stderr, "Usage   :", _usage
	print >> sys.stderr, "Version :", _version
	print >> sys.stderr, "         ", _code
	sys.exit(1)

#
# unicode 変換
#
def to_unicode(s):
	try:
		return unicode(s, 'utf_8')
	except:
		error("不当なマルチバイト文字が含まれています。")

#
# 文字列の表示幅
#
def strwidth(s):
	wid = 0
	for c in to_unicode(s):
		if c <= '\x7f' or c >= u'\uff61' and c <= u'\uff9f':
			wid += 1
		else:
			wid += 2
	return wid

#
# 入力ファイルオープン
#
def open_file(n, mode = 'r'):
	if n >= len(sys.argv) or sys.argv[n] == '-':
		file = sys.stdin
	else:
		try:
			file = open(sys.argv[n], mode)
		except:
			error("ファイル %s をオープンできません。", sys.argv[n])
	return file

#
# 通常ファイルの判定
#
def isfile(fd):
	try:
		return stat.S_ISREG(os.fstat(fd).st_mode)
	except:
		return False

#
#メイン関数
#
if __name__ == '__main__':

        if len(sys.argv) < 2 \
         or sys.argv[1] == '--help' \
         or sys.argv[1] == '--version':
		usage()

	#
	# -<n>
	#
	if re.match('-\d+$', sys.argv[1]):
		n = int(sys.argv[1][1:])
		del sys.argv[1]
		if len(sys.argv) <= 1:
			usage()
	else:
		n = 1

	#
	# 1st pass
	#
	files = []
	for i in range(1, len(sys.argv)):
		f = open_file(i)
		if isfile(f.fileno()):
			tmp = None
		else:
			tmp = tempfile.mkstemp(prefix='ycat-')
			os.unlink(tmp[1])
			tmp = os.fdopen(tmp[0], 'w+')
		wid = 0
		for l in f:
			l = l.rstrip('\n')
			wid = max(wid, strwidth(l))
			if tmp:
				print >>tmp, l
		if tmp:
			f.close()
			f = tmp
		f.seek(0)
		files += [ [ f, wid ] ]

	#
	# 2nd pass
	#
	while True:
		lines = []
		exist = False
		for f in files:
			l = f[0].readline()
			if l:
				l = l.rstrip('\n')
				exist = True
			l += ' ' * (f[1] - strwidth(l))
			lines += [ l ]
		if not exist:
			sys.exit(0)
		for i in range(len(lines) - 1):
			sys.stdout.write(lines[i] + ' ' * n)
		sys.stdout.write(lines[-1] + '\n')
