#!/usr/bin/env python
#coding: utf-8
# 
# ctail ファイル末尾のn行を取り出す。 （Open usp Tukubai版）
#
# designed by Nobuaki Tounaka
# written by Ryuichi Ueda
#
# 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 = "ctail -<n> <file>"
_version = "Fri Oct 21 11:26:06 JST 2011"
_code = "Open usp Tukubai (LINUX+FREEBSD/PYTHON2.4/UTF-8)"

import os
import sys

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

def prefixEqual(prefix,token):
	if len(prefix) > len(token):	return False
	
	p = token[0:len(prefix)]
	if p == prefix:	return True

	return False

def die(message):
	print >> sys.stderr, "Error[ctail] :", message
	sys.exit(1)


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

	###########################################
	#オプションの処理
	###########################################
	file = sys.stdin
	n = 10

	argc = len(sys.argv)
	#ファイルか、-nか
	try:
		for i in range(1, argc):
			arg = sys.argv[i]
			if arg == "-":			pass
			elif prefixEqual("-",arg):	n = int(arg[1:])
			else:				file = open(arg,'r')
	except:
		printUsage()

	if n <= 0:
		printUsage()

	###########################################
	#出力
	###########################################
	line_queue = []
	for line in file:
		line_queue.append(line)
		if len(line_queue) > n:
			print line_queue.pop(0),
