/****************************************************************************
** Leistungsorientierte Krankenanstaltenfinanzierung (LKF)                 **
** Scoring-C-Sourcen V2026.1                                               **
** (C) 2026 BMASGPK                                                        **
*****************************************************************************
** lkfscoring.c - Hauptprogramm (Commandline-Interface)                    **
**                                                                         **
**		 Alex.Holzer@chello.at                                             **
**       Bernhard.Pesec@dothealth.at                                       **
***************************************************************************/

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h> 
#include <errno.h>

#ifdef __APPLE__
#include <sys/types.h>
#include <dirent.h>
#elif defined(__GNU__) || defined(UNIX)
#define LKF_DISABLE_IO   1
#else
#include <io.h>
#endif

#include "lkf5defs.h"

/* macros ***************************************************************************************************/

#define FLAG_MODUS_PLAUS			1
#define FLAG_MODUS_PLAUS_FILE		(1<<1)
#define FLAG_MODUS_ERROR_FILE		(1<<2)
#define FLAG_MODUS_SUM_FILE			(1<<3)
#define FLAG_MODUS_ABT_FILE			(1<<4)
#define FLAG_MODUS_SCORING			(1<<8)
#define FLAG_MODUS_SCOR_FORMAT_NORM	(1<<9)
#define FLAG_MODUS_SCOR_FORMAT_SV   (1<<10)
#define FLAG_MODUS_SCOR_FORMAT_C	(1<<11)
#define FLAG_MODUS_SCOR_FORMAT_CX	(1<<12)
#define FLAG_MODUS_DIFF				(1<<16)
#define FLAG_MODUS_PATH				(1<<18)
#define FLAG_MODUS_NPPLAUS_TRACE    (1<<19)
#define FLAG_MODUS_INTSCORING		(1<<20)
#define FLAG_MODUS_DATAOUT			(1<<21)
#define FLAG_MODUS_STAT             (1<<22)
#define FLAG_MODUS_NPPLAUS_SUM      (1<<23)
#define FLAG_MODUS_MELDEDIAG_FILE_OFF (1<<24)
#define FLAG_MODUS_ERRSUM_FILE_OFF  (1<<25)
#define FLAG_MODUS_WARNSUM_FILE_OFF (1<<26)
#define FLAG_MODUS_ANONYMIZE        (1<<27)
/* Intensiv-Scoring-Modus-Flags (V8.1) ***********************************************************************/
#define FLAG_INTMODUS_AKTIV				 1
#define FLAG_INTMODUS_OUTPUT_EINSTUFUNG	 2
#define FLAG_INTMODUS_OUTPUT_ANALYSE	 4
#define FLAG_INTMODUS_OUTPUT_SAPSII		 8
#define FLAG_INTMODUS_OUTPUT_TISS		16
#define FLAG_INTMODUS_OUTPUT_TRISS		32
#define FLAG_INTMODUS_INTAUF_DETAILS	64
#define FLAG_INTMODUS_OUTPUT_DETAILS	(FLAG_INTMODUS_INTAUF_DETAILS|FLAG_INTMODUS_OUTPUT_SAPSII|FLAG_INTMODUS_OUTPUT_TISS|FLAG_INTMODUS_OUTPUT_TRISS)

#define LKF_MAX_PATH 256

typedef struct 
{
	char ABTFC[10]; /* V16.0: 8 - 10 fuer NULL-Terminator */
	unsigned int nBetten;
} INTABTDEF;

typedef struct 
{
	int modus;								/* Programm-Modus */
	unsigned int modelljahr;				/* Modelljahr */
    int flags;                              /* Flags */
	char sStammPath[LKF_MAX_PATH];			/* Stammdaten-Pfad */
	char sInputPath[LKF_MAX_PATH];			/* Input-Pfad */
	char sOutputPath[LKF_MAX_PATH];			/* Output-Pfad */
	unsigned int int_modus;					/* Intensiv-Scoring-Ausgabemodus */
	unsigned int lkf_compatibility;         /* Compatibility-Setting für lkf-C-Routinen */
	unsigned int private_compatibility;     /* Compatibility-Setting innerhalb LKFScoring.EXE */
	unsigned int field[60];					/* Feldnummern fuer Custom Output */
	unsigned int field_anz;					/* Anzahl Felder fuer Custom Output */
	LKF_FILTER *pFilter;					/* Filter-Definition */
	int cmb_jahr;							/* Abrechungsjahr */ 
	int period_val;							/* Periodenwert */
	int lfdnr;								/* Laufende Nummer */
	char period_type;						/* Periodentyp */
	char IntStartDate[10];					/* Start-Datum */
	char IntEndDate[10];					/* End-Datum */
	unsigned int nIntAbtDatAnzahl;			/* IntensivAbteilungsanzahl */
	INTABTDEF *pIntAbtDef;					/* IntensivAbteilungsdefinition */
	unsigned int *errorfields;				/* FileStruktur des Errorfiles */
	unsigned int *warningfields;			/* FileStruktur des Warningfiles */
	unsigned int *infofields;               /* FileStruktur des Hinweisfiles ab Modell 2009 */
	unsigned int errorfieldcount;           /* Anzahl Error-Felder */
	unsigned int warningfieldcount;			/* Anzahl Warning-Felder */
	unsigned int infofieldcount;            /* Anzahl Hinweis-Felder */
	unsigned int *ktrerrorfields;           /* Kostenträger ab Modell 2009 */
	unsigned int ktrerrorfieldcount;        /* Anzahl Kostensträger-Felder ab Modell 2009 */
	unsigned int *ktrwarningfields;         /* Kostenträger ab Modell 2009 */
	unsigned int ktrwarningfieldcount;      /* Anzahl Kostensträger-Felder ab Modell 2009 */
    
    int fmt_err_pre2017;                    /* V21.0 */
    int fmt_add_posfield;                   /* V22.2 */
    unsigned int packageSize;               /* V21.0: work in packages */
    
    const char *anonymizationParameters;    /* V2024.1 */
    
} LKF_SCORING_PARAMETERS;

/* argument prototypes **************************************************************************************/

static int parse_commandline (int argc, char *argv[], LKF_SCORING_PARAMETERS *pParameters);
static int parse_command (const char **ppBuf, LKF_SCORING_PARAMETERS *pParameters);

static int parse_commandfile (const char *sCommandFile, const char *sInputFile, LKF_SCORING_PARAMETERS *pParameters);

static int parse_command_filter (int bModus, const char **ppBuf, LKF_FILTER **ppFilter);
static int parse_filter_file (const char *filename, LKF_FILTER **ppFilter);

static int WriteErrorlistFile (LKF_CONTEXT *pContext, const char *path);
static int WriteSatzartInfoFile (LKF_CONTEXT *pContext, const char *path);


static unsigned int infofields[] = {CHECKFIELD_KANR, CHECKFIELD_AUFNR, CHECKFIELD_GEBDAT, CHECKFIELD_GESCHL, CHECKFIELD_AUFDAT, CHECKFIELD_ENTDAT,
   									   CHECKFIELD_ABTFCENT, CHECKFIELD_SATZART, CHECKFIELD_FELD_LANG, CHECKFIELD_CODE, CHECKFIELD_TEXT};
static unsigned int warningfields[] = {CHECKFIELD_KANR, CHECKFIELD_AUFNR, CHECKFIELD_GEBDAT, CHECKFIELD_GESCHL, CHECKFIELD_AUFDAT, CHECKFIELD_ENTDAT,
   									   CHECKFIELD_ABTFCENT, CHECKFIELD_MASSNAHME, CHECKFIELD_SATZART, CHECKFIELD_FELD_LANG, CHECKFIELD_CODE, CHECKFIELD_TEXT};
static unsigned int errorfields2016[] = {CHECKFIELD_KANR, CHECKFIELD_AUFNR, CHECKFIELD_GEBDAT, CHECKFIELD_GESCHL, CHECKFIELD_AUFDAT, CHECKFIELD_ENTDAT,
									 CHECKFIELD_ABTFCENT, CHECKFIELD_SATZART, CHECKFIELD_FELD_LANG, CHECKFIELD_CODE, CHECKFIELD_TEXT};


static unsigned int infofieldsBM[] = {CHECKFIELD_KANR, CHECKFIELD_AUFID64, CHECKFIELD_ALTER, CHECKFIELD_GESCHL, CHECKFIELD_AUFDAT, CHECKFIELD_ENTDAT,
    CHECKFIELD_ABTFCENT, CHECKFIELD_SATZART, CHECKFIELD_FELD_LANG, CHECKFIELD_CODE, CHECKFIELD_TEXT};
static unsigned int warningfieldsBM[] = {CHECKFIELD_KANR, CHECKFIELD_AUFID64, CHECKFIELD_ALTER, CHECKFIELD_GESCHL, CHECKFIELD_AUFDAT, CHECKFIELD_ENTDAT,
    CHECKFIELD_ABTFCENT, CHECKFIELD_MASSNAHME, CHECKFIELD_SATZART, CHECKFIELD_FELD_LANG, CHECKFIELD_CODE, CHECKFIELD_TEXT};
static unsigned int errorfieldsBM[] = {CHECKFIELD_KANR, CHECKFIELD_AUFID64, CHECKFIELD_ALTER, CHECKFIELD_GESCHL, CHECKFIELD_AUFDAT, CHECKFIELD_ENTDAT,
    CHECKFIELD_ABTFCENT, CHECKFIELD_SATZART, CHECKFIELD_FELD_LANG, CHECKFIELD_CODE, CHECKFIELD_TEXT};


static unsigned int infofields2017[] = {CHECKFIELD_KANR, CHECKFIELD_AUFNR, CHECKFIELD_GEBDAT, CHECKFIELD_GESCHL, CHECKFIELD_AUFDAT, CHECKFIELD_ENTDAT,
    CHECKFIELD_ABTFCENT, CHECKFIELD_SATZART, CHECKFIELD_FELD_LANG, CHECKFIELD_CODE, CHECKFIELD_TEXT150CHAR, CHECKFIELD_FUCOAUFNR};
static unsigned int warningfields2017[] = {CHECKFIELD_KANR, CHECKFIELD_AUFNR, CHECKFIELD_GEBDAT, CHECKFIELD_GESCHL, CHECKFIELD_AUFDAT, CHECKFIELD_ENTDAT,
    CHECKFIELD_ABTFCENT, CHECKFIELD_MASSNAHME, CHECKFIELD_SATZART, CHECKFIELD_FELD_LANG, CHECKFIELD_CODE, CHECKFIELD_TEXT150CHAR, CHECKFIELD_FUCOAUFNR};
static unsigned int errorfields2017[] = {CHECKFIELD_KANR, CHECKFIELD_AUFNR, CHECKFIELD_GEBDAT, CHECKFIELD_GESCHL, CHECKFIELD_AUFDAT, CHECKFIELD_ENTDAT,
    CHECKFIELD_ABTFCENT, CHECKFIELD_SATZART, CHECKFIELD_FELD_LANG, CHECKFIELD_CODE, CHECKFIELD_TEXT150CHAR, CHECKFIELD_FUCOAUFNR};


static unsigned int infofieldsBM2017[] = {CHECKFIELD_KANR, CHECKFIELD_AUFID64, CHECKFIELD_ALTER, CHECKFIELD_GESCHL, CHECKFIELD_AUFDAT, CHECKFIELD_ENTDAT,
    CHECKFIELD_ABTFCENT, CHECKFIELD_SATZART, CHECKFIELD_FELD_LANG, CHECKFIELD_CODE, CHECKFIELD_TEXT150CHAR, CHECKFIELD_FUCOAUFNR};
static unsigned int warningfieldsBM2017[] = {CHECKFIELD_KANR, CHECKFIELD_AUFID64, CHECKFIELD_ALTER, CHECKFIELD_GESCHL, CHECKFIELD_AUFDAT, CHECKFIELD_ENTDAT,
    CHECKFIELD_ABTFCENT, CHECKFIELD_MASSNAHME, CHECKFIELD_SATZART, CHECKFIELD_FELD_LANG, CHECKFIELD_CODE, CHECKFIELD_TEXT150CHAR, CHECKFIELD_FUCOAUFNR};
static unsigned int errorfieldsBM2017[] = {CHECKFIELD_KANR, CHECKFIELD_AUFID64, CHECKFIELD_ALTER, CHECKFIELD_GESCHL, CHECKFIELD_AUFDAT, CHECKFIELD_ENTDAT,
    CHECKFIELD_ABTFCENT, CHECKFIELD_SATZART, CHECKFIELD_FELD_LANG, CHECKFIELD_CODE, CHECKFIELD_TEXT150CHAR, CHECKFIELD_FUCOAUFNR};

#ifdef PRINT_MELPUNKTE
static void PrintMELPunkte (LKF_AUFENTHALT *pAufenthalt);
#endif

/* V14.2 - Kostentraeger-Formate */
static unsigned int ktrfields[] = {CHECKFIELD_KANR, CHECKFIELD_BERICHTSTYP, CHECKFIELD_SATZART, CHECKFIELD_FELD_LANG, CHECKFIELD_CODE, CHECKFIELD_TEXT};


static void setFileError (char *error, const char *file, const char *errnotext, const char *postfix)
{
    sprintf (error, "File '%s' %s: %s", file, postfix, errnotext);
}

static const char *currentTimeBuf (char *timebuf) {
    time_t rawtime;
    long buflen;
    time(&rawtime);
    strcpy(timebuf, ctime(&rawtime));
    buflen = (long) strlen(timebuf);
    timebuf[buflen-1] = 0;
    return timebuf;
}

