def Generate(fname, AppDef, Info):
    global errObj
    global app
    global info
    print
    print 'Creating Configuration Files...'
    print

    errObj = Logger()
    app = simplifiedApplicationDefinition(AppDef)
    Info.stack = Stack('DOWN', 0x00)
    info = Info

    alarmsForCounters = getAlarmsForCounters()

    namespace = {
        'app': app,
        'osVars': osVars,
        'info': Info,
        'ORTICfg': ORTICfg,
        'alarmsForCounters': alarmsForCounters,
        'getApplicationModes': getApplicationModes,
        'time': time,
    }

    # app.tasks.sort(key=lambda x: x['RELATIVE_PRIORITY'].value)

    app.tasks.sort(key=lambda x: x.PRIORITY)

    #    if info['useResources'] == False:
    #        osVars['runningTaskPriority'] = '(OS_TaskConf[OsCurrentTID].Priority)'

    #    from pkg_resources import Requirement, resource_filename
    #    filename = resource_filename(Requirement.parse("MyProject"),"sample.conf")

    writeTemplate(r'hfile.tmpl', 'Os_Cfg.h', namespace, encodeAsUTF8=False)
    writeTemplate('cfile.tmpl', 'Os_Cfg.c', namespace, encodeAsUTF8=False)
    writeTemplate('isrcfgfile.tmpl',
                  'ISR_Cfg.h',
                  namespace,
                  encodeAsUTF8=False)
    if app.os.ORTI_DEBUG.value == True:
        info.vendor = 'K_OS'

        info.koilVersion = app.os.ORTI_DEBUG.KOIL_VERSION
        info.osekVersion = app.os.ORTI_DEBUG.OSEK_VERSION

        info.context = (
            Register('PC', 'uint16', 7),
            Register('Y', 'uint16', 5),
            Register('X', 'uint16', 3),
            Register('D', 'uint16', 1),
            Register('A', 'uint8', 2),
            Register('B', 'uint8', 1),
            Register('CCR', 'uint8', 0x00),
        )
        writeTemplate('ortifile.tmpl',
                      'App.ort',
                      namespace,
                      encodeAsUTF8=False)
  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, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

   s. FLOSS-EXCEPTION.txt
