#!/usr/bin/env python
#coding: utf-8
#
# yobi 曜日挿入フィルタ（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 = "yobi [-ej] <field> <filename>"
_usage1 = "yobi -d[ej] <string>"
_version = "Fri Oct 21 11:26:06 JST 2011"
_code = "Open usp Tukubai (LINUX+FREEBSD/PYTHON2.4/UTF-8)"
_keypat = r'\d+$'

import re
import os
import sys
from getopt import getopt
from datetime import datetime

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

def usage():
	print >> sys.stderr, "Usage   :", _usage
	print >> sys.stderr, "        :", _usage1
	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

#
# 曜日の計算
#
def weekday(date, lang):
	if not re.match(r'\d{8}', date):
		error("日付が8桁整数になっていません。")
	try:
		w = datetime(int(date[:4]), int(date[4:6]), int(date[6:])).weekday()
	except:
		error("日付が正しくありません。")
	return {
		'':  [ str(x) for x in range(1, 7) + [ 0 ] ],
		'e': [ 'Mon', 'Tue','Wed','Thu','Fri','Sat','Sun' ],
		'j': [ '月',  '火', '水', '木', '金', '土', '日' ],
	}[lang][w]

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

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

	#
	# オプションの取得
	#
	direct, lang = '', ''
	try:
		opts = getopt(sys.argv[1:], "dej")
		for opt in opts[0]:
			if opt[0] == '-d':
				direct = True
			else:
				# '-e' or '-j':
				lang = opt[0][1]
		if not opts[1]:
			usage()
		sys.argv = sys.argv[0:1] + opts[1]
	except:
		usage()
	#
	# ダイレクトモード
	#
	if direct:
		print weekday(sys.argv[1], lang)
		sys.exit(0)

	#
	# <field>
	#
	if not re.match(_keypat, sys.argv[1]):
		usage()
	fld = int(sys.argv[1])
	if fld == 0:
		error("フィールド番号が正しくありません、")

	#
	# メインループ
	#
	for line in open_file(2):
		line = FieldLine(line)
		if line.size() < fld:
			print line.getField(1, line.size())
		else:
			print line.getField(1, fld), weekday(line.getField(fld), lang),
			if fld < line.size():
				print line.getField(fld + 1, line.size()),
			print

	sys.exit(0)