static int handle_packaged_execution (const char *inputFile, LKF_CONTEXT *pScoringContext, LKF_SCORING_PARAMETERS *pParameters, char *error)
{
    int firstPackage = 1;
    FILE *fp_input, *fp_output = 0, *fp_error = 0, *fp_warning = 0, *fp_hinweis = 0, *fp_meldediag = 0;
    char outputFileName[128], outputFilePath[512], meldediag_outputFileName[128];
    char line[2048], buf[2048];
    const char *lastLine;
    
    unsigned int x01_count = 0, x01_sum_count = 0;
    const char *ka = 0;
    char ka_name[32];
    unsigned int i, j, nCount, aufanz, auf_filter_anz, count, nAufenthaltAnz;
    LKF_AUFENTHALT *pAufenthalt;
    
    int isKtr = lkf_context_GetGlobalInfo (pScoringContext, LKF_CONTEXTINFO_KTR);
    unsigned int errorfieldcount = isKtr ? pParameters->ktrerrorfieldcount : pParameters->errorfieldcount;
    unsigned int warningfieldcount = isKtr ? pParameters->ktrwarningfieldcount : pParameters->warningfieldcount;
    unsigned int *errorfields = isKtr ? pParameters->ktrerrorfields : pParameters->errorfields;
    unsigned int *warningfields = isKtr ? pParameters->ktrwarningfields : pParameters->warningfields; /* V2019.1 */

    unsigned int errcount = 0, warncount = 0, meldediagcount = 0;
    unsigned int kerr, kwarn;
    double sum_punkte_inlkf = 0, sum_punkte_exlkf = 0;
    double sum_punkte_stat = 0, sum_punkte_amb = 0;
    char timebuf[64];

    fp_input = fopen (inputFile, "r");
    if (!fp_input) {
        setFileError(error, inputFile, strerror(errno), "konnte nicht gelesen werden");
        return 1;
    }
    
    printf ("%s: start\n", currentTimeBuf (timebuf));

    while ((lastLine = fgets (line, 2047, fp_input)) || firstPackage) {
        
        if (*line == 'M' || *line == 'X' || *line == 'I' || lastLine == 0)
        {
            if (!memcmp (line, "X01", 3) || !memcmp (line, "M01", 3) || lastLine == 0)
            {
                if (x01_count == pParameters->packageSize || lastLine == 0)
                {
                    if (firstPackage)
                    {
                        char addline[2048];
                        long streampos;
                        streampos = ftell (fp_input);
                        
                        while (fgets(addline, 2047, fp_input)) {
                            if (*addline != 'M' && *addline != 'X' && *addline != 'I') {
                                lkf_add_line (pScoringContext, addline);
                            }
                        }
                        
                        fseek(fp_input, streampos, SEEK_SET);
                        lkf_context_plaus_package (pScoringContext, 1);
                        ka = lkf_get_context_ka (pScoringContext, 0, &aufanz, &auf_filter_anz);
                        if (!ka) ka = "K000";
                        lkf_KA_to_Name (pScoringContext, ka, ka_name);
                        
                        if (pParameters->modus & FLAG_MODUS_ERROR_FILE)
                        {
                            if (errorfieldcount > 0) {
                                lkf_setErrorFormat (pScoringContext, LKF_FAC_ALL, errorfieldcount, errorfields);
                                lkf_compose_filename (pScoringContext, ka, 'e', outputFileName);
                                sprintf (outputFilePath, "%s%s", pParameters->sOutputPath, outputFileName);
                                
                                fp_error = fopen (outputFilePath, "w");
                                if (!fp_error) {
                                    setFileError(error, outputFilePath, strerror(errno), "konnte nicht initialisiert werden");
                                    return 1;
                                }
                                lkf_getSatzartErrorHeadline (pScoringContext, LKF_FAC_ALL, 1024, buf);
                                fprintf (fp_error, "%s\n", buf);
                            }
                            
                            if (warningfieldcount > 0) {
                                lkf_setErrorFormat (pScoringContext, LKF_FAC_ALL, warningfieldcount, warningfields);
                                lkf_compose_filename (pScoringContext, ka, 'w', outputFileName);
                                sprintf (outputFilePath, "%s%s", pParameters->sOutputPath, outputFileName);
                                
                                fp_warning = fopen (outputFilePath, "w");
                                if (!fp_warning) {
                                    setFileError(error, outputFilePath, strerror(errno), "konnte nicht initialisiert werden");
                                    return 1;
                                }
                                lkf_getSatzartErrorHeadline (pScoringContext, LKF_FAC_ALL, 1024, buf);
                                fprintf (fp_warning, "%s\n", buf);
                            }
                            
                            if (!isKtr && pParameters->infofieldcount > 0)
                            {
                                lkf_setErrorFormat (pScoringContext, LKF_FAC_ALL, pParameters->infofieldcount, pParameters->infofields);
                                lkf_compose_filename (pScoringContext, ka, 'h', outputFileName);
                                sprintf (outputFilePath, "%s%s", pParameters->sOutputPath, outputFileName);
                                
                                fp_hinweis = fopen (outputFilePath, "w");
                                if (!fp_hinweis) {
                                    setFileError(error, outputFilePath, strerror(errno), "konnte nicht initialisiert werden");
                                    return 1;
                                }
                                lkf_getSatzartErrorHeadline (pScoringContext, LKF_FAC_ALL, 1024, buf);
                                fprintf (fp_hinweis, "%s\n", buf);
                            }
                            
                            if (!(pParameters->modus & FLAG_MODUS_MELDEDIAG_FILE_OFF))
                            {
                                lkf_compose_filename (pScoringContext, ka, 'm', meldediag_outputFileName);
                                sprintf (outputFilePath, "%s%s", pParameters->sOutputPath, meldediag_outputFileName);
                                
                                fp_meldediag = fopen(outputFilePath, "w");
                                if (!fp_meldediag) {
                                    setFileError(error, outputFilePath, strerror(errno), "konnte nicht initialisiert werden");
                                    return 1;
                                }
                                lkf_plaus_WriteFileHeader (pScoringContext, fp_meldediag, LKF_FILE_MELDEDIAG, 0, meldediag_outputFileName, 0);
                            }

                            
                            if (!isKtr && (pParameters->modus & FLAG_MODUS_SCORING)) {
                                lkf_compose_filename (pScoringContext, ka, 's', outputFileName);
                                sprintf (outputFilePath, "%s%s", pParameters->sOutputPath, outputFileName);
                                
                                fp_output = fopen (outputFilePath, "w");
                                if (!fp_output) {
                                    setFileError(error, outputFilePath, strerror(errno), "konnte nicht initialisiert werden");
                                    return 1;
                                }
                                
                                nCount = lkf_getaddlineanz (pScoringContext);
                                for (i = 0; i < nCount; i++)
                                {
                                    lkf_getaddline (pScoringContext, i, buf);
                                    if (memcmp (buf, "K01", 3))
                                        continue;
                                    fprintf (fp_output, "%s\n", buf);
                                }
                            }
                        }
                    }
                    else
                    {
                        lkf_context_plaus_package (pScoringContext, 0);
                    }
                    
                    
                    errcount = lkf_context_GetErrorAnz (pScoringContext, 0, 0);
                    warncount = lkf_context_GetWarningAnz (pScoringContext, 0, 0);
                    meldediagcount = lkf_context_GetMeldeDiagAnz (pScoringContext, 0);
                    
                    printf ("%s: %6d Aufenthalte: %6d Errors, %6d Warnings, %6d meldepfl.Diag.\n", currentTimeBuf (timebuf), x01_sum_count, errcount, warncount, meldediagcount);
                    
                    
                    if (fp_error) {
                        lkf_setErrorFormat (pScoringContext, LKF_FAC_ALL, errorfieldcount, errorfields);
                        count = lkf_setErrorFilter (pScoringContext, LKF_ERRORFILTER_ALLERRORS);
                        
                        for (i = 0; i < count; i++)
                        {
                            lkf_getSatzartError (pScoringContext, i, 1024, buf);
                            fprintf (fp_error, "%s\n", buf);
                        }
                    }
                    
                    if (fp_warning) {
                        lkf_setErrorFormat (pScoringContext, LKF_FAC_ALL, warningfieldcount, warningfields);
                        count = lkf_setErrorFilter (pScoringContext, LKF_ERRORFILTER_ALLWARNINGS);
                        
                        for (i = 0; i < count; i++)
                        {
                            lkf_getSatzartError (pScoringContext, i, 1024, buf);
                            fprintf (fp_warning, "%s\n", buf);
                        }
                    }
                    
                    if (fp_hinweis) {
                        lkf_setErrorFormat (pScoringContext, LKF_FAC_ALL, pParameters->infofieldcount, pParameters->infofields);
                        count = lkf_setErrorFilter (pScoringContext, LKF_ERRORFILTER_ALLINFOS);
                        
                        for (i = 0; i < count; i++)
                        {
                            lkf_getSatzartError (pScoringContext, i, 1024, buf);
                            fprintf (fp_hinweis, "%s\n", buf);
                        }
                    }
                    
                    if (fp_meldediag) {
                        LKF_ERROR_LIST *pMeldeDiag;
                        for (i = 0; i < x01_count; i++) {
                            
                            pAufenthalt = lkf_get_aufenthalt(pScoringContext, i);
                            
                            if (!pAufenthalt)
                                continue; /* V22.2 */
                            
                            pMeldeDiag = lkf_auf_firstmeldediag (pAufenthalt);
                                
                            while (pMeldeDiag) {
                                lkf_plaus_GetMeldeDiagText (pAufenthalt, pMeldeDiag, buf, 512);
                                pMeldeDiag = lkf_auf_nextmeldediag (pMeldeDiag);
                                fprintf (fp_meldediag, "%s\n", buf);
                            }
                        }
                    }
                    
                    if (fp_output) {
                        int ret = lkf_context_scoring(pScoringContext, 0);
                        if (ret < 0)
                        {
                            strcpy (error, lkf_context_get_errortext (pScoringContext));
                            lkf_free_context (pScoringContext);
                            return 5;
                        }

                        sum_punkte_inlkf = lkf_get_context_scorvalue (pScoringContext, 0, SCORFIELD_SCGES_INLKF_TKL);
                        sum_punkte_exlkf = lkf_get_context_scorvalue (pScoringContext, 0, SCORFIELD_SCGES_EXLKF_TKL);

                        sum_punkte_stat = lkf_get_context_scorvalue(pScoringContext, 0, SCORFIELD_SCGES_STAT);
                        sum_punkte_amb = lkf_get_context_scorvalue(pScoringContext, 0, SCORFIELD_SCGES_AMB);

                        printf ("%s: %6d Aufenthalte: %11.0f LKF-Punkte (sonstige Punkte: %11.0f)", currentTimeBuf (timebuf), x01_sum_count, sum_punkte_inlkf, sum_punkte_exlkf);

                        if (sum_punkte_stat != 0 && sum_punkte_amb != 0)
                            printf (", %11.0f stationaere Punkte, %11.0f ambulante Punkte\n", sum_punkte_stat, sum_punkte_amb);
                        else
                            printf ("\n");
                        nAufenthaltAnz = lkf_get_aufenthalt_anz (pScoringContext);
                        
                        for (i = 0; i < nAufenthaltAnz; i++) {
                            pAufenthalt = lkf_get_aufenthalt (pScoringContext, i);
                            if (lkf_auf_is_marked(pAufenthalt))
                            {
                                nCount = lkf_auf_getlineanz (pAufenthalt);
                                for (j = 0; j < nCount; j++) {
                                    lkf_auf_getline (pAufenthalt, j, buf);
                                    fprintf (fp_output, "%s\n", buf);
                                }
                                
                                nCount = lkf_auf_getintlineanz (pAufenthalt);
                                for (j = 0; j < nCount; j++)
                                {
                                    lkf_auf_getintline (pAufenthalt, j, buf);
                                    fprintf (fp_output, "%s\n", buf);
                                }
                            }
                        }
                    }
                    
                    if (pParameters->modus & FLAG_MODUS_STAT)
                    {
                        if (firstPackage)
                            lkf_stat (pScoringContext);
                        else
                            lkf_stat_package (pScoringContext);
                    }
                    
                    
                    firstPackage = 0;
                    lkf_reset_aufenthalt_package (pScoringContext);
                    x01_count = 0;
                    
                    if (lastLine == 0)
                        break;
                }
                
                if (lkf_add_line(pScoringContext, line) == 0) {
                    ++x01_count;
                    ++x01_sum_count;
                }
            }
            else {
                lkf_add_line (pScoringContext, line);
            }
            
        }
        else if (firstPackage)
        {
            lkf_add_line (pScoringContext, line);
        }
    }
    
    fclose (fp_input);
    
    if (x01_count > 0) {
        lkf_context_plaus_package(pScoringContext, 0);

        errcount = lkf_context_GetErrorAnz (pScoringContext, 0, 0);
        warncount = lkf_context_GetWarningAnz (pScoringContext, 0, 0);
        meldediagcount = lkf_context_GetMeldeDiagAnz (pScoringContext, 0);

        printf ("%s: %6d Aufenthalte: %6d Errors, %6d Warnings, %6d meldepfl.Diag.\n", currentTimeBuf (timebuf), x01_sum_count, errcount, warncount, meldediagcount);

        if (fp_error) {
            lkf_setErrorFormat (pScoringContext, LKF_FAC_ALL, errorfieldcount, errorfields);
            count = lkf_setErrorFilter (pScoringContext, LKF_ERRORFILTER_ALLERRORS);
            
            for (i = 0; i < count; i++)
            {
                lkf_getSatzartError (pScoringContext, i, 1024, buf);
                fprintf (fp_error, "%s\n", buf);
            }
        }
        
        if (fp_warning) {
            lkf_setErrorFormat (pScoringContext, LKF_FAC_ALL, warningfieldcount, warningfields);
            count = lkf_setErrorFilter (pScoringContext, LKF_ERRORFILTER_ALLWARNINGS);
            
            for (i = 0; i < count; i++)
            {
                lkf_getSatzartError (pScoringContext, i, 1024, buf);
                fprintf (fp_warning, "%s\n", buf);
            }
        }
        
        if (fp_hinweis) {
            lkf_setErrorFormat (pScoringContext, LKF_FAC_ALL, pParameters->infofieldcount, pParameters->infofields);
            count = lkf_setErrorFilter (pScoringContext, LKF_ERRORFILTER_ALLINFOS);
            
            for (i = 0; i < count; i++)
            {
                lkf_getSatzartError (pScoringContext, i, 1024, buf);
                fprintf (fp_hinweis, "%s\n", buf);
            }
        }
        
        if (fp_meldediag) {
            LKF_ERROR_LIST *pMeldeDiag;
            for (i = 0; i < x01_count; i++) {
                
                pAufenthalt = lkf_get_aufenthalt(pScoringContext, i);
                
                pMeldeDiag = lkf_auf_firstmeldediag (pAufenthalt);
                
                while (pMeldeDiag) {
                    lkf_plaus_GetMeldeDiagText (pAufenthalt, pMeldeDiag, buf, 512);
                    pMeldeDiag = lkf_auf_nextmeldediag (pMeldeDiag);
                    fprintf (fp_meldediag, "%s\n", buf);
                }
            }
            lkf_plaus_WriteFileFooter (pScoringContext, fp_meldediag, LKF_FILE_MELDEDIAG, 0, meldediag_outputFileName, 0);
            
            fclose (fp_meldediag);
        }
        
        if (fp_output) {
            int ret = lkf_context_scoring(pScoringContext, 0);
            if (ret < 0)
            {
                strcpy (error, lkf_context_get_errortext (pScoringContext));
                lkf_free_context (pScoringContext);
                return 5;
            }
            
            sum_punkte_inlkf = lkf_get_context_scorvalue (pScoringContext, 0, SCORFIELD_SCGES_INLKF_TKL);
            sum_punkte_exlkf = lkf_get_context_scorvalue (pScoringContext, 0, SCORFIELD_SCGES_EXLKF_TKL);
            
            sum_punkte_stat = lkf_get_context_scorvalue(pScoringContext, 0, SCORFIELD_SCGES_STAT);
            sum_punkte_amb = lkf_get_context_scorvalue(pScoringContext, 0, SCORFIELD_SCGES_AMB);
            
            printf ("%s: %6d Aufenthalte: %11.0f LKF-Punkte (sonstige Punkte: %11.0f)", currentTimeBuf (timebuf), x01_sum_count, sum_punkte_inlkf, sum_punkte_exlkf);
            
            if (sum_punkte_stat != 0 && sum_punkte_amb != 0)
                printf (", %11.0f stationaere Punkte, %11.0f ambulante Punkte\n", sum_punkte_stat, sum_punkte_amb);
            else
                printf ("\n");
            
            nAufenthaltAnz = lkf_get_aufenthalt_anz (pScoringContext);
            
            for (i = 0; i < nAufenthaltAnz; i++) {
                pAufenthalt = lkf_get_aufenthalt (pScoringContext, i);
                if (lkf_auf_is_marked(pAufenthalt))
                {
                    nCount = lkf_auf_getlineanz (pAufenthalt);
                    for (j = 0; j < nCount; j++) {
                        lkf_auf_getline (pAufenthalt, j, buf);
                        fprintf (fp_output, "%s\n", buf);
                    }
                    
                    nCount = lkf_auf_getintlineanz (pAufenthalt);
                    for (j = 0; j < nCount; j++)
                    {
                        lkf_auf_getintline (pAufenthalt, j, buf);
                        fprintf (fp_output, "%s\n", buf);
                    }
                }
            }
        }
    
        if (pParameters->modus & FLAG_MODUS_STAT)
        {
            if (firstPackage)
                lkf_stat (pScoringContext);
            else
                lkf_stat_package (pScoringContext);
        }
    
        lkf_reset_aufenthalt_package(pScoringContext);
    }
    
    lkf_check_nombds (pScoringContext, 0);
    kerr = lkf_context_getSatzartErrorAnz (pScoringContext, LKF_SEV_FATAL | LKF_SEV_ERROR);
    kwarn = lkf_context_getSatzartErrorAnz (pScoringContext, LKF_SEV_WARNING);
    
    errcount += kerr;
    warncount += kwarn;
    printf ("Sonstige Checks:    %6d Errors, %6d Warnings\n", kerr, kwarn);
    printf ("%6d Aufenthalte: %6d Errors, %6d Warnings, %6d meldepfl.Diag.\n", x01_sum_count, errcount, warncount, meldediagcount);

    
    if (fp_error) {
        lkf_setErrorFormat (pScoringContext, LKF_FAC_ALL, errorfieldcount, errorfields);
        count = lkf_setErrorFilter (pScoringContext, LKF_ERRORFILTER_ALLERRORS);
        
        for (i = 0; i < count; i++)
        {
            lkf_getSatzartError (pScoringContext, i, 1024, buf);
            fprintf (fp_error, "%s\n", buf);
        }
        fclose (fp_error);
    }
    
    if (fp_warning) {
        lkf_setErrorFormat (pScoringContext, LKF_FAC_ALL, warningfieldcount, warningfields);
        count = lkf_setErrorFilter (pScoringContext, LKF_ERRORFILTER_ALLWARNINGS);
        
        for (i = 0; i < count; i++)
        {
            lkf_getSatzartError (pScoringContext, i, 1024, buf);
            fprintf (fp_warning, "%s\n", buf);
        }
        
        fclose (fp_warning);
    }
    
    if (fp_hinweis) {
        lkf_setErrorFormat (pScoringContext, LKF_FAC_ALL, pParameters->infofieldcount, pParameters->infofields);
        count = lkf_setErrorFilter (pScoringContext, LKF_ERRORFILTER_ALLINFOS);
        
        for (i = 0; i < count; i++)
        {
            lkf_getSatzartError (pScoringContext, i, 1024, buf);
            fprintf (fp_hinweis, "%s\n", buf);
        }
        
        fclose (fp_hinweis);
    }
    
    
    if (fp_output) {
        nCount = lkf_getaddlineanz (pScoringContext);
        for (i = 0; i < nCount; i++)
        {
            lkf_getaddline (pScoringContext, i, buf);
            if (!memcmp (buf, "K01", 3))
                continue;
            fprintf (fp_output, "%s\n", buf);
        }
        fclose (fp_output);
    }
    
    return 0;
}