"""

import unittest

from kosek.Logger import Logger

logger = Logger()

class Info(object): pass


class ApplicationDefinitionBuilder(object):
    def __init__(self, parser, definitionList, description):
        self.definitionList = definitionList
        self.parser = parser
        self.description = description
        self.info = Info()

    def postProcessing(self):
        result = {}
        self.standardResources = self.parser.standardResources  # TODO: in der Grammatik handeln!!!
        self.internalResources = self.parser.internalResources
def main():
    print ("kosgen, Part of k_os (Konnex Operating-System based on the OSEK/VDX-Standard).")
    usage = 'usage: %prog [options] oil_file'

    options = []
    args = []

    op = OptionParser(usage = usage, version = '%prog ' + __version__,
        description = "Generate K-OS-Configuration from '.oil'-File."
    )
    op.add_option('-f', '--command-file', type = 'string', metavar = 'FILE', dest = 'command_file',
        help = 'read options from command-FILE'
    )

    input_group = OptionGroup(op, 'Input')
    input_group.add_option('-I', '--include-path', dest = 'inc_path', action = 'append',
        metavar = 'dir',
        help = """Add directory to the list of directories to be searched for include files.
        Environment-Variable 'KOS_INCLUDE' is also used to locate Include-Files."""

    )
    op.add_option_group(input_group)

    group = OptionGroup(op, 'Output')
    group.add_option('-o', '--orti', help = 'generate orti-FILE', dest = 'orti', action = 'store_true', default = False)
    group.add_option('-r', '--resource-usage', help = 'generate resource statistics', dest = 'res_usage',
            action = 'store_true', default = False)
    group.add_option('-t', '--test', help = "verify only, don't generate anything", dest = 'test',
        action = 'store_true', default = False)
    group.add_option('-V', '--verbose', help = 'print Information messages', dest = 'verbose',
        action = 'store_true', default = False)
    group.add_option('-S', '--silent', help = "don't print any messages.", dest = 'silent', action = 'store_true',
        default = False)

## keep immediate file.
    op.add_option_group(group)

    (options, args) = op.parse_args()

    SetIncludePaths(options.inc_path)

    if len(args) == 0:
        op.error('no input file')

    if len(args) != 1:
        op.error('incorrect number of arguments')

    error = Logger()
    logger = logging.getLogger('kos.oil.logger')
    if options.verbose:
        logger.setLevel(logging.DEBUG)
    elif options.silent:
        logger.setLevel(logging.CRITICAL)
    else:
        logger.setLevel(logging.WARNING)

    inFile = open(args[0])
    outFilename = os.path.splitext(os.path.abspath(args[0]))[0] + '.i'
    outFile = open(outFilename, 'w')
    Preproc.Preproc(inFile, outFile)
    outFile.close()

    try:
        inFile = open(outFilename)
    except IOError:
        error.fatalError("Could not open file '%s'.\n" % outFilename)
    else:
        (implDefMap, appDefMap, info) = parse(outFilename)

        info.version = __version__.replace('.', '_').replace('-', '_')

        if options.test == False:
            if error.errorCounter > 0:
                error.error('\n%u Error(s) occured during parsing, generating nothing.'
                              % error.errorCounter)
            else:
                GenCfg.Generate(os.path.splitext(args[0])[0], appDefMap, info)
def main():
    print(
        "kosgen, Part of k_os (Konnex Operating-System based on the OSEK/VDX-Standard)."
    )
    usage = 'usage: %prog [options] oil_file'

    options = []
    args = []

    op = OptionParser(
        usage=usage,
        version='%prog ' + __version__,
        description="Generate K-OS-Configuration from '.oil'-File.")
    op.add_option('-f',
                  '--command-file',
                  type='string',
                  metavar='FILE',
                  dest='command_file',
                  help='read options from command-FILE')

    input_group = OptionGroup(op, 'Input')
    input_group.add_option(
        '-I',
        '--include-path',
        dest='inc_path',
        action='append',
        metavar='dir',
        help=
        """Add directory to the list of directories to be searched for include files.
        Environment-Variable 'KOS_INCLUDE' is also used to locate Include-Files."""
    )
    op.add_option_group(input_group)

    group = OptionGroup(op, 'Output')
    group.add_option('-o',
                     '--orti',
                     help='generate orti-FILE',
                     dest='orti',
                     action='store_true',
                     default=False)
    group.add_option('-r',
                     '--resource-usage',
                     help='generate resource statistics',
                     dest='res_usage',
                     action='store_true',
                     default=False)
    group.add_option('-t',
                     '--test',
                     help="verify only, don't generate anything",
                     dest='test',
                     action='store_true',
                     default=False)
    group.add_option('-V',
                     '--verbose',
                     help='print Information messages',
                     dest='verbose',
                     action='store_true',
                     default=False)
    group.add_option('-S',
                     '--silent',
                     help="don't print any messages.",
                     dest='silent',
                     action='store_true',
                     default=False)

    ## keep immediate file.
    op.add_option_group(group)

    (options, args) = op.parse_args()

    SetIncludePaths(options.inc_path)

    if len(args) == 0:
        op.error('no input file')

    if len(args) != 1:
        op.error('incorrect number of arguments')

    error = Logger()
    logger = logging.getLogger('kos.oil.logger')
    if options.verbose:
        logger.setLevel(logging.DEBUG)
    elif options.silent:
        logger.setLevel(logging.CRITICAL)
    else:
        logger.setLevel(logging.WARNING)

    inFile = open(args[0])
    outFilename = os.path.splitext(os.path.abspath(args[0]))[0] + '.i'
    outFile = open(outFilename, 'w')
    Preproc.Preproc(inFile, outFile)
    outFile.close()

    try:
        inFile = open(outFilename)
    except IOError:
        error.fatalError("Could not open file '%s'.\n" % outFilename)
    else:
        (implDefMap, appDefMap, info) = Parse(outFilename)

        info.version = __version__

        if options.test == False:
            if error.errorCounter > 0:
                error.error(
                    '\n%u Error(s) occured during parsing, generating nothing.'
                    % error.errorCounter)
            else:
                GenCfg.Generate(os.path.splitext(args[0])[0], appDefMap, info)