# -*- coding: utf-8 -*-
"""
This file is part of KToBlzCheck
Copyright (C) 2019 Ralf Habacker <ralf.habacker@freenet.de>

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

"""
This script converts the ascii file of German Bank Codes (BLZ-Datei)
as available from the Deutsche Bundesbank into the bankdata.txt file
for the ktoblzcheck library.
"""

import codecs
import argparse

def processFile(fileName, outFile):
    """ procedd raw bankdata file
    """

    rowsInserted = 0

    institutesFile = codecs.open(fileName, "r", encoding=args.encoding)
    out = codecs.open(outFile, 'w', encoding=args.encoding)
    for institute in institutesFile:
        if institute[8:9] == "1":
            out.write("%s\t%s\t%s\t%s\n" % (institute[0:8], institute[150:152], institute[9:67].strip(), institute[72:107]))
            rowsInserted += 1

    return rowsInserted


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Creates")
    parser.add_argument(dest='file', help='File to load')
    parser.add_argument('-o', '--output', default="bankdata_xxx.txt", help='bankdata file in ktoblzcheck format')
    parser.add_argument('-e', '--encoding', default="iso 8859-1", help='Charset of file')
    args = parser.parse_args()

    print("Read data from \"{0}\" with \"{1}\" encoding".format(args.file, args.encoding))
    institutions = processFile(args.file, args.output)
    print("Added {0} institutions to output file\"{1}\"".format(institutions, args.output))