int main (int argc, char *argv[])
{
	int ret;
	
	LKF_SCORING_PARAMETERS Parameters; /* V8.1: Aufruf-Parameter */
	FILE *fp;


	char input_file[512];		/* Input-File */
	char ausgabe_file[256];		/* Buffer zur Speicherung des in Warning/Error-File vermerkten Ausgabefiles */
	char fn2[20];

	char error[1024];
	char buf[1024];

	LKF_CONTEXT *pScoringContext;  /* Scoring-Context */
	unsigned int i, aufanz, ka_anz = 0, auf_filter_anz, details_anz, j;
		
	const char *ka = 0;
	char ka_name[32]; /* V14.2:  24->32 */

    double sum_punkte_inlkf = 0, sum_punkte_exlkf = 0, sum_punkte_stat = 0, sum_punkte_amb = 0;
	
	unsigned int count = 0, errcount = 0, warncount = 0;
	unsigned int meldediagcount = 0;

	unsigned int hinweiscount;
    
    int isKtr = 0;
    int isBM;

    char search_path[260];
#ifndef LKF_DISABLE_IO
#ifdef __APPLE__
    DIR *dp = 0;
    struct dirent *ep;
#else
	struct _finddata_t filepath;
#endif
#endif
    
	long filepath_handler;

	memset (&Parameters, 0, sizeof (LKF_SCORING_PARAMETERS));
	

	Parameters.ktrerrorfields = ktrfields;
	Parameters.ktrerrorfieldcount = sizeof(ktrfields) / sizeof(unsigned int); /* V14.2 */
	Parameters.ktrwarningfields = ktrfields;
	Parameters.ktrwarningfieldcount = sizeof(ktrfields) / sizeof(unsigned int); /* V14.2 */
	/* PARAMETERUEBERPRUEFUNG ****************************************************************
	**     Parameter 1:   P nur Plaus, S nur Scoring, PS Plaus und Scoring,                 **
	**                    PSN Plaus und Scoring, kein Plaus-File wird erzeugt               **
	**     Parameter 2:   Stammdaten-Directory [PC, UNIX: inkl. (Back-)Slash am Ende]       **
	**     Parameter 3:   Eingabedatei                                                      **
	**     Parameter 4:   Periode im Format <Abrechnungsjahr><Typ><Wert><lfdNr>             **
	**                    <Abrechnungsjahr> 4stellig; <Typ> J fuer Jahr, H fuer Halbjahr,     **
	**                    Q fuer Quartal, M fuer Monat, T fuer Tag; <Wert> 3stellig, gueltige   **
	**                    Werte: 1 fuer J, 1-2 fuer H, 1-4 fuer Q, 1-12 fuer Monat, 1-365 fuer   **
	**                    Tag (366 wenn <Abrechnungsjahr> ein Schaltjahr ist); <lfdNr> wird **
	**                    bei Plaus direkt in Satzart 2 uebernommen.                         **
	**     Parameter 5:   Ausgabe-Pfad (PC, UNIX: inkl. (Back-)Slash am Ende)               **
	*****************************************************************************************/

	if (argc == 3)
	{ /* V12.1 */
		if (parse_commandfile (argv[1], argv[2], &Parameters))
			return 1;
	}
	else if (parse_commandline (argc, argv, &Parameters))
		return 1; 

    if (!strcmp (Parameters.sInputPath, "errorlist")) {
        printf ("\nErrorliste nach LKF-Modell %d", Parameters.modelljahr);
        pScoringContext = lkf_alloc_context (Parameters.modelljahr, Parameters.sStammPath, error);

        if (!pScoringContext) {
            fprintf(stderr, "%s", error);
            exit(1);
        }
        
        lkf_set_contextflags(pScoringContext, Parameters.flags); /* V21.0: FIX: UTF8-Flag auch bei Errorlist anwenden */
        
        sprintf (ausgabe_file, "%ssatzart%4d.csv", Parameters.sOutputPath, Parameters.modelljahr);
        WriteSatzartInfoFile(pScoringContext, ausgabe_file);

        sprintf (ausgabe_file, "%serrorlist%4d.csv", Parameters.sOutputPath, Parameters.modelljahr);
        WriteErrorlistFile(pScoringContext, ausgabe_file);

        exit(0);
    }

    if (Parameters.modus == FLAG_MODUS_ANONYMIZE) {
        printf ("\nAnonymisierung (Import nach LKF-Modell %d)", Parameters.modelljahr);
    }
    else {
        printf ("\nAbrechnung nach LKF-Modell %d", Parameters.modelljahr);
    }
	
	if (Parameters.modelljahr < 2015) {
        isBM = 0;
    }
    else if (Parameters.flags & LKFCONTEXT_MODUS_BMG) {
        printf("\nMODUS BM\n");
        isBM = 1;
    }
    else {
        isBM = 0;
    }
    
    if (Parameters.modelljahr >= 2017 && !Parameters.fmt_err_pre2017) {
        if (!Parameters.errorfields) {
            if (isBM) {
                Parameters.errorfields = errorfieldsBM2017;
                Parameters.errorfieldcount = sizeof(errorfieldsBM2017)/sizeof (unsigned int);
            }
            else {
                Parameters.errorfields = errorfields2017;
                Parameters.errorfieldcount = sizeof(errorfields2017)/sizeof (unsigned int);
            }
        }
        
        if (!Parameters.warningfields) {
            if (isBM) {
                Parameters.warningfields = warningfieldsBM2017;
                Parameters.warningfieldcount = sizeof(warningfieldsBM2017)/sizeof (unsigned int);
            }
            else {
                Parameters.warningfields = warningfields2017;
                Parameters.warningfieldcount = sizeof(warningfields2017)/sizeof (unsigned int);
            }
        }
        
        if (!Parameters.infofields) {
            if (isBM) {
                Parameters.infofields = infofieldsBM2017;
                Parameters.infofieldcount = sizeof(infofieldsBM2017) / sizeof(unsigned int); /* V13.0 */
            }
            else {
                Parameters.infofields = infofields2017;
                Parameters.infofieldcount = sizeof(infofields2017) / sizeof(unsigned int); /* V13.0 */
            }
        }
        
        if (Parameters.fmt_add_posfield) {
            unsigned int *original;
            original = Parameters.infofields;
            Parameters.infofields = (unsigned int *) malloc(sizeof (unsigned int) * Parameters.infofieldcount + 1);
            memcpy (Parameters.infofields, original, sizeof (unsigned int) * Parameters.infofieldcount);
            Parameters.infofields[Parameters.infofieldcount++] = CHECKFIELD_CHILD_IDENT;

            original = Parameters.warningfields;
            Parameters.warningfields = (unsigned int *) malloc(sizeof (unsigned int) * Parameters.warningfieldcount + 1);
            memcpy (Parameters.warningfields, original, sizeof (unsigned int) * Parameters.warningfieldcount);
            Parameters.warningfields[Parameters.warningfieldcount++] = CHECKFIELD_CHILD_IDENT;

            original = Parameters.errorfields;
            Parameters.errorfields = (unsigned int *) malloc(sizeof (unsigned int) * Parameters.errorfieldcount + 1);
            memcpy (Parameters.errorfields, original, sizeof (unsigned int) * Parameters.errorfieldcount);
            Parameters.errorfields[Parameters.errorfieldcount++] = CHECKFIELD_CHILD_IDENT;
        }
    }
    else {
        if (!Parameters.errorfields) {
            if (isBM) {
                Parameters.errorfields = errorfieldsBM;
                Parameters.errorfieldcount = sizeof(errorfieldsBM)/sizeof (unsigned int);
            }
            else {
                Parameters.errorfields = errorfields2016;
                Parameters.errorfieldcount = sizeof(errorfields2016)/sizeof (unsigned int);
            }
        }
        
        if (!Parameters.warningfields) {
            if (isBM) {
                Parameters.warningfields = warningfieldsBM;
                Parameters.warningfieldcount = sizeof(warningfieldsBM)/sizeof (unsigned int);
            }
            else {
                Parameters.warningfields = warningfields;
                Parameters.warningfieldcount = sizeof(warningfields)/sizeof (unsigned int);
            }
        }
        
        if (!Parameters.infofields) {
            if (isBM) {
                Parameters.infofields = infofieldsBM;
                Parameters.infofieldcount = sizeof(infofieldsBM) / sizeof(unsigned int); /* V13.0 */
            }
            else {
                Parameters.infofields = infofields;
                Parameters.infofieldcount = sizeof(infofields) / sizeof(unsigned int); /* V13.0 */
            }
        }
    }
    
    
    printf ("\nStammdatenDir : %s", Parameters.sStammPath);
	printf ("\nFile-Path : %s", Parameters.sOutputPath);

	printf ("\nAbrechnungsjahr: %d", Parameters.cmb_jahr);
	printf ("\nPeriodentyp: %c", Parameters.period_type);
	printf ("\nPeriodenwert: %d", Parameters.period_val);
	printf ("\nlfd. Nr.: %d\n\n", Parameters.lfdnr);

	filepath_handler = -1;

#ifndef LKF_DISABLE_IO
	if (Parameters.modus & FLAG_MODUS_PATH) {

        sprintf (search_path, "%s", Parameters.sInputPath);
#ifdef __APPLE__
        dp = opendir(search_path);
        if (dp) {
            do {
                ep = readdir (dp);
            } while (ep && ep->d_type != DT_REG);
        }
        else {
            ep = 0;
        }
        
        if (!ep) {
            if (dp) {
                closedir(dp);
            }
            printf ("Mit Suchstring '%s' wurde kein File gefunden!\n", search_path);
            return 1;
        }
        else {
            sprintf (search_path, "%s*.*", Parameters.sInputPath);
            sprintf (input_file, "%s%s", Parameters.sInputPath, ep->d_name);
            filepath_handler = 1;
        }
#else
		printf ("\nInput-Path: %s\n\n", Parameters.sInputPath);

		filepath_handler = (long) _findfirst (search_path, &filepath);
		
		if (filepath_handler != -1 && filepath.attrib != _A_SUBDIR) {
			_findclose(filepath_handler);
			filepath_handler = -1;
		}

		while (filepath_handler != -1 && filepath.attrib == _A_SUBDIR) {
			if (_findnext (filepath_handler, &filepath) == -1) filepath_handler = -1;
		}

		if (filepath_handler == -1) {
			printf ("Mit Suchstring '%s' wurde kein File gefunden!\n", search_path);
			return 1;
		}
		else {
			sprintf (input_file, "%s%s", Parameters.sInputPath, filepath.name);
		}
#endif
	}
	else {
		strcpy (input_file, Parameters.sInputPath);
	}
#else
    strcpy (input_file, Parameters.sInputPath);
#endif

	do {

		printf ("\nInputfile : %s\n\n", input_file);

		pScoringContext = lkf_alloc_context (Parameters.modelljahr, Parameters.sStammPath, error);

		if (!pScoringContext) {
			printf ("FEHLER beim Einlesen der Scoring-Stammdaten:\n");
			printf ("  -> %s\n", error);
			return 2;
		}

		if (Parameters.lkf_compatibility) lkf_set_compatibilitymode (pScoringContext, Parameters.lkf_compatibility); 

		if ((Parameters.int_modus & FLAG_INTMODUS_AKTIV) && (Parameters.flags & LKFCONTEXT_NUR_MBDS)) 
			Parameters.flags |= LKFCONTEXT_INTENSIV; /* V14.0 */

		lkf_set_contextparameters (pScoringContext, Parameters.cmb_jahr, Parameters.period_val, Parameters.lfdnr, Parameters.period_type, Parameters.flags);

		/* Custom Output Line */
		if (Parameters.modus & FLAG_MODUS_SCOR_FORMAT_C) {
			lkf_define_custom_line (pScoringContext, Parameters.field_anz, Parameters.field, 0, 'x');
		}
		else if (Parameters.modus & FLAG_MODUS_SCOR_FORMAT_CX) {
			lkf_define_custom_line (pScoringContext, Parameters.field_anz, Parameters.field, 1, 'x');
		}
        
        if (Parameters.packageSize > 0) {
            *error = 0;
            if (handle_packaged_execution (input_file, pScoringContext, &Parameters, error)) {
                printf ("FEHLER: %s\n", error);
                return 1;
            }
            ka = lkf_get_context_ka (pScoringContext, 0, &aufanz, &auf_filter_anz);
            if (!ka) ka = "K000";
            lkf_KA_to_Name (pScoringContext, ka, ka_name);
            
            if (Parameters.modus & FLAG_MODUS_ABT_FILE)
            {
                lkf_compose_filename (pScoringContext, ka, 'a', fn2);
                sprintf (ausgabe_file, "%s%s", Parameters.sOutputPath, fn2);
                lkf_write_abtfile (ausgabe_file, pScoringContext, 0, 0, error);
            }

        }
        else {
            printf ("**** Einlesen der Input-Datei ****\n");
            ret = lkf_read_inputfile (input_file, pScoringContext, error);
            
            if (ret) {
                
                printf ("FEHLER beim Einlesen der Input-Datei:\n");
                printf ("  -> %s\n", error);
                return 4;
            }
            
            /* Ermittlung der Anzahl Aufenthalte in der Input-Datei */
            aufanz = lkf_get_aufenthalt_anz (pScoringContext);
            
            if (!aufanz) {
                printf ("Die Input-Datei besteht aus keinem einzigen Patienten!\n");
                auf_filter_anz = 0; /* V18.1 */
            }
            else {
                printf ("%d Aufenthalte eingelesen.\n", aufanz);
                
                /* Filterung */
                if (Parameters.pFilter) {
                    count = lkf_context_filter (pScoringContext, Parameters.pFilter, 0);
                    printf ("%d Aufenthalte nach Filterung.\n", count);
                    lkf_filter_drop (Parameters.pFilter);
                }
                
                ka_anz = lkf_get_context_ka_anz (pScoringContext);
                
                printf ("\n");
                ka = lkf_get_context_ka (pScoringContext, 0, &aufanz, &auf_filter_anz);
                if (!ka) ka = "K000";
                lkf_KA_to_Name (pScoringContext, ka, ka_name);
                
                
                if (auf_filter_anz != aufanz)
                    printf ("%4s %-20s %6d von %6d Aufenthalt(en)\n", ka, ka_name, auf_filter_anz, aufanz);
                else printf ("%4s %-20s %6d Aufenthalt(e)\n", ka, ka_name, aufanz);
                
                printf ("\n");
            }
            
            if (Parameters.modus == FLAG_MODUS_ANONYMIZE) {
                LKF_ANONYMISATION_CONTEXT *pAContext;
                LKF_CONTEXT *pTargetContext;
                unsigned int i;
                pTargetContext = lkf_alloc_context(Parameters.modelljahr, Parameters.sInputPath, error);
                pAContext = lkf_create_anonymisation_context(pTargetContext, Parameters.anonymizationParameters);
                lkf_copy_addlines (pTargetContext, pScoringContext, 1);
                for (i = 0; i < aufanz; i++) {
                    lkf_anonymisation_add_aufenthalt(pAContext, lkf_get_aufenthalt(pScoringContext, i));
                }
                ka = lkf_get_context_ka (pScoringContext, 0, &aufanz, &auf_filter_anz);
                if (!ka) ka = "K000"; /* V12.1 */

                lkf_compose_filename (pScoringContext, ka, 'd', fn2);
                sprintf (ausgabe_file, "%s%s", Parameters.sOutputPath, fn2);
                printf ("Output-File: %s\n", ausgabe_file);
                lkf_write_datafile(pTargetContext, ausgabe_file, 0, 0);
                lkf_free_anonymisation_context(pAContext);
                lkf_free_context(pTargetContext);
                lkf_free_context (pScoringContext);
                exit(0); // path not implemented yet => exit
            }
            
            printf ("**** Plausibilitaets-Ueberpruefung ****\n");
            
            ret = (int) lkf_check (pScoringContext, 0);
            
            if (ret)
            { /* V12.1 - Plaus-Check-Fehler reporten */
                printf ("CHECK-FEHLER %04X: %s\n", ret, lkf_context_get_errortext (pScoringContext));
            }
            
            isKtr = lkf_context_GetGlobalInfo (pScoringContext, LKF_CONTEXTINFO_KTR);
            
            
            errcount = lkf_context_GetErrorAnz (pScoringContext, 0, 0);
            warncount = lkf_context_GetWarningAnz (pScoringContext, 0, 0);
            meldediagcount = lkf_context_GetMeldeDiagAnz (pScoringContext, 0);
            
            count = lkf_context_get_plaused_anz (pScoringContext,0);
            printf ("%6d Aufenthalte: %6d Errors, %6d Warnings, %6d meldepfl.Diag.\n", count, errcount, warncount, meldediagcount);
            
            /* V13.0 */
            hinweiscount = lkf_context_GetHinweisAnz (pScoringContext, 0, 0);
            if (hinweiscount > 0)
                printf ("                    %6d Hinweis(e)\n", hinweiscount);
            
            if (ret < 0) {
                printf ("  %s\n", lkf_context_get_errortext (pScoringContext));
                lkf_free_context (pScoringContext);
                return 4;
            }
            
            if (Parameters.modus & FLAG_MODUS_ERROR_FILE) {
                
                unsigned int errorfieldcount = isKtr ? Parameters.ktrerrorfieldcount : Parameters.errorfieldcount;
                unsigned int warningfieldcount = isKtr ? Parameters.ktrwarningfieldcount : Parameters.warningfieldcount;
                
                ka = lkf_get_context_ka (pScoringContext, 0, &aufanz, &auf_filter_anz);
                
                if (!auf_filter_anz && aufanz) continue; /* V18.1 */
                
                if (!ka) ka = "K000"; /* V12.1 */
                
                if (Parameters.modus & FLAG_MODUS_ABT_FILE)
                {
                    lkf_compose_filename (pScoringContext, ka, 'a', fn2);
                    sprintf (ausgabe_file, "%s%s", Parameters.sOutputPath, fn2);
                    lkf_write_abtfile (ausgabe_file, pScoringContext, 0, 0, error);
                }
                
                
                if (Parameters.modelljahr < 2004 || (Parameters.private_compatibility & 256))
                {
                    lkf_compose_filename (pScoringContext, ka, 'e', fn2);
                    sprintf (ausgabe_file, "%s%s", Parameters.sOutputPath, fn2);
                    lkf_write_errorfile (ausgabe_file, pScoringContext, 0, 0, input_file, fn2, error);
                    
                    lkf_compose_filename (pScoringContext, ka, 'w', fn2);
                    sprintf (ausgabe_file, "%s%s", Parameters.sOutputPath, fn2);
                    lkf_write_errorfile (ausgabe_file, pScoringContext, 0, 1, input_file, fn2, error);
                }
                else {
                    /* V8.1: Schreibe Error-File */
                    
                    if (errorfieldcount > 0)
                    {
                        
                        lkf_setErrorFormat (pScoringContext, LKF_FAC_ALL, errorfieldcount, isKtr ? Parameters.ktrerrorfields : Parameters.errorfields);
                        lkf_compose_filename (pScoringContext, ka, 'e', fn2);
                        sprintf (ausgabe_file, "%s%s", Parameters.sOutputPath, fn2);
                        count = lkf_setErrorFilter (pScoringContext, LKF_ERRORFILTER_ALLERRORS);
                        
                        fp = fopen (ausgabe_file, "w");
                        if (fp)
                        {
                            lkf_getSatzartErrorHeadline (pScoringContext, LKF_FAC_ALL, 1024, buf);
                            fprintf (fp, "%s\n", buf);
                            
                            for (i = 0; i < count; i++)
                            {
                                lkf_getSatzartError (pScoringContext, i, 1024, buf);
                                fprintf (fp, "%s\n", buf);
                            }
                            fclose (fp);
                        }
                    }
                    
                    /* V8.1: Schreibe Warning-File */
                    
                    if (warningfieldcount > 0)
                    {
                        lkf_setErrorFormat (pScoringContext, LKF_FAC_ALL, warningfieldcount, isKtr ? Parameters.ktrwarningfields : Parameters.warningfields);
                        lkf_compose_filename (pScoringContext, ka, 'w', fn2);
                        sprintf (ausgabe_file, "%s%s", Parameters.sOutputPath, fn2);
                        count = lkf_setErrorFilter (pScoringContext, LKF_ERRORFILTER_ALLWARNINGS);
                        fp = fopen (ausgabe_file, "w");
                        if (fp)
                        {
                            lkf_getSatzartErrorHeadline (pScoringContext, LKF_FAC_ALL, 1024, buf);
                            fprintf (fp, "%s\n", buf);
                            
                            for (i = 0; i < count; i++)
                            {
                                lkf_getSatzartError (pScoringContext, i, 1024, buf);
                                fprintf (fp, "%s\n", buf);
                            }
                            fclose (fp);
                        }
                    }
                    
                    if (!isKtr && Parameters.infofieldcount > 0)
                    {
                        lkf_setErrorFormat (pScoringContext, LKF_FAC_ALL, Parameters.infofieldcount, Parameters.infofields);
                        lkf_compose_filename (pScoringContext, ka, 'h', fn2);
                        sprintf (ausgabe_file, "%s%s", Parameters.sOutputPath, fn2);
                        count = lkf_setErrorFilter (pScoringContext, LKF_ERRORFILTER_ALLINFOS);
                        fp = fopen (ausgabe_file, "w");
                        if (fp)
                        {
                            lkf_getSatzartErrorHeadline (pScoringContext, LKF_FAC_ALL, 1024, buf);
                            fprintf (fp, "%s\n", buf);
                            
                            for (i = 0; i < count; i++)
                            {
                                lkf_getSatzartError (pScoringContext, i, 1024, buf);
                                fprintf (fp, "%s\n", buf);
                            }
                            fclose (fp);
                        }
                    }
                }
            }
        }
        
        if (Parameters.modus & FLAG_MODUS_ERROR_FILE) {

            if (Parameters.packageSize == 0 && !(Parameters.modus & FLAG_MODUS_MELDEDIAG_FILE_OFF))
            {
                lkf_compose_filename (pScoringContext, ka, 'm', fn2);
                sprintf (ausgabe_file, "%s%s", Parameters.sOutputPath, fn2);
				lkf_write_meldediagfile (ausgabe_file, pScoringContext, 0, error); /* V9.2 */
			}

			if (!(Parameters.modus & FLAG_MODUS_ERRSUM_FILE_OFF))
			{
				lkf_compose_filename (pScoringContext, 0, 'e', fn2);
				sprintf (ausgabe_file, "%s%s", Parameters.sOutputPath, fn2);
				lkf_write_errsumfile (ausgabe_file, pScoringContext, 0, error);
			}
			if (!(Parameters.modus & FLAG_MODUS_WARNSUM_FILE_OFF))
			{
				lkf_compose_filename (pScoringContext, 0, 'w', fn2);
				sprintf (ausgabe_file, "%s%s", Parameters.sOutputPath, fn2);
				lkf_write_errsumfile (ausgabe_file, pScoringContext, 1, error);
			}
        }
        
		if (Parameters.modus & FLAG_MODUS_NPPLAUS_TRACE) 
		{
			ka = lkf_get_context_ka (pScoringContext, 0, 0, 0);
			if (ka) 
			{
				FILE *npplaus_file;
				unsigned int tfcount;
				sprintf (ausgabe_file, "%s%s_npp.csv", Parameters.sOutputPath, ka);
					
				npplaus_file = fopen (ausgabe_file, "w");
				if (npplaus_file) {
					lkf_npplaus_getProtokollHeadline (pScoringContext, buf, 1024);
					fprintf (npplaus_file, "%s\n", buf);
						
					count = lkf_npplaus_getWarningLineCount (pScoringContext);
					for (i = 0; i < count; i++) 
					{
						lkf_npplaus_getWarningLine (pScoringContext, i, buf, 1024);
						fprintf (npplaus_file, "%s\n", buf);
			
						/* V10.1 */
						lkf_npplaus_getInfoLine (pScoringContext, i, buf, 1024);
						fprintf (npplaus_file, "%s\n", buf);
					
						tfcount = lkf_npplaus_getReasonCount (pScoringContext, i);

						for (j = 0; j < tfcount; j++)
						{
							lkf_npplaus_getReasonLine (pScoringContext, i, j, buf, 1024);
							fprintf (npplaus_file, "%s\n", buf);
						}
					}

					count = lkf_npplaus_getProtokollLineCount (pScoringContext);
					for (i = 0; i < count; i++) 
					{
						lkf_npplaus_getProtokollLine (pScoringContext, i, buf, 1024);
						fprintf (npplaus_file, "%s\n", buf);
					}
							
					fclose (npplaus_file);
				}
			}
		}

		if (Parameters.modus & FLAG_MODUS_NPPLAUS_SUM)
		{ /* V12.1 */
			FILE *npplaus_sum;
			sprintf (ausgabe_file, "%s%s_nps.csv", Parameters.sOutputPath, ka);

			npplaus_sum = fopen (ausgabe_file, "w");	
			
			if (npplaus_sum)
			{
			
				if (lkf_npplaus_sum_headline (pScoringContext, buf, 512))
				fprintf (npplaus_sum, "%s\n", buf);

				count = lkf_npplaus_sum_abtcount (pScoringContext);

				for (i = 0; i < count; i++) {
					if (lkf_npplaus_sum_abtline (pScoringContext, i, buf, 512))
						fprintf (npplaus_sum, "%s\n", buf);
				}

				lkf_npplaus_tfsum_headline (pScoringContext, buf, 512);
				fprintf (npplaus_sum, "%s\n", buf);

				for (i = 0; i < count; i++)
				{
					lkf_npplaus_tfsum (pScoringContext, i, buf, 512);
					fprintf (npplaus_sum, "%s\n", buf);
				}

				lkf_npplaus_critsum_headline (pScoringContext, buf, 512);
				fprintf (npplaus_sum, "%s\n", buf);

				for (i = 0; i < count; i++)
				{
					lkf_npplaus_critsum (pScoringContext, i, buf, 512);
					fprintf (npplaus_sum, "%s\n", buf);
				}
				fclose (npplaus_sum);
			}
		}

		if (Parameters.packageSize <= 0 && !isKtr && (Parameters.modus & FLAG_MODUS_SCORING)) {

			unsigned int fno_inlkf, fno_exlkf;

            fno_inlkf = SCORFIELD_SCGES_INLKF_TKL;
            fno_exlkf = SCORFIELD_SCGES_EXLKF_TKL;

			printf ("\n**** LKF-Punkteberechnung ****\n");
			/* Scoring-Punkteberechnung */
			sum_punkte_inlkf = sum_punkte_exlkf = 0; /* V17.0 */

			while ((ret = lkf_context_scoring (pScoringContext, 1000))>0) 
			{
				sum_punkte_inlkf = lkf_get_context_scorvalue (pScoringContext, 0, fno_inlkf);
				sum_punkte_exlkf = lkf_get_context_scorvalue (pScoringContext, 0, fno_exlkf);
                sum_punkte_stat = lkf_get_context_scorvalue(pScoringContext, 0, SCORFIELD_SCGES_STAT);
                sum_punkte_amb = lkf_get_context_scorvalue(pScoringContext, 0, SCORFIELD_SCGES_AMB);

				count = lkf_context_get_scored_anz (pScoringContext, 0);
				printf ("%6d Aufenthalte: %11.0f LKF-Punkte (sonstige Punkte: %11.0f)", count, sum_punkte_inlkf, sum_punkte_exlkf);
                if (sum_punkte_stat != 0 && sum_punkte_amb != 0)
                    printf (", %11.0f stationaere Punkte, %11.0f ambulante Punkte\n", sum_punkte_stat, sum_punkte_amb);
                else
                    printf ("\n");
                
            }
			
			if (ret < 0) 
			{
				printf (" %s\n", lkf_context_get_errortext (pScoringContext));
				lkf_free_context (pScoringContext);
				return 5;
			}

			ka = lkf_get_context_ka (pScoringContext, 0, &aufanz, &auf_filter_anz);
			if (auf_filter_anz)
			{
				if (Parameters.modus & FLAG_MODUS_SCOR_FORMAT_NORM ||
					Parameters.modus & FLAG_MODUS_SCOR_FORMAT_C ||
					Parameters.modus & FLAG_MODUS_SCOR_FORMAT_CX) 
				{
					int flags;
					lkf_compose_filename (pScoringContext, ka, 's', fn2);
					sprintf (ausgabe_file, "%s%s", Parameters.sOutputPath, fn2);
					

					if (Parameters.modus & FLAG_MODUS_DATAOUT && !(Parameters.modus & (FLAG_MODUS_SCOR_FORMAT_C|FLAG_MODUS_SCOR_FORMAT_CX))) 
					{
						fp = fopen (ausgabe_file, "w");
						if (lkf_write_datafile (pScoringContext, ausgabe_file, 0, 0))
						{
							printf ("Output-Datafile %s konnte nicht geöffnet werden\n", ausgabe_file);
						}
					}
					else {
						if (!(Parameters.modus & FLAG_MODUS_SCOR_FORMAT_NORM)) flags = ~(1<<9);
						else flags = 0;
						lkf_write_file (ausgabe_file, pScoringContext, 0, flags, error); /* V9.2 */
					}	
				}

				if (Parameters.modus & FLAG_MODUS_SCOR_FORMAT_SV) 
				{
					lkf_compose_filename (pScoringContext, ka, 'v', fn2);
					sprintf (ausgabe_file, "%s%s", Parameters.sOutputPath, fn2);
					lkf_write_svnrfile (ausgabe_file, pScoringContext, 0, 0, error); /* V9.2 */
				}
			}
		}
        
        if (Parameters.packageSize <= 0)
        {
        
            printf ("\n**** ERGEBNIS (%d Aufenthalte) ****\n", count);
            if (Parameters.modus & FLAG_MODUS_PLAUS)
            {
                printf ("Plausibilitaets-Ueberpruefung: %3d Errors, %3d Warnings, %3d meldepfl.Diag.\n", errcount, warncount, meldediagcount);
                printf ("INSGESAMT:                     %3d Errors, %3d Warnings, %3d Hinweise\n", lkf_context_getSatzartErrorAnz(pScoringContext, LKF_SEV_ERROR | LKF_SEV_FATAL), lkf_context_getSatzartErrorAnz(pScoringContext, LKF_SEV_WARNING), lkf_context_getSatzartErrorAnz(pScoringContext, LKF_SEV_INFO));
            }
        }
        
		if (Parameters.packageSize <= 0 && !isKtr)
		{

            if (Parameters.modus & FLAG_MODUS_SCORING) {
                printf ("LKF-Punkteberechnung:          %.0f LKF-Punkte, %.0f sonstige Punkte\n", sum_punkte_inlkf, sum_punkte_exlkf);
                if (sum_punkte_stat != 0 && sum_punkte_amb != 0)
                    printf ("                               %.0f stationaere Punkte, %.0f ambulante Punkte\n", sum_punkte_stat, sum_punkte_amb);
            }
			if (Parameters.flags & LKFCONTEXT_OPTIMIZER) 
			{
				unsigned int anz, opt;
				double maxpt, perc, actpt;

				printf ("\n**** Optimizer Statistics ****\n");

				for (i = 0; i < ka_anz; i++) {
				
					ka = lkf_get_context_ka (pScoringContext, i, &aufanz, &auf_filter_anz);
					perc = lkf_get_context_ka_optimized (pScoringContext, i, &anz, &opt, &maxpt, &actpt);


					printf (" Krankenanstalt %4.4s:\n", ka);
					printf ("    Anzahl optimierbarer Aufenthalte:  %4d\n", anz);
					printf ("    Davon optimiert (max. Punkte):     %4d\n", opt);
					printf ("    Maximal erreichbare Punktezahl:    %.0f LKF-Punkte\n", maxpt);
					printf ("    Tatsaechlich erreichte Punktezahl: %.0f LKF-Punkte\n", actpt);
					printf ("        in Prozent des Maximalwerts:   %5.2f %%\n\n", perc*100);
				
				}
			}

			if (Parameters.int_modus & FLAG_INTMODUS_AKTIV) 
			{
				unsigned int anz;
				if (Parameters.int_modus & FLAG_INTMODUS_OUTPUT_EINSTUFUNG) {
					for (i = 0; i < Parameters.nIntAbtDatAnzahl; i++) 
					{
						if (Parameters.pIntAbtDef[i].ABTFC[0]) 
						{
							lkf_setIntAbtData (pScoringContext, Parameters.pIntAbtDef[i].ABTFC, Parameters.pIntAbtDef[i].nBetten);
						}
					}

					if (Parameters.IntEndDate[0] && Parameters.IntStartDate[0])
						lkf_int_setintcontextparameters (pScoringContext, Parameters.IntStartDate, Parameters.IntEndDate, 0, 0);
				}
				lkf_int_scoring (pScoringContext);

				ka = lkf_get_context_ka (pScoringContext, 0, 0, 0);
				lkf_compose_filename (pScoringContext, ka, 'i', fn2);
				sprintf (ausgabe_file, "%s%s", Parameters.sOutputPath, fn2);
				
				fp = fopen (ausgabe_file, "w");
				if (fp) 
				{
					anz = lkf_int_getAbtAnz (pScoringContext);

					if (Parameters.int_modus & FLAG_INTMODUS_OUTPUT_EINSTUFUNG) 
					{

						lkf_int_getAbtHeadline (pScoringContext, buf, 1024);
						fprintf (fp, "%s\n", buf);
						for (i = 0; i < anz; i++) 
						{
							lkf_int_getAbtData (pScoringContext, i, buf, 1024);
							fprintf (fp, "%s\n", buf);
						}
					}

					if (Parameters.int_modus & FLAG_INTMODUS_OUTPUT_ANALYSE) 
					{
						lkf_int_getAnalyseHeadline (pScoringContext, buf, 1024);
						fprintf (fp, "%s\n", buf);
						for (i = 0; i < anz; i++)
						{
							for (j = 1; j < 13; j++) 
							{
								if (lkf_int_getAnalyseData (pScoringContext, i, j, buf, 1024)) 
									fprintf (fp, "%s\n", buf);
							}
						}
					}

					if (Parameters.int_modus & FLAG_INTMODUS_OUTPUT_DETAILS) 
					{
						lkf_int_getIntAufenthaltDetailsHeadline (pScoringContext, buf, 1024);
						fprintf (fp, "%s\n", buf);
					
						anz = lkf_int_getIntAufenthaltCount (pScoringContext);
					
						for (i = 0; i < anz; i++) {

							if (Parameters.int_modus & FLAG_INTMODUS_INTAUF_DETAILS) 
							{
								lkf_int_getIntAufenthaltDetails (pScoringContext, i, buf, 1024);
								fprintf (fp, "%s\n", buf);
							}

							if (Parameters.int_modus & FLAG_INTMODUS_OUTPUT_SAPSII) 
							{
								details_anz = lkf_int_getIntAufenthaltSAPSCount (pScoringContext, i);
								for (j = 0; j < details_anz; j++) 
								{
									lkf_int_getIntAufenthaltSAPSDetails (pScoringContext, i, j, buf, 1024);
									fprintf (fp, "%s\n", buf);
								}
							}

							if (Parameters.int_modus & FLAG_INTMODUS_OUTPUT_TISS)
							{
								details_anz = lkf_int_getIntAufenthaltTISSCount (pScoringContext, i);
								for (j = 0; j < details_anz; j++) 
								{
									lkf_int_getIntAufenthaltTISSDetails (pScoringContext, i, j, buf, 1024);
									fprintf (fp, "%s\n", buf);
								}
							}

							if (Parameters.int_modus & FLAG_INTMODUS_OUTPUT_TRISS) 
							{
								details_anz = lkf_int_getIntAufenthaltTRISSCount (pScoringContext, i);
								for (j = 0; j < details_anz; j++) 
								{
									lkf_int_getIntAufenthaltTRISSDetails (pScoringContext, i, j, buf, 1024);
									fprintf (fp, "%s\n", buf);
								}
							}
						}
					}
					fclose (fp);
				}
			}

			if (Parameters.modus & FLAG_MODUS_STAT)
			{
				lkf_stat (pScoringContext);
				ka = lkf_get_context_ka (pScoringContext, 0, 0, 0);
				lkf_compose_filename (pScoringContext, ka, 't', fn2);
				sprintf (ausgabe_file, "%s%s", Parameters.sOutputPath, fn2);
				
				fp = fopen (ausgabe_file, "w");
				if (fp) 
				{
					unsigned int nType, nCount;

					for (nType = 0; nType < 4; nType++)
					{
						lkf_stat_getHeadline (pScoringContext, nType, buf, 1024);
						fprintf (fp, "%s\n", buf);

						nCount = lkf_stat_getLineCount (pScoringContext, nType);
					
						for (i = 0; i < nCount; i++)
						{
							lkf_stat_getLine (pScoringContext, nType, i, buf, 1024);
							fprintf (fp, "%s\n", buf);
						}					
 					}

					fclose (fp);
				}
			}
            
#ifdef PRINT_MELPUNKTE
        {
            LKF_AUFENTHALT *pAufenthalt;
            count = lkf_get_aufenthalt_anz(pScoringContext);
            for (i = 0; i < count; i++) {
                pAufenthalt = lkf_get_aufenthalt(pScoringContext, i);
                PrintMELPunkte(pAufenthalt);
            }
        }
#endif

			if (Parameters.modus & FLAG_MODUS_DIFF) 
			{
				unsigned int anz, diff;
				LKF_AUFENTHALT *pAufenthalt;

				count = 0;

				anz = lkf_get_aufenthalt_anz (pScoringContext);
			
				for (i = 0; i < anz; i++) {
				
					pAufenthalt = lkf_get_aufenthalt (pScoringContext, i);
					diff = (unsigned int) lkf_auf_getdiff (pAufenthalt);

					if (diff) {
					
						printf ("DIFF %s: ", lkf_auf_get_ident (pAufenthalt, buf));

						printf ((diff & LKFDIFF_PLAUS) ? "PLAUS " : "      ");
                        
                        if (diff & LKFDIFF_SCGES) {
                            char scges[12];
                            char oscges[12];
                            lkf_auf_get_fieldvalue(pAufenthalt, SCORFIELD_SCGES, scges, 12);
                            lkf_auf_get_fieldvalue(pAufenthalt, -SCORFIELD_SCGES, oscges, 12);
                            
                            printf ("SCGES  : %12.12s (orig: %12.12s)", scges, oscges);
                        }
                        else {
                            printf ((diff & LKFDIFF_SCGES) ? "SCGES " : "      ");
                        }
 
						printf ("\n");
						++count;
					}
				}

				printf ("%d Differenzen gefunden (%d Aufenthalte).\n", count, anz);

			}
		}
        else {
            if (Parameters.modus & FLAG_MODUS_STAT)
            {
                ka = lkf_get_context_ka (pScoringContext, 0, 0, 0);
                lkf_compose_filename (pScoringContext, ka, 't', fn2);
                sprintf (ausgabe_file, "%s%s", Parameters.sOutputPath, fn2);
                
                fp = fopen (ausgabe_file, "w");
                if (fp)
                {
                    unsigned int nType, nCount;
                    
                    for (nType = 0; nType < 4; nType++)
                    {
                        lkf_stat_getHeadline (pScoringContext, nType, buf, 1024);
                        fprintf (fp, "%s\n", buf);
                        
                        nCount = lkf_stat_getLineCount (pScoringContext, nType);
                        
                        for (i = 0; i < nCount; i++)
                        {
                            lkf_stat_getLine (pScoringContext, nType, i, buf, 1024);
                            fprintf (fp, "%s\n", buf);
                        }					
                    }
                    
                    fclose (fp);
                }
            }
        }

        lkf_free_context (pScoringContext);
#ifndef LKF_DISABLE_IO
        if (Parameters.modus & FLAG_MODUS_PATH) {
#ifdef __APPLE__
            do {
                ep = readdir (dp);
            } while (ep && ep->d_type != DT_REG);
            
            if (!ep) filepath_handler = -1;
            else {
                sprintf (input_file, "%s%s", Parameters.sInputPath, ep->d_name);
            }
#else
            filepath.attrib = _A_SUBDIR;
            while (filepath_handler != -1 && filepath.attrib == _A_SUBDIR) {
                if (_findnext (filepath_handler, &filepath) == -1) {
                    filepath_handler = -1;
                }
            }
            
            if (filepath_handler != -1) sprintf (input_file, "%s%s", Parameters.sInputPath, filepath.name);
#endif
        }
#else
        filepath_handler = -1;
#endif
    } while (filepath_handler != -1);

	lkf_unloadStamm ();
    lkf_unloadSatzart();
	return 0;
}

