#!/usr/bin/python3
# vim:se tw=0 sts=4 ts=4 et ai:
"""
Copyright © 2014 Osamu Aoki

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import os
import sys
import re

# example pattern: Copyright (C) 2000 Jakub Jelinek (jakub@redhat.com)
re_copy = re.compile('\s*(?:\(c\))?\s*copyright.[^n][^o][^t]', re.IGNORECASE)

re_nocopy = re.compile(r'''
    copyright.+\sdisclaimer\s|
    copyright\s+for\s|
    copyright.+\sholder\s|
    copyright\s+is\s|
    copyright.*\sinterest\s|
    copyright.*\sinformation\s|
    copyright.*\slicense\s|
    copyright.*\sline\s|
    copyright.*\sname\s|
    copyright.*\sstring\s|
    copyright.*\snotice\s|
    copyright\slaw
    ''', re.IGNORECASE | re.VERBOSE)
def header(g):
    print ("#%#%#%# This is copyright analyser test data by Osamu Aoki.", file=g)
    print ("#%#%#%# The following lines shall not be considered copyright statement.", file=g)
    print ("#%#%#%# ", file=g)
    print ("/*", file=g)

def tailer(g):
    print ("*/", file=g)
    print ("", file=g)
    print ("BOGUS LINE", file=g)
#######################################################################
# Test script
#######################################################################
if __name__ == '__main__':
    file = sys.argv[1]
    i = 0
    mode = 'L' # copyright, license
    with open(file, 'r') as f:
        for line in f:
            #print('R: {}'.format(line))
            copy = re_copy.match(line)
            nocopy = re_nocopy.match(line)
            if copy and (not nocopy): # C
                #print('C: {}'.format(line))
                if mode == 'L': # L -> C
                    if i != 0:
                        tailer(g)
                        g.close()
                    i += 1
                    g = open('mit_{:03}.txt'.format(i), 'w')
                    header(g)
                mode = 'C'
            else: # L
                #print('L: {}'.format(line))
                mode = 'L'
            if i != 0:
                print(line, file=g, end = '')

