#!/usr/bin/env python3

""" This script is used to generate built-in string tables for dos.library
They use very own format which is impossible to generate with FlexCat.
"""

import sys

def getline(fhandle):
    line = ";"
    while line.startswith(';'):
        line = fhandle.readline()

    return line.rstrip('\n')


def main():
    fhandle = open(sys.argv[1], 'r')
    ids = []
    numbers = []
    strings = []
    while True:
        id_line = getline(fhandle)
        str_line = getline(fhandle)
        if (id_line == "") or (str_line == ""):
            break

        tmp = id_line.split()
        ids.append(tmp[0])

        tmp = tmp[1].split('(')
        tmp = tmp[1].split('/')
        numbers.append(tmp[0])

        strings.append(str_line)

    print("/* This file is automatically generated! Do not edit! */")
    print()

    print("/*")
    print(" * Error codes index table.")
    print(" * This table actually consists of pairs of values (begin, end).")
    print(" * One string in the table below corresponds to one error code")
    print(" * from the specified interval.")
    print(" * The table is terminated by two zeros.")
    print(" * This layout was recreated based on locale.library code brought from MorphOS.")
    print(" */")
    print("const ULONG err_Numbers[] =")
    print("{")
    first = ids[0]
    last = ids[0]
    n = 0
    while n < len(numbers) - 1:
        prev = int(numbers[n])
        n = n + 1
        if int(numbers[n]) == prev + 1:
            last = ids[n]
        else:
            print("    %s, %s," % (first, last))
            first = ids[n]
            last = ids[n]
    print("    0, 0")
    print("};")
    print()

    print("/*")
    print(" * Strings follow each other.")
    print(" * Every string is prefixed by length byte in BCPL manner. NULL terminator is counted too.")
    print(" */")
    print("const char err_Strings[] =")
    print("{")
    for str_line in strings:
        print("    %d," % (len(str_line) + 1))
        for c in str_line:
            print("'%s'," % c, end=' ')
        print("0,")
    print("};")
    fhandle.close()


if __name__ == "__main__":
    main()