/***************************************************************************************************
** Funktion parse_commandfile: Parst die Commandline und das angeg. Commandfile                   **
***************************************************************************************************/

static void remove_crlf (char *sWert)
{
	unsigned int nLen = (unsigned int) strlen (sWert);
	while (nLen > 0 && (sWert[nLen-1] == 10 || sWert[nLen-1] == 13))
		--nLen;
	sWert[nLen] = 0;
}

static unsigned int parse_csv (const char *sWert, unsigned int nSize, unsigned int *pArray)
{
	unsigned int nr;
	unsigned int nCount = 0;
	const char **ppPos = &sWert;
	while (**ppPos >= '0' && **ppPos <= '9') 
	{
		nr = (unsigned int) strtoul (*ppPos, (char **) ppPos, 10);
		if (nr) pArray[nCount++] = nr;
		if (**ppPos != ';' || nCount == nSize) return nCount;
		++*ppPos;
	}
	return nCount;
}

static int parse_commandfile (const char *sCommandFile, const char *sInputFile, LKF_SCORING_PARAMETERS *pParameters)
{ /* V12.1 */
	FILE *fp;
	char sCommandLine[1024];
	const char *sTrennPos;
	char sToken[128];
	char sWert[512];
	int bWarningAsErrors = 0;
	int nInfoAs = 0; /* V13.0 */
	fp = fopen (sCommandFile, "r");

	if (!fp)
	{
		printf ("Commandfile '%s' konnte nicht geöffnet werden", sCommandFile);
		return 1;
	}

	pParameters->modus |= FLAG_MODUS_ERROR_FILE;
	pParameters->modus |= FLAG_MODUS_SCOR_FORMAT_NORM;
	pParameters->modus |= FLAG_MODUS_SCORING; /* V16.0 - Scoring auch bei Textfile */
	pParameters->modelljahr = 0;
	
	while (fgets (sCommandLine, 1024, fp))
	{
		sTrennPos = strchr (sCommandLine, '=');
		if (sTrennPos)
		{
			strncpy (sToken, sCommandLine, sTrennPos-sCommandLine);
			sToken[sTrennPos-sCommandLine] = 0;
			strcpy (sWert, sTrennPos+1);
			remove_crlf (sWert);
		}
		else
		{
			strcpy (sToken, sCommandLine);
			sWert[0] = 0;
			remove_crlf (sToken);
		}
		if (!strcmp (sToken, "MODELL"))
			pParameters->modelljahr = (unsigned int) atoi (sWert);
		else if (!strcmp (sToken, "FLAGS"))
			pParameters->flags |= atoi (sWert);
		else if (!strcmp(sToken, "BATCH"))
			pParameters->modus |= FLAG_MODUS_PATH;
		else if (!strcmp(sToken, "QUICKSCORE"))
			pParameters->flags |= LKFCONTEXT_ALLOWQUICKSCORE;
		else if (!strcmp(sToken, "OPTIMIZER"))
			pParameters->flags |= LKFCONTEXT_OPTIMIZER;
		else if (!strcmp(sToken, "NPPLAUS"))
		{
			pParameters->flags |= LKFCONTEXT_NPPLAUS;
			if (strstr (sWert, "TRACE"))
				pParameters->modus |= FLAG_MODUS_NPPLAUS_TRACE;
			if (strstr (sWert, "SUM"))
				pParameters->modus |= FLAG_MODUS_NPPLAUS_SUM;
		}
		else if (!strcmp(sToken, "NICHTFONDS"))
			pParameters->flags |= LKFCONTEXT_NICHTFONDSKA;
		else if (!strcmp (sToken, "COMPATIBILITY"))
		{
			unsigned int cm = (unsigned int) atoi (sWert);
			pParameters->lkf_compatibility = cm & 255;
			pParameters->private_compatibility = cm & (255<<8);
		}
		else if (!strcmp(sToken, "FMT:SV"))
		{
			pParameters->modus &= ~FLAG_MODUS_SCOR_FORMAT_NORM;
			pParameters->modus |= FLAG_MODUS_SCOR_FORMAT_SV;
		}
		else if (!strcmp(sToken, "FMT:C"))
		{
			pParameters->modus &= ~FLAG_MODUS_SCOR_FORMAT_NORM;
			pParameters->modus |= FLAG_MODUS_SCOR_FORMAT_C;
			pParameters->field_anz = parse_csv (sWert, 60, pParameters->field);
		}
		else if (!strcmp (sToken, "FMT:CX"))
		{
			pParameters->modus &= ~FLAG_MODUS_SCOR_FORMAT_NORM;
			pParameters->modus |= FLAG_MODUS_SCOR_FORMAT_CX;
			pParameters->field_anz = parse_csv (sWert, 60, pParameters->field);
		}
		else if (!strcmp (sToken, "DIFFERENZ"))
		{
			pParameters->modus |= FLAG_MODUS_DIFF; 
		}
		else if (!strcmp (sToken, "ERRORFILE"))
		{
			if (!strcmp (sWert, "OFF"))
				pParameters->errorfieldcount = 0;
			else if (*sWert)
			{
				pParameters->errorfields = (unsigned int *) calloc (100, sizeof (unsigned int)); 
				pParameters->errorfieldcount = parse_csv (sWert, 100, pParameters->errorfields);
				pParameters->ktrwarningfields = pParameters->errorfields;
				pParameters->ktrwarningfieldcount = pParameters->errorfieldcount;
			}
		}
		else if (!strcmp (sToken, "WARNINGFILE"))
		{
			if (!strcmp (sWert, "OFF"))
				pParameters->warningfieldcount = 0;
			else if (!strcmp (sWert, "ERROR"))
				bWarningAsErrors = 1;
			else if (*sWert)
			{
				pParameters->warningfields = (unsigned int *) calloc (100, sizeof (unsigned int)); 
				pParameters->warningfieldcount = parse_csv (sWert, 100, pParameters->warningfields);
				pParameters->ktrwarningfields = pParameters->warningfields;
				pParameters->ktrwarningfieldcount = pParameters->warningfieldcount;
			}
		}
		else if (!strcmp (sToken, "INFOFILE"))
		{ /* V13.0 */
			if (!strcmp (sWert, "OFF"))
				pParameters->infofieldcount = 0;
			else if (!strcmp (sWert, "WARNING"))
				nInfoAs = 1;
			else if (!strcmp (sWert, "ERROR"))
				nInfoAs = 2;
			else if (*sWert)
			{
				pParameters->infofields = (unsigned int *) calloc (100, sizeof (unsigned int)); 
				pParameters->infofieldcount = parse_csv (sWert, 100, pParameters->warningfields);
			}
		}
		else if (!strcmp (sToken, "ERRORABTFILE"))
		{
			pParameters->modus |= FLAG_MODUS_ABT_FILE;
		}
		else if (!strcmp (sToken, "MELDEDIAG"))
		{
			if (!strcmp (sWert, "OFF"))
				pParameters->modus |= FLAG_MODUS_MELDEDIAG_FILE_OFF;
		}
		else if (!strcmp (sToken, "ERRSUM"))
		{
			if (!strcmp (sWert, "OFF"))
				pParameters->modus |= FLAG_MODUS_ERRSUM_FILE_OFF;
		}
		else if (!strcmp (sToken, "WARNSUM"))
		{
			if (!strcmp (sWert, "OFF"))
				pParameters->modus |= FLAG_MODUS_WARNSUM_FILE_OFF;
		}
		else if (!strcmp (sToken, "ERRORS"))
		{
			if (!strcmp (sWert, "OFF"))
				pParameters->modus &= ~FLAG_MODUS_ERROR_FILE;
		}
		else if (!strcmp (sToken, "FILTER"))
		{
			const char *pWert = sWert;
			if (parse_command_filter (0, (const char **) &pWert, &pParameters->pFilter))
				return 1;
		}
		else if (!strcmp (sToken, "FILTERFILE"))
		{
			if (parse_filter_file (sWert, &pParameters->pFilter)) return 1;
		}
		else if (!strcmp (sToken, "OUT"))
		{
			strncpy (pParameters->sOutputPath, sWert, LKF_MAX_PATH);
			pParameters->sOutputPath[LKF_MAX_PATH-1] = 0;
		}
		else if (!strcmp (sToken, "STAMM"))
		{
			strncpy (pParameters->sStammPath, sWert, LKF_MAX_PATH);
			pParameters->sStammPath[LKF_MAX_PATH-1] = 0;
		}
		else if (!strcmp (sToken, "ABRECHNUNG"))
		{
			if (!lkf_GetInt (sWert, 4, &pParameters->cmb_jahr)) {
				printf ("Jahr ungueltig!!\n");
				return 1;
			}
			
			pParameters->period_type = sWert[4];

			if (islower (pParameters->period_type)) pParameters->period_type = (char) toupper (pParameters->period_type);

			if (!strchr ("JHQMT", pParameters->period_type)) {
				printf ("\nUngueltiger Periodentyp ((muß J, H, Q, M oder T sein) !");
				return 1;
			}
			
			if (!lkf_GetInt (sWert + 5, 3, &pParameters->period_val)) {
				printf ("Periodenwert falsch\n");
				return 1;
			}
			
			if (!lkf_GetInt (sWert + 8, 2, &pParameters->lfdnr)) {
				printf ("laufende Nummer falsch\n");
				return 1;
			}
		}
		else if (!strcmp (sToken, "JAHR"))
		{
			pParameters->cmb_jahr = atoi (sWert);
			pParameters->period_type = 'J';
			pParameters->period_val = 1;
			pParameters->lfdnr = 1;
			if (pParameters->cmb_jahr <= 0)
			{
				printf ("Parameter JAHR falsch");
				return 1;
			}
		}
		else if (!strcmp (sToken, "INTENSIV"))
		{
			const char *pWert = sWert;
			pParameters->modus |= FLAG_MODUS_INTSCORING;
			pParameters->int_modus = FLAG_INTMODUS_AKTIV;
			while (pWert && strchr ("123DEAdea", *pWert)) /* V16.0 - D akzeptieren */  
			{
				switch (*pWert) 
				{ 
					case 'A':
					case 'a':
						pParameters->int_modus |= FLAG_INTMODUS_OUTPUT_ANALYSE;
						break;
			
					case 'D':
					case 'd':
						pParameters->int_modus |= FLAG_INTMODUS_INTAUF_DETAILS;
						break;
					case '1':
						pParameters->int_modus |= FLAG_INTMODUS_OUTPUT_SAPSII;
						break;
					case '2':
						pParameters->int_modus |= FLAG_INTMODUS_OUTPUT_TISS;
						break;
					case '3':
						pParameters->int_modus |= FLAG_INTMODUS_OUTPUT_TRISS;
						break;
				}
				++pWert;
			}

		}
		else if (!strcmp (sToken, "STATISTIK"))
		{
			pParameters->modus |= FLAG_MODUS_STAT;
		}
		
	}

	strncpy (pParameters->sInputPath, sInputFile, LKF_MAX_PATH);
	pParameters->sInputPath[LKF_MAX_PATH-1] = 0;

	if (bWarningAsErrors)
	{
		pParameters->warningfields = pParameters->errorfields;
		pParameters->warningfieldcount = pParameters->errorfieldcount;
	}
	if (nInfoAs == 2)
	{
		pParameters->infofields = pParameters->errorfields;
		pParameters->infofieldcount = pParameters->errorfieldcount;
	}
	else if (nInfoAs == 1)
	{
		pParameters->infofields = pParameters->warningfields;
		pParameters->infofieldcount = pParameters->warningfieldcount;
	}

	if (!pParameters->sInputPath[0])
	{
		printf ("Input-File fehlt");
		return 1;
	}

	if (!pParameters->sOutputPath[0])
	{
		printf ("Input-File fehlt");
		return 1;
	}

	if (!pParameters->sStammPath[0])
	{
		printf ("Stammdaten-Pfad fehlt");
		return 1;
	}

	if (pParameters->cmb_jahr == 0)
	{
		printf ("Abrechnungsjahr fehlt");
		return 1;
	}

	if (!pParameters->modelljahr)
		pParameters->modelljahr = LKF_YEAR_LATEST;
	if (!(pParameters->lkf_compatibility & LKF_COMPATIBILITY_SCORINGOUTPUT))
		pParameters->modus |= FLAG_MODUS_DATAOUT;

	if (pParameters->modus & (FLAG_MODUS_SCOR_FORMAT_SV|FLAG_MODUS_SCOR_FORMAT_C|FLAG_MODUS_SCOR_FORMAT_CX))
		pParameters->modus |= FLAG_MODUS_SCOR_FORMAT_NORM;

	strncpy (pParameters->sInputPath, sInputFile, LKF_MAX_PATH);
	pParameters->sInputPath[LKF_MAX_PATH-1] = 0;

	return 0;
}

