#!/usr/bin/env python
#coding: utf-8
#
# up3 ラストマージツール（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 = "up3 key=<key> <master_file> <tran_file>"
_version = "Fri Oct 21 11:26:06 JST 2011"
_code = "Open usp Tukubai (LINUX+FREEBSD/PYTHON2.4/UTF-8)"
_keypat = r'(\d+|NF(-\d+)?)(/(\d|NF(-\d+)?))?$'	# 1st key: \1, 2nd key: \4

import re
import os
import sys

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

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

class FieldLine:
	def __init__(self, line, allow_z = False):
		self.__allow_zero = allow_z
		line = line.rstrip('\n')
		self.__fields = [ line ]
		self.__fields += [ x for x in line.split(' ') if x ]

	def size(self):
		return len(self.__fields) - 1

	def getFieldNum(self, key):
		if type(key) == type(0):
			return key
		if re.match(r'\d+$', key):
			key = int(key)
		elif key == 'NF':
			key = self.size()
		else:
			key = self.size() - int(key[3:])
			if key <= 0:
				error("NF-x の x が大きすぎます。")
		if key < 0:
			error("フィールド番号が負です。")
		if key == 0 and not self.__allow_zero:
			error("フィールド番号が０です。")
		if key > self.size():
			error("フィールド番号が大きすぎます。")
		return key

	def getField(self, s, e = None):
		s = self.getFieldNum(s)
		if e == None:
			e = s
		else:
			e = self.getFieldNum(e)
		if s <= e:
			return ' '.join(self.__fields[s : e + 1])
		else:
			t = self.__fields[e : s + 1]
			t.reverse()
			return ' '.join(t)

#
# 入力ファイルオープン
#
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

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

	if len(sys.argv) <= 2:
		usage()

	#
	# key=<key>
	#
	k = re.match('key=' + _keypat, sys.argv[1])
	if not k:
		usage()
	k1 = k.group(1)
	k2 = k.group(4)

	master = open_file(2)
	trans  = open_file(3)

	#
	# trans の１行入力
	#
	tline = trans.readline()
	if not tline:
		for mline in master:
			print mline,
		sys.exit(0)
	t = FieldLine(tline)

	#
	# メインループ
	#
	for mline in master:
		m = FieldLine(mline)
		while m.getField(k1, k2) > t.getField(k1, k2):
			print tline,
			tline = trans.readline()
			if not tline:
				print mline,
				for mline in master:
					print mline,
				sys.exit(0)
			t = FieldLine(tline)
		print mline,

	#
	# trans の残り行の出力
	#
	while tline:
		print tline,
		tline = trans.readline()

	sys.exit(0)
