#!/usr/bin/env python

import sys, os

def usage():
    print("""\n\
rmobjs.py deletes all files listed in the given file.
example:

   ls -1 *.o > files.txt
   rmobjs.py files.txt

if the first word on a line of the file in sys.argv[1] is a file,
delete it.  skip blank lines, lines starting with # (comments), and
lines that contain = (probably assignments)
""")

if len(sys.argv)<2:
    print("too few arguments")
    usage()
    sys.exit(2)

print("  Deleting all files in",sys.argv[1]," (hit Ctrl-c NOW if you disagree)")

if os.access(sys.argv[1], os.F_OK):
    f = open(sys.argv[1], 'r')
else:
    print("could not open file ",sys.argv[1])
    usage()
    sys.exit(1)

removed=0
mod_removed=0

for line in f:
    if line.strip()=="":
        continue
    if line.strip()[0]=="#":
        continue
    if line.find("=")>-1:
        continue

    filename = line.split()[0]
    if os.access(filename, os.F_OK and os.W_OK):
        os.remove(filename)
        removed+=1

    dotpos = filename.rfind('.')
    modname = filename[:dotpos] + ".mod"

    if os.access(modname, os.F_OK and os.W_OK):
        os.remove(modname)
        mod_removed+=1


print(" ",removed,".o files removed", mod_removed, ".mod files removed")