#ifdef PRINT_MELPUNKTE
static void PrintMELPunkte (LKF_AUFENTHALT *pAufenthalt)
{
    unsigned int i, melCount, abtCount;
    long melzu, leistpkt, melpkt;
    char punktbuf[20], ptkbuf[20], plkbuf[20], melzubuf[20], aufdat[10];
    char patidbuf[20];
    char melbuf[10], melanzbuf[6], melposbuf[5], meldatbuf[10];
    char abtpos[6];
    double abtLP, abtTP;
    double sumAbtLP, sumAbtTP;
    melCount = lkf_auf_get_melanz(pAufenthalt);
    
    lkf_auf_get_fieldvalue(pAufenthalt, SCORFIELD_AUFNR, patidbuf, 18);
    lkf_auf_get_fieldvalue(pAufenthalt, SCORFIELD_AUFDAT, aufdat, 10);

    lkf_auf_get_fieldvalue(pAufenthalt, SCORFIELD_LDFPLK, plkbuf, 20);
    lkf_auf_get_fieldvalue(pAufenthalt, SCORFIELD_LDFPTK, plkbuf, 20);
    lkf_auf_get_fieldvalue(pAufenthalt, SCORFIELD_SCGES, punktbuf, 20);
    lkf_auf_get_fieldvalue(pAufenthalt, SCORFIELD_MELZU, melzubuf, 20);
    
    printf ("%12.12s;%08.8s;*******;PUNKTE=%s;LK=%s;TK=%s;MELZU=%s\n", patidbuf, aufdat, punktbuf,plkbuf, ptkbuf, melzubuf);
    
    for (i = 0; i < melCount; i++) {
        lkf_auf_get_mel3(pAufenthalt, i, melbuf, melanzbuf, meldatbuf, melposbuf);
        melzu = lkf_auf_get_mel_field (pAufenthalt, i, 0);
        leistpkt = lkf_auf_get_mel_field(pAufenthalt, i, 1);
        melpkt = lkf_auf_get_mel_field(pAufenthalt, i, 2);
        printf ("%12.12s;%3d;%5.5s;%4.4s;%8.8s;%4.4s;%5ld;%5ld;%5ld\n", patidbuf, i, melbuf, melanzbuf, meldatbuf, melposbuf, melzu, leistpkt, melpkt);
    }

    printf ("%12.12s;ABTEILUNG\n", patidbuf);

    sumAbtLP = 0;
    sumAbtTP = 0;
    abtCount = lkf_auf_get_abtanz(pAufenthalt);
    for (i = 0; i < abtCount; i++) {
        lkf_auf_get_abtscor (pAufenthalt, i, abtpos, &abtTP, &abtLP);
        printf ("%12.12s;%3d;%5.5s;%6.2lf;%6.2lf\n", patidbuf, i, abtpos, abtTP, abtLP);
        sumAbtLP += abtLP;
        sumAbtTP += abtTP;
    }
    printf ("%12.12s;   ;     ;%6.2lf;%6.2lf;%6.2lf\n", patidbuf, sumAbtTP, sumAbtLP, sumAbtLP + sumAbtTP);
}
#endif

