#! /usr/bin/env python
from __future__ import print_function, unicode_literals

'''Count lines in xbase source files'''
'''Used by sloccount'''

import sys
import argparse
import re

def parse_args(argv=None):
    parser = argparse.ArgumentParser(description='Count lines in xbase programs')
    parser.add_argument("-f", metavar=('file',), nargs=1, type=str)
    parser.add_argument("files", type=str, nargs='*')
    return parser.parse_args(argv)

def countline(line):
    line = line.strip()
    return line and not (line.startswith('*') or line.startswith('&&') or re.match(r'^[Ee][Nn][Dd][A-Za-z]*$', line))

def main(argv=None):
    encoding = 'cp1252'
    args = parse_args(argv)
    files = []
    if args.f:
        args.f = args.f[0]
        if args.f == '-':
            files += sys.stdin.readlines()
        else:
            with open(args.f, 'rb') as fid:
                files += fid.readlines()
    files += args.files
    total=0
    for filename in files:
        filename = filename.strip()
        with open(filename, 'rb') as fid:
            lines = len([None for line in fid.readlines() if countline(line.decode(encoding))])
        print('{} {}'.format(lines, filename))
        total += lines

    print('Total:\n{}'.format(total))

if __name__ == '__main__':
    main()
