import sys
import time
import StringIO

def gettail(fp, n):
  start = fp.tell()
  fp.seek(0, 2)
  end = fp.tell()
  s = ''
  while len(s) < end - start and s.count('\n') <= n:
    a = min(160 * n, fp.tell() - start)
    fp.seek(-a, 1)
    s = fp.read(a) + s
  return StringIO.StringIO(s).readlines()[-n:]

def getnlines(fp, start, n):
  fp.seek(0, 2)
  pos = fp.tell()
  fp.seek(start)
  for s in gettail(fp, n):
    sys.stdout.write(s)
    sys.stdout.flush()
  return pos

n = 10
f = False
fp = None

sys.argv.pop(0)
while sys.argv:
  s = sys.argv.pop(0)
  if s == '-n':
    n = int(sys.argv.pop(0))
  elif s == '-f':
    f = True
  elif not s.startswith('-'):
    fp = file(s, 'rb')

pos = getnlines(fp, 0, n)

while f:
  time.sleep(1)
  pos = getnlines(fp, pos, n)