/***************************************************************************************************
** Funktion parse_commandline: Parst die Commandline-Parameter und ermittelt daraus die Steuer-   **
**      informationen fuer das Programm.															  **
***************************************************************************************************/

static int parse_commandline (int argc, char *argv[], LKF_SCORING_PARAMETERS *pParameters)
{
	char *buf;

	if (argc < 6 || argc > 7)
	{
		printf("\nUngueltige Anzahl von Parametern !");
		printf("\nAufrufformat : LKFScoring <Steuerdatei> <Inputfile>");
		printf("\noder           LKFScoring <Flags> StammdatenDir Inputfile YYYYPVVVNN File-Path [<Filter-File>]");
		printf("\n                          <Flags> = [M[<YYYY>][T]][F|L[<flag>]][P[N|P|E][A]][S[N|V|(C<fmt>|X<fmt>[I]]][F<Filter>]");
		return 1;
	}

	/* Ermittlung von Jahr, Periodentyp, Periodenwert, laufender Nummer */
	if (!lkf_GetInt (argv[4], 4, &pParameters->cmb_jahr)) {
		printf ("Jahr ungueltig!!\n");
		return 1;
	}
	
	pParameters->period_type = argv[4][4];

	if (islower (pParameters->period_type)) pParameters->period_type = (char) toupper (pParameters->period_type);

	if (!strchr ("JHQMT", pParameters->period_type)) {
		printf ("\nUngueltiger Periodentyp ((muß J, H, Q, M oder T sein) !");
		return 1;
	}
	
	if (!lkf_GetInt (argv[4] + 5, 3, &pParameters->period_val)) {
		printf ("Periodenwert falsch\n");
		return 1;
	}
	
	if (!lkf_GetInt (argv[4] + 8, 2, &pParameters->lfdnr)) {
		printf ("laufende Nummer falsch\n");
		return 1;
	}

	/* Parsen des Parameters 1 (Modus-Parameter) */
	buf = argv[1];
	pParameters->modus = (int) parse_command ((const char **) &buf, pParameters);

	if (parse_command_filter (1, (const char **) &buf, &pParameters->pFilter)) return 1;

	/* Bearbeiten des optionalen Filter-Parameter */
	if (argc > 6) {
		if (pParameters->pFilter) {
			printf ("Es duerfen nicht zwei Filter angegeben werden\n"); 
			return 1;
		}
		if (parse_filter_file (argv[6], &pParameters->pFilter)) return 1;	
	}

	if (*buf) {
		printf ("\nParameter 1 ungueltig!");
		return 1;
	}

	strncpy (pParameters->sStammPath, argv[2], LKF_MAX_PATH);
	pParameters->sStammPath[LKF_MAX_PATH-1] = 0;
	strncpy (pParameters->sInputPath, argv[3], LKF_MAX_PATH);
	pParameters->sInputPath[LKF_MAX_PATH-1] = 0;
	strncpy (pParameters->sOutputPath, argv[5], LKF_MAX_PATH);
	pParameters->sOutputPath[LKF_MAX_PATH-1] = 0;

	return 0;
}



