"""Script to fix birdsong json files, some of which have trailing commas

"""
import argparse
import os
import sys


if __name__ == '__main__':
    description = 'Remove trailing comma from json file'
    parser = argparse.ArgumentParser(description=description)

    # Default input file:
    parser.add_argument('-i', '--input_filename', required=True, \
        help='Input file')
    parser.add_argument('-w', '--write_over', action='store_true', \
        help="Write over the input file")
    options = parser.parse_args()

    print(options)

    with open(options.input_filename, 'r+') as fp:
        offset = -5
        fp.seek(offset, os.SEEK_END)
        data = fp.read()
        print('data: {}'.format(data))
        dm3 = data[-3]
        #print('data[-3] {}'.format(data[-3]))
        if dm3 == ',':
            print('data[-3] IS COMMA')
            if options.write_over:
                fp.seek(-3, os.SEEK_END)
                fp.write(' ')
                print('Overwrote comma with space')
        else:
            print('file is OK')
