#!/usr/bin/env python3

import argparse,os,re,sys

progname=os.path.basename(sys.argv[0])

def die(msg='',rc=1):
  if msg:
    print(f"{progname}: {msg}",file=sys.stderr)
  sys.exit(rc)

ap=argparse.ArgumentParser(
  description="""Read from the given FILENAME, or standard input if no FILENAME is given, and write only lines that do not occur later in the file. This has the effect of writing out only the last occurrance of each distinct line value. Output is written to standard output unless --in-place is used."""
)
ap.add_argument('-i',dest='ignore_case',action='store_true',help="""Ingore the case of the input when comparing lines. (This option doubles the amount of memory required.)""")
ap.add_argument('--in-place',dest='in_place',action='store_true',help="""Edit the input file in place. This means that the input file will be replaced with the de-duplicated output, and nothing will be written to standard output. The FILENAME argument MUST be given if this option is used, and an error will occur if that file cannot be written to.""")
ap.add_argument('args',metavar='FILENAME',nargs='?',help="This file will be read rather than standard input.")
try:
  opt=ap.parse_args()
except Exception as e:
  die(str(e))
if opt.in_place and not opt.args:
  die("--in-place option requires a FILENAME argument to be given.")
if opt.args and len(opt.args)>1:
  die("only 1 FILENAME argument may be given")

# Get our input from SOMEPLACE.
if opt.args:
  filename=opt.args[0]
  if opt.in_place:
    f=open(filename,'rw+')
  else:
    f=open(filename,'r')
else:
  f=sys.stdin

# Turn the text coming in into the text going out.
coming=f.readlines()
going=[]
if opt.ignore_case:
  # Here's how we ignore case.
  ic=[x.lower() for x in coming]
  while coming:
    if ic[0] not in ic[1:]:
      going.append(coming[0])
    del(ic[0])
    del(coming[0])
else:
  # Respecting case is simpler.
  while coming:
    if coming[0] not in coming[1:]:
      going.append(coming[0])
    del(coming[0])

# Write the outgoing text.
if opt.in_place:
  f.truncate()
else:
  f=sys.stdout
f.writelines(going)