/****************************************************************************
** Funktion parse_command: Übernimmt das Parsen des Modus-Parameters der   **
**     Commandline.                                                        **
****************************************************************************/

static int parse_intensiveinstufung (const char **ppBuf, LKF_SCORING_PARAMETERS *pParameters)
{
	const char *pStart, *pEnd, *pKomma;
	unsigned int i, nAbtCount = 0;

	if (**ppBuf == '(') 
	{
		++*ppBuf;
		pStart = *ppBuf;
		pEnd = strchr (pStart, ')');

		if (!pEnd) return 0;

		pKomma = pStart;

		while (pKomma && *pKomma) 
		{
			if (*pKomma == 'A') ++nAbtCount;
			pKomma = strchr (pKomma, ',');
			if (pKomma) ++pKomma;
		}

		if (nAbtCount) 
		{
			pParameters->nIntAbtDatAnzahl = nAbtCount;
			pParameters->pIntAbtDef = (INTABTDEF *) calloc (sizeof(INTABTDEF), nAbtCount);
		}

		pKomma = pStart;
		i = 0;

		while (pKomma && *pKomma && pKomma[1] == '=' && pKomma[2])
		{
			switch (*pKomma)
			{
				case 'A': case 'a':
					if (pKomma[10] == ':') 
					{
						memcpy (pParameters->pIntAbtDef[i].ABTFC, pKomma + 2, 8);
						pParameters->pIntAbtDef[i].ABTFC[8] = 0;
						pParameters->pIntAbtDef[i].nBetten = (unsigned int) atoi (pKomma + 11);
						if (!pParameters->pIntAbtDef[i].nBetten) pParameters->pIntAbtDef[i].nBetten = 1;
					}
					else pParameters->pIntAbtDef[i].ABTFC[0] = 0;
					++i;
					break;
				case 'S': case 's':
					memcpy (pParameters->IntStartDate, pKomma + 2, 8);
					pParameters->IntStartDate[8] = 0;
					break;
				case 'E': case 'e':
					memcpy (pParameters->IntEndDate, pKomma + 2, 8);
					pParameters->IntEndDate[8] = 0;
					break;
				default:
					break;
			}
			pKomma = strchr (pKomma, ',');
			if (pKomma) ++pKomma;
		}
		*ppBuf = pEnd; 
	}
	return 0;
}

static int parse_command (const char **ppBuf, LKF_SCORING_PARAMETERS *pParameters)
{
    unsigned int nr, cm;
    char *endbuf;
    
    pParameters->flags = 0;
    
    if (**ppBuf == 'X' || **ppBuf == 'x') {
        ++*ppBuf;
        if (**ppBuf >= '1' && **ppBuf <= '9') {
            pParameters->modelljahr = (unsigned int) strtoul (*ppBuf, (char **) ppBuf, 10);
        }
        else pParameters->modelljahr = (unsigned int) pParameters->cmb_jahr;
        if (**ppBuf == ':') {
            ++*ppBuf;
            pParameters->anonymizationParameters = *ppBuf;
            *ppBuf += strlen (pParameters->anonymizationParameters);
        }
        pParameters->modus = FLAG_MODUS_ANONYMIZE;
        return FLAG_MODUS_ANONYMIZE;
    }
	/* Parameter fuer das Jahresmodell */
	else if (**ppBuf == 'M' || **ppBuf == 'm' || **ppBuf == 'A' || **ppBuf =='a') {
		++*ppBuf;

		if (**ppBuf >= '1' && **ppBuf <= '9') {
			pParameters->modelljahr = (unsigned int) strtoul (*ppBuf, (char **) ppBuf, 10);
		}
		else pParameters->modelljahr = (unsigned int) pParameters->cmb_jahr;

		while (**ppBuf && strchr ("MmBbQqTtOoDdNnYyUuEe", **ppBuf)) /* V10.0 */
		{

			switch (**ppBuf) {
			
			case 'Y': case 'y':
			
				pParameters->flags |= (unsigned int) atoi ((*ppBuf)+1);
				++*ppBuf;
				while (**ppBuf >= '0' && **ppBuf <= '9') ++*ppBuf;
				--*ppBuf;
				break;

            case 'U': case 'u':
                pParameters->packageSize = (unsigned int) atoi((*ppBuf)+1);
                ++*ppBuf;
                while (**ppBuf >= '0' && **ppBuf <= '9') ++*ppBuf;
                --*ppBuf;
                break;
                    
            case 'T': case 't':
                // Tagesklinik - immer aktiv, Parameter wird ignoriert
                break;
			case 'B': case 'b':
				pParameters->modus |= FLAG_MODUS_PATH; 
				break;
			case 'Q': case 'q': 
				pParameters->flags |= LKFCONTEXT_ALLOWQUICKSCORE;
				break;
			case 'O': case 'o':
				pParameters->flags |= LKFCONTEXT_OPTIMIZER; 
				break;
			case 'D': case 'd': 
				pParameters->modus |= FLAG_MODUS_DIFF; 
				break;
            case 'E': case 'e':
                if  (strchr ("01", (*ppBuf)[1])) {
                    switch ((*ppBuf)[1]) {
                        case '0':
                            pParameters->fmt_err_pre2017 = 1;
                        case '1':
                            pParameters->fmt_add_posfield = 1;
                    }
                    ++*ppBuf;
                }
                else
                    pParameters->fmt_err_pre2017 = 1;
                break;
			case 'N': case 'n': 
				pParameters->flags |= LKFCONTEXT_NPPLAUS; 
				if (strchr ("Nn", (*ppBuf)[1])) {
					++*ppBuf;
					pParameters->modus |= FLAG_MODUS_NPPLAUS_TRACE;
				}
				if (strchr ("Uu", (*ppBuf)[1])) {
					++*ppBuf;
					pParameters->modus |= FLAG_MODUS_NPPLAUS_SUM;
				}
				break;
			case 'M': case 'm': /* Fonds/Nicht-Fonds-Einstellung */
				if (strchr ("Nn", (*ppBuf)[1])) 
				{
					++*ppBuf;
					pParameters->flags |= LKFCONTEXT_NICHTFONDSKA;
				}
				else if (strchr ("Ff", (*ppBuf)[1]))
					++*ppBuf;
				break;
			default:
				break;
			}
			++*ppBuf;
		}
	}
	else pParameters->modelljahr = LKF_YEAR_LATEST; /* nimm das aktuelles Modell */
	/* Parameter fuer den Difference-Modus */

	if (**ppBuf == 'C' || **ppBuf == 'c') 
	{
		++*ppBuf;
		cm = (unsigned int) strtoul (*ppBuf, &endbuf, 10);
		pParameters->lkf_compatibility = cm & 255;
		pParameters->private_compatibility = cm & (255<<8);
		*ppBuf = endbuf;
	}

	if (!(pParameters->lkf_compatibility & LKF_COMPATIBILITY_SCORINGOUTPUT)) 
		pParameters->modus |= FLAG_MODUS_DATAOUT;
     	
	/* Parameter fuer den Plaus-Check */
	if (**ppBuf == 'P' || **ppBuf == 'p') {
		++*ppBuf;
		pParameters->modus |= FLAG_MODUS_PLAUS;

		if (**ppBuf == 'N' || **ppBuf == 'n') ++*ppBuf;
		else if (**ppBuf == 'E' || **ppBuf == 'e') {
			++*ppBuf;
			pParameters->modus |= FLAG_MODUS_ERROR_FILE | FLAG_MODUS_SUM_FILE;
		}
		else if (**ppBuf == 'P' || **ppBuf == 'p') {
			++*ppBuf;
			pParameters->modus |= FLAG_MODUS_PLAUS_FILE;
		}
		else pParameters->modus |= FLAG_MODUS_PLAUS_FILE | FLAG_MODUS_ERROR_FILE | FLAG_MODUS_SUM_FILE;

		if (**ppBuf == 'A' || **ppBuf == 'a') {
			++*ppBuf;
			pParameters->modus |= FLAG_MODUS_ABT_FILE;
		}
	}

	/* Parameter fuer das Scoring */
	if (**ppBuf == 'S' || **ppBuf == 's') {
		++*ppBuf;
		pParameters->modus |= FLAG_MODUS_SCORING;

		if (**ppBuf == 'N' || **ppBuf == 'n') ++*ppBuf;
		else {
			if (**ppBuf == 'V' || **ppBuf == 'v') {
				++*ppBuf;
				pParameters->modus |= FLAG_MODUS_SCOR_FORMAT_SV;
			}
			else {
				
				if (**ppBuf == 'C' || **ppBuf == 'c' || 
					 **ppBuf == 'X' || **ppBuf == 'x') {

					if (**ppBuf == 'C' || **ppBuf == 'c') pParameters->modus |= FLAG_MODUS_SCOR_FORMAT_C;
					else pParameters->modus |= FLAG_MODUS_SCOR_FORMAT_CX;
					++*ppBuf;

					/* Parsen der Parameter fuer Custom Output */
					pParameters->field_anz = 0;
					while (**ppBuf >= '0' && **ppBuf <= '9') {
						nr = (unsigned int) strtoul (*ppBuf, (char **) ppBuf, 10);
						if (nr) pParameters->field[pParameters->field_anz++] = nr;
						if (**ppBuf != ';') return pParameters->modus;
						++*ppBuf;
					}
					if (**ppBuf != 'I') pParameters->modus |= FLAG_MODUS_SCOR_FORMAT_NORM;
					else ++*ppBuf;
				}
				else pParameters->modus |= FLAG_MODUS_SCOR_FORMAT_NORM;
			}
		}
	}

	if (**ppBuf == 'I' || **ppBuf == 'i') 
	{
		++*ppBuf;
		pParameters->modus |= FLAG_MODUS_INTSCORING;
		pParameters->int_modus = FLAG_INTMODUS_AKTIV;
		
		while (**ppBuf && strchr ("123DdEAea", **ppBuf)) /* V15.2 -> dD akzeptieren */ 
		{
			switch (**ppBuf) 
			{ 
				case 'A':
				case 'a':
					pParameters->int_modus |= FLAG_INTMODUS_OUTPUT_ANALYSE;
					break;
		
				case 'D':
				case 'd':
					pParameters->int_modus |= FLAG_INTMODUS_INTAUF_DETAILS;
					break;
				case '1':
					pParameters->int_modus |= FLAG_INTMODUS_OUTPUT_SAPSII;
					break;
				case '2':
					pParameters->int_modus |= FLAG_INTMODUS_OUTPUT_TISS;
					break;
				case '3':
					pParameters->int_modus |= FLAG_INTMODUS_OUTPUT_TRISS;
					break;
				case 'E':
				case 'e':
					pParameters->int_modus |= FLAG_INTMODUS_OUTPUT_EINSTUFUNG;
					if ((*ppBuf)[1] == '(') 
					{
						++*ppBuf;					
						parse_intensiveinstufung (ppBuf, pParameters);
					}
					break;
			}
			++*ppBuf;
		}

	}

	if (**ppBuf == 'T' || **ppBuf == 't') 
	{
		++*ppBuf;
		pParameters->modus |= FLAG_MODUS_STAT;
	}

	return pParameters->modus;
}

/*************************************************************************************
** Funktion parse_command_filter: Parst eine eventuell angegebene Filterinformation **
**     im Modus-Parameter (Parameter 1).                                            **
*************************************************************************************/

static int parse_command_filter (int bModus, const char **ppBuf, LKF_FILTER **ppFilter)
{
	const char *format_buf;
	int anz, i;

	if (bModus)
	{
		if (**ppBuf != 'F' && **ppBuf != 'f')
		{
			*ppFilter = 0;
			return 0;
		}
		++*ppBuf;
	}

	format_buf = *ppBuf;
	*ppFilter = lkf_filter_create (ppBuf);

	if (!*ppFilter) {
		printf ("Syntaxfehler im Filterausdruck:\n");
		printf ("   Filter: %s\n", format_buf);
		printf ("           ");
		anz = (int) (*ppBuf - format_buf);
		for (i = 0; i < anz; i++) putchar (' ');
		printf ("#\n");
		return 1;
	}
	return 0;
}


/*************************************************************************************
** Funktion parse_filter_file: Parst einen in einem Textfile angegebenen Filter.    **
*************************************************************************************/

static int parse_filter_file (const char *filename, LKF_FILTER **ppFilter)
{
#define MAX_FILTERBUFFER_LEN 2048
	char filter_buffer[MAX_FILTERBUFFER_LEN + 1];
	const char *tmp_buf;
	unsigned int len = 0;
	FILE *fp;

	fp = fopen (filename, "r");
	if (!fp) {
		printf ("Filter-File '%s' konnte nicht geöffnet werden\n", filename);
		return 1;
	}

	while (len < MAX_FILTERBUFFER_LEN && fgets (filter_buffer + len, (int) (MAX_FILTERBUFFER_LEN + 1 - len), fp)) {
		len += (unsigned int) strlen (filter_buffer + len);
	}

	fclose (fp);

	if (len >= MAX_FILTERBUFFER_LEN) {
		printf ("Der Filter-File ist zu lang.\n");
		return 1;
	}

	tmp_buf = filter_buffer;
	*ppFilter = lkf_filter_create (&tmp_buf);

	if (!*ppFilter) {
		printf ("Fehler im Filter-Statement.\n");
		return 1;
	}
	return 0;
}

static int WriteErrorlistFile (LKF_CONTEXT *pContext, const char *path) {
	unsigned int errorcount, i;
	char buf[1024];
    int flags = -1;
	LKF_SATZART_ERRORINFO_LIST *pList;
	const LKF_SATZART_ERRORINFO *pErrorInfo;
    
    FILE *fp;
    fp = fopen (path, "w");
    if (!fp) {
        return -1;
    }
    
	pList = lkf_create_errorinfo (pContext, (unsigned int) flags);
	lkf_errorinfo_getHeadline (pList, buf, 1024);
    fprintf (fp, "%s\n", buf);
	    
	errorcount = lkf_errorinfo_getCount (pList);
    
	for (i = 0; i < errorcount; i++)
	{
		pErrorInfo = lkf_errorinfo_getError (pList, i);
		lkf_errorinfo_getErrorLine (pErrorInfo, buf, 1024);
        fprintf (fp, "%s\n", buf);
/*
		usagecount = lkf_errorinfo_getErrorUsageCount (pErrorInfo);
        
		for (j = 0; j < usagecount; j++)
		{
			pUsage = lkf_errorinfo_getErrorUsage (pErrorInfo, j);
			lkf_errorinfo_getErrorUsageLine (pUsage, buf, 1024);
            fprintf (fp, "%s\n", buf);
		}
*/
	}
    
	lkf_free_errorinfo (pList);
	return 1;
    
}

static void FillCheckInfo (FILE *fp, LKF_CONTEXT *pContext, const void *pCheckInfo, const char *sFieldIndex, const char *sErrorIndex)
{
	const void *pNextCheck, *pNextCheckErr;
	char buf[2048], linebuf[1024];
	char sNextErrorIndex[20];
    
	lkf_Satzart_getCheckInfo (pContext, pCheckInfo, sFieldIndex, sErrorIndex, buf, 2048);
    fprintf (fp, "%s\n", buf);
    
	if (lkf_Satzart_getCheckDetails (pContext, pCheckInfo, buf, 2048) > 0)
	{
		unsigned int lastpos, pos = 0;
		while (buf[pos])
		{
			lastpos = pos;
			while (buf[pos] && buf[pos] != '\n') ++pos;
			buf[pos] = 0;
			sprintf (linebuf, "D;%s                         ; %-16.16s;\"%s\"",sFieldIndex, sErrorIndex, buf + lastpos);
            fprintf (fp, "%s\n", linebuf);
			pos++;
		}
	}
    
	pNextCheck = lkf_Satzart_getNextCheck (pContext, pCheckInfo, 1);
	pNextCheckErr = lkf_Satzart_getNextCheck (pContext, pCheckInfo, 0);
    
	if (pNextCheck) {
		if (pNextCheck == pNextCheckErr)
			sprintf (sNextErrorIndex, "%s.->", sErrorIndex);
		else
			sprintf (sNextErrorIndex, "%s.ok", sErrorIndex);
		sNextErrorIndex[18] = 0;
		FillCheckInfo (fp, pContext, pNextCheck, sFieldIndex, sNextErrorIndex);
	}
    
	if (pNextCheckErr && pNextCheckErr != pNextCheck)
	{
		sprintf (sNextErrorIndex, "%s.er", sErrorIndex);
		sNextErrorIndex[18] = 0;
		FillCheckInfo (fp, pContext, pNextCheckErr, sFieldIndex, sNextErrorIndex);
	}
}


static int WriteSatzartInfoFile (LKF_CONTEXT *pContext, const char *path) {
	const void *pCheckInfo;
	unsigned int satzart_count, feld_count, i, j;
	const LKF_SATZART_DEFS *pSatzartDefs;
	char buf[1024];
	char fieldindex[128];
    FILE *fp;
    int modellJahr;
    
    fp = fopen (path, "w");
    if (!fp) return -1;
    
    modellJahr = lkf_context_getModellJahr(pContext);
	fprintf (fp, "SATZART-DEFINITIONEN fuer Modelljahr %d\n", modellJahr);
    
	pSatzartDefs = lkf_Satzart_getDefinition ((unsigned int) modellJahr);
	satzart_count = lkf_Satzart_getCount (pSatzartDefs);
    
	for (i = 0; i < satzart_count; i++)
	{
		if (lkf_Satzart_getSatzartDef (pSatzartDefs, i, buf, 1024)) fprintf (fp, "%s\n", buf);
		if (lkf_Satzart_getSatzartKeyInfo (pSatzartDefs, i, buf, 1024)) fprintf (fp, "%s\n", buf);
        
		feld_count = lkf_Satzart_getSatzartFieldCount (pSatzartDefs, i);
        
		for (j = 0; j < feld_count; j++)
		{
			if (lkf_Satzart_getSatzartFieldInfo (pSatzartDefs, i, j, buf, 1024)) fprintf (fp, "%s\n", buf);
			if (1)
			{
				pCheckInfo = lkf_Satzart_getSatzartFieldCheck (pContext, pSatzartDefs, i, j);
				if (pCheckInfo)
				{
					lkf_Satzart_getSatzartFieldTextId (pSatzartDefs, i, j, fieldindex, 128);
					FillCheckInfo (fp, pContext, pCheckInfo, fieldindex, "");
				}
			}
		}
        
		/* V9.1: Generelle Checks f¸r diese Satzart */
		pCheckInfo = lkf_Satzart_getSatzartFieldCheck (pContext, pSatzartDefs, i, (1<<16)); /* V10.2 */
		if (pCheckInfo)
		{
			lkf_Satzart_getSatzartFieldTextId (pSatzartDefs, i, (1<<16), fieldindex, 128);
			FillCheckInfo (fp, pContext, pCheckInfo, fieldindex, "");
		}
	}
    
	/* V9.1: Generelle Checks Satzart-¸bergreifend */
	i = 0;
	while ((pCheckInfo = lkf_Satzart_getSatzartFieldCheck (pContext, pSatzartDefs, (1<<16), i))) /* V10.2 */
	{
		lkf_Satzart_getSatzartFieldTextId (pSatzartDefs, (1<<16), i, fieldindex, 128);
		FillCheckInfo (fp, pContext, pCheckInfo, fieldindex, "");
		++i;
	}
    
	/* V14.2: Generelle Checks Satzart-¸bergreifend Berichtswesen*/
	i = 0;
	while ((pCheckInfo = lkf_Satzart_getSatzartFieldCheck (pContext, pSatzartDefs, (1<<17), i)))
	{
		lkf_Satzart_getSatzartFieldTextId (pSatzartDefs, (1<<16), i, fieldindex, 128);
		FillCheckInfo (fp, pContext, pCheckInfo, fieldindex, "");
		++i;
	}
    fclose (fp);
    return 0;
}
