/*
 * MATLAB Compiler: 3.0
 * Date: Thu Aug 07 20:04:08 2008
 * Arguments: "-B" "macro_default" "-O" "all" "-O" "fold_scalar_mxarrays:on"
 * "-O" "fold_non_scalar_mxarrays:on" "-O" "optimize_integer_for_loops:on" "-O"
 * "array_indexing:on" "-O" "optimize_conditionals:on" "-x" "-W" "mex" "-L" "C"
 * "-t" "-T" "link:mexlibrary" "libmatlbmx.mlib" "prognoz_maxr" 
 */
#include "prognoz_maxr.h"
#include "mwservices.h"
#include "dy2sost.h"
#include "libmatlbm.h"
#include "random.h"

extern mxArray * bif_flag;
extern mxArray * type_prirash;
static mxArray * _mxarray0_;
static mxArray * _mxarray1_;
static mxArray * _mxarray2_;
static mxArray * _mxarray3_;

static mxChar _array5_[4] = { 'u', 'n', 'i', 'f' };
static mxArray * _mxarray4_;
static mxArray * _mxarray6_;
static mxArray * _mxarray7_;
static mxArray * _mxarray8_;

void InitializeModule_prognoz_maxr(void) {
    _mxarray0_ = mclInitializeDouble(0.0);
    _mxarray1_ = mclInitializeDouble(1.0);
    _mxarray2_ = mclInitializeDoubleVector(0, 0, (double *)NULL);
    _mxarray3_ = mclInitializeDouble(99999.0);
    _mxarray4_ = mclInitializeString(4, _array5_);
    _mxarray6_ = mclInitializeDouble(2.0);
    _mxarray7_ = mclInitializeDouble(-99999.0);
    _mxarray8_ = mclInitializeDouble(.01);
}

void TerminateModule_prognoz_maxr(void) {
    mxDestroyArray(_mxarray8_);
    mxDestroyArray(_mxarray7_);
    mxDestroyArray(_mxarray6_);
    mxDestroyArray(_mxarray4_);
    mxDestroyArray(_mxarray3_);
    mxDestroyArray(_mxarray2_);
    mxDestroyArray(_mxarray1_);
    mxDestroyArray(_mxarray0_);
}

static mxArray * mlfPrognoz_maxr_vector2sost(mxArray * vector_ver);
static void mlxPrognoz_maxr_vector2sost(int nlhs,
                                        mxArray * plhs[],
                                        int nrhs,
                                        mxArray * prhs[]);
static mxArray * mlfPrognoz_maxr_getclusters(mxArray * sostmax,
                                             mxArray * nsost);
static void mlxPrognoz_maxr_getclusters(int nlhs,
                                        mxArray * plhs[],
                                        int nrhs,
                                        mxArray * prhs[]);
static mxArray * mlfPrognoz_maxr_findnextver(mxArray * * rmax,
                                             mxArray * * place,
                                             mxArray * ysost,
                                             mxArray * dt,
                                             mxArray * sost4prognoz,
                                             mxArray * minnum);
static void mlxPrognoz_maxr_findnextver(int nlhs,
                                        mxArray * plhs[],
                                        int nrhs,
                                        mxArray * prhs[]);
static mxArray * mlfPrognoz_maxr_findcursost(mxArray * * place,
                                             mxArray * ysost,
                                             mxArray * dt,
                                             mxArray * cursost);
static void mlxPrognoz_maxr_findcursost(int nlhs,
                                        mxArray * plhs[],
                                        int nrhs,
                                        mxArray * prhs[]);
static mxArray * Mprognoz_maxr(mxArray * * mas_sredn,
                               mxArray * * r_min,
                               mxArray * * r_max,
                               mxArray * * r_avg,
                               int nargout_,
                               mxArray * y_urez,
                               mxArray * dt,
                               mxArray * r,
                               mxArray * s,
                               mxArray * nprognoz,
                               mxArray * tbeg);
static mxArray * Mprognoz_maxr_vector2sost(int nargout_, mxArray * vector_ver);
static mxArray * Mprognoz_maxr_getclusters(int nargout_,
                                           mxArray * sostmax,
                                           mxArray * nsost);
static mxArray * Mprognoz_maxr_findnextver(mxArray * * rmax,
                                           mxArray * * place,
                                           int nargout_,
                                           mxArray * ysost,
                                           mxArray * dt,
                                           mxArray * sost4prognoz,
                                           mxArray * minnum);
static mxArray * Mprognoz_maxr_findcursost(mxArray * * place,
                                           int nargout_,
                                           mxArray * ysost,
                                           mxArray * dt,
                                           mxArray * cursost);

static mexFunctionTableEntry local_function_table_[4]
  = { { "vector2sost", mlxPrognoz_maxr_vector2sost, 1, 1, NULL },
      { "getclusters", mlxPrognoz_maxr_getclusters, 2, 1, NULL },
      { "findnextver", mlxPrognoz_maxr_findnextver, 4, 3, NULL },
      { "findcursost", mlxPrognoz_maxr_findcursost, 3, 2, NULL } };

_mexLocalFunctionTable _local_function_table_prognoz_maxr
  = { 4, local_function_table_ };

/*
 * The function "mlfPrognoz_maxr" contains the normal interface for the
 * "prognoz_maxr" M-function from file
 * "d:\dayly\20080807\markovchains1_1mex20080807\prognoz_maxr.m" (lines 1-67).
 * This function processes any input arguments and passes them to the
 * implementation version of the function, appearing above.
 */
mxArray * mlfPrognoz_maxr(mxArray * * mas_sredn,
                          mxArray * * r_min,
                          mxArray * * r_max,
                          mxArray * * r_avg,
                          mxArray * y_urez,
                          mxArray * dt,
                          mxArray * r,
                          mxArray * s,
                          mxArray * nprognoz,
                          mxArray * tbeg) {
    int nargout = 1;
    mxArray * mas_newsost = NULL;
    mxArray * mas_sredn__ = NULL;
    mxArray * r_min__ = NULL;
    mxArray * r_max__ = NULL;
    mxArray * r_avg__ = NULL;
    mlfEnterNewContext(
      4, 6, mas_sredn, r_min, r_max, r_avg, y_urez, dt, r, s, nprognoz, tbeg);
    if (mas_sredn != NULL) {
        ++nargout;
    }
    if (r_min != NULL) {
        ++nargout;
    }
    if (r_max != NULL) {
        ++nargout;
    }
    if (r_avg != NULL) {
        ++nargout;
    }
    mas_newsost
      = Mprognoz_maxr(
          &mas_sredn__,
          &r_min__,
          &r_max__,
          &r_avg__,
          nargout,
          y_urez,
          dt,
          r,
          s,
          nprognoz,
          tbeg);
    mlfRestorePreviousContext(
      4, 6, mas_sredn, r_min, r_max, r_avg, y_urez, dt, r, s, nprognoz, tbeg);
    if (mas_sredn != NULL) {
        mclCopyOutputArg(mas_sredn, mas_sredn__);
    } else {
        mxDestroyArray(mas_sredn__);
    }
    if (r_min != NULL) {
        mclCopyOutputArg(r_min, r_min__);
    } else {
        mxDestroyArray(r_min__);
    }
    if (r_max != NULL) {
        mclCopyOutputArg(r_max, r_max__);
    } else {
        mxDestroyArray(r_max__);
    }
    if (r_avg != NULL) {
        mclCopyOutputArg(r_avg, r_avg__);
    } else {
        mxDestroyArray(r_avg__);
    }
    return mlfReturnValue(mas_newsost);
}

/*
 * The function "mlxPrognoz_maxr" contains the feval interface for the
 * "prognoz_maxr" M-function from file
 * "d:\dayly\20080807\markovchains1_1mex20080807\prognoz_maxr.m" (lines 1-67).
 * The feval function calls the implementation version of prognoz_maxr through
 * this function. This function processes any input arguments and passes them
 * to the implementation version of the function, appearing above.
 */
void mlxPrognoz_maxr(int nlhs, mxArray * plhs[], int nrhs, mxArray * prhs[]) {
    mxArray * mprhs[6];
    mxArray * mplhs[5];
    int i;
    if (nlhs > 5) {
        mlfError(
          mxCreateString(
            "Run-time Error: File: prognoz_maxr Line: 1 Column"
            ": 1 The function \"prognoz_maxr\" was called with"
            " more than the declared number of outputs (5)."),
          NULL);
    }
    if (nrhs > 6) {
        mlfError(
          mxCreateString(
            "Run-time Error: File: prognoz_maxr Line: 1 Column"
            ": 1 The function \"prognoz_maxr\" was called with"
            " more than the declared number of inputs (6)."),
          NULL);
    }
    for (i = 0; i < 5; ++i) {
        mplhs[i] = NULL;
    }
    for (i = 0; i < 6 && i < nrhs; ++i) {
        mprhs[i] = prhs[i];
    }
    for (; i < 6; ++i) {
        mprhs[i] = NULL;
    }
    mlfEnterNewContext(
      0, 6, mprhs[0], mprhs[1], mprhs[2], mprhs[3], mprhs[4], mprhs[5]);
    mplhs[0]
      = Mprognoz_maxr(
          &mplhs[1],
          &mplhs[2],
          &mplhs[3],
          &mplhs[4],
          nlhs,
          mprhs[0],
          mprhs[1],
          mprhs[2],
          mprhs[3],
          mprhs[4],
          mprhs[5]);
    mlfRestorePreviousContext(
      0, 6, mprhs[0], mprhs[1], mprhs[2], mprhs[3], mprhs[4], mprhs[5]);
    plhs[0] = mplhs[0];
    for (i = 1; i < 5 && i < nlhs; ++i) {
        plhs[i] = mplhs[i];
    }
    for (; i < 5; ++i) {
        mxDestroyArray(mplhs[i]);
    }
}

/*
 * The function "mlfPrognoz_maxr_vector2sost" contains the normal interface for
 * the "prognoz_maxr/vector2sost" M-function from file
 * "d:\dayly\20080807\markovchains1_1mex20080807\prognoz_maxr.m" (lines
 * 67-144). This function processes any input arguments and passes them to the
 * implementation version of the function, appearing above.
 */
static mxArray * mlfPrognoz_maxr_vector2sost(mxArray * vector_ver) {
    int nargout = 1;
    mxArray * newsost = NULL;
    mlfEnterNewContext(0, 1, vector_ver);
    newsost = Mprognoz_maxr_vector2sost(nargout, vector_ver);
    mlfRestorePreviousContext(0, 1, vector_ver);
    return mlfReturnValue(newsost);
}

/*
 * The function "mlxPrognoz_maxr_vector2sost" contains the feval interface for
 * the "prognoz_maxr/vector2sost" M-function from file
 * "d:\dayly\20080807\markovchains1_1mex20080807\prognoz_maxr.m" (lines
 * 67-144). The feval function calls the implementation version of
 * prognoz_maxr/vector2sost through this function. This function processes any
 * input arguments and passes them to the implementation version of the
 * function, appearing above.
 */
static void mlxPrognoz_maxr_vector2sost(int nlhs,
                                        mxArray * plhs[],
                                        int nrhs,
                                        mxArray * prhs[]) {
    mxArray * mprhs[1];
    mxArray * mplhs[1];
    int i;
    if (nlhs > 1) {
        mlfError(
          mxCreateString(
            "Run-time Error: File: prognoz_maxr/vector2sost Line: 67 C"
            "olumn: 1 The function \"prognoz_maxr/vector2sost\" was ca"
            "lled with more than the declared number of outputs (1)."),
          NULL);
    }
    if (nrhs > 1) {
        mlfError(
          mxCreateString(
            "Run-time Error: File: prognoz_maxr/vector2sost Line: 67 C"
            "olumn: 1 The function \"prognoz_maxr/vector2sost\" was ca"
            "lled with more than the declared number of inputs (1)."),
          NULL);
    }
    for (i = 0; i < 1; ++i) {
        mplhs[i] = NULL;
    }
    for (i = 0; i < 1 && i < nrhs; ++i) {
        mprhs[i] = prhs[i];
    }
    for (; i < 1; ++i) {
        mprhs[i] = NULL;
    }
    mlfEnterNewContext(0, 1, mprhs[0]);
    mplhs[0] = Mprognoz_maxr_vector2sost(nlhs, mprhs[0]);
    mlfRestorePreviousContext(0, 1, mprhs[0]);
    plhs[0] = mplhs[0];
}

/*
 * The function "mlfPrognoz_maxr_getclusters" contains the normal interface for
 * the "prognoz_maxr/getclusters" M-function from file
 * "d:\dayly\20080807\markovchains1_1mex20080807\prognoz_maxr.m" (lines
 * 144-208). This function processes any input arguments and passes them to the
 * implementation version of the function, appearing above.
 */
static mxArray * mlfPrognoz_maxr_getclusters(mxArray * sostmax,
                                             mxArray * nsost) {
    int nargout = 1;
    mxArray * maxclusters = NULL;
    mlfEnterNewContext(0, 2, sostmax, nsost);
    maxclusters = Mprognoz_maxr_getclusters(nargout, sostmax, nsost);
    mlfRestorePreviousContext(0, 2, sostmax, nsost);
    return mlfReturnValue(maxclusters);
}

/*
 * The function "mlxPrognoz_maxr_getclusters" contains the feval interface for
 * the "prognoz_maxr/getclusters" M-function from file
 * "d:\dayly\20080807\markovchains1_1mex20080807\prognoz_maxr.m" (lines
 * 144-208). The feval function calls the implementation version of
 * prognoz_maxr/getclusters through this function. This function processes any
 * input arguments and passes them to the implementation version of the
 * function, appearing above.
 */
static void mlxPrognoz_maxr_getclusters(int nlhs,
                                        mxArray * plhs[],
                                        int nrhs,
                                        mxArray * prhs[]) {
    mxArray * mprhs[2];
    mxArray * mplhs[1];
    int i;
    if (nlhs > 1) {
        mlfError(
          mxCreateString(
            "Run-time Error: File: prognoz_maxr/getclusters Line: 144 C"
            "olumn: 1 The function \"prognoz_maxr/getclusters\" was cal"
            "led with more than the declared number of outputs (1)."),
          NULL);
    }
    if (nrhs > 2) {
        mlfError(
          mxCreateString(
            "Run-time Error: File: prognoz_maxr/getclusters Line: 144 "
            "Column: 1 The function \"prognoz_maxr/getclusters\" was c"
            "alled with more than the declared number of inputs (2)."),
          NULL);
    }
    for (i = 0; i < 1; ++i) {
        mplhs[i] = NULL;
    }
    for (i = 0; i < 2 && i < nrhs; ++i) {
        mprhs[i] = prhs[i];
    }
    for (; i < 2; ++i) {
        mprhs[i] = NULL;
    }
    mlfEnterNewContext(0, 2, mprhs[0], mprhs[1]);
    mplhs[0] = Mprognoz_maxr_getclusters(nlhs, mprhs[0], mprhs[1]);
    mlfRestorePreviousContext(0, 2, mprhs[0], mprhs[1]);
    plhs[0] = mplhs[0];
}

/*
 * The function "mlfPrognoz_maxr_findnextver" contains the normal interface for
 * the "prognoz_maxr/findnextver" M-function from file
 * "d:\dayly\20080807\markovchains1_1mex20080807\prognoz_maxr.m" (lines
 * 208-243). This function processes any input arguments and passes them to the
 * implementation version of the function, appearing above.
 */
static mxArray * mlfPrognoz_maxr_findnextver(mxArray * * rmax,
                                             mxArray * * place,
                                             mxArray * ysost,
                                             mxArray * dt,
                                             mxArray * sost4prognoz,
                                             mxArray * minnum) {
    int nargout = 1;
    mxArray * vectorver = NULL;
    mxArray * rmax__ = NULL;
    mxArray * place__ = NULL;
    mlfEnterNewContext(2, 4, rmax, place, ysost, dt, sost4prognoz, minnum);
    if (rmax != NULL) {
        ++nargout;
    }
    if (place != NULL) {
        ++nargout;
    }
    vectorver
      = Mprognoz_maxr_findnextver(
          &rmax__, &place__, nargout, ysost, dt, sost4prognoz, minnum);
    mlfRestorePreviousContext(
      2, 4, rmax, place, ysost, dt, sost4prognoz, minnum);
    if (rmax != NULL) {
        mclCopyOutputArg(rmax, rmax__);
    } else {
        mxDestroyArray(rmax__);
    }
    if (place != NULL) {
        mclCopyOutputArg(place, place__);
    } else {
        mxDestroyArray(place__);
    }
    return mlfReturnValue(vectorver);
}

/*
 * The function "mlxPrognoz_maxr_findnextver" contains the feval interface for
 * the "prognoz_maxr/findnextver" M-function from file
 * "d:\dayly\20080807\markovchains1_1mex20080807\prognoz_maxr.m" (lines
 * 208-243). The feval function calls the implementation version of
 * prognoz_maxr/findnextver through this function. This function processes any
 * input arguments and passes them to the implementation version of the
 * function, appearing above.
 */
static void mlxPrognoz_maxr_findnextver(int nlhs,
                                        mxArray * plhs[],
                                        int nrhs,
                                        mxArray * prhs[]) {
    mxArray * mprhs[4];
    mxArray * mplhs[3];
    int i;
    if (nlhs > 3) {
        mlfError(
          mxCreateString(
            "Run-time Error: File: prognoz_maxr/findnextver Line: 208 C"
            "olumn: 1 The function \"prognoz_maxr/findnextver\" was cal"
            "led with more than the declared number of outputs (3)."),
          NULL);
    }
    if (nrhs > 4) {
        mlfError(
          mxCreateString(
            "Run-time Error: File: prognoz_maxr/findnextver Line: 208 "
            "Column: 1 The function \"prognoz_maxr/findnextver\" was c"
            "alled with more than the declared number of inputs (4)."),
          NULL);
    }
    for (i = 0; i < 3; ++i) {
        mplhs[i] = NULL;
    }
    for (i = 0; i < 4 && i < nrhs; ++i) {
        mprhs[i] = prhs[i];
    }
    for (; i < 4; ++i) {
        mprhs[i] = NULL;
    }
    mlfEnterNewContext(0, 4, mprhs[0], mprhs[1], mprhs[2], mprhs[3]);
    mplhs[0]
      = Mprognoz_maxr_findnextver(
          &mplhs[1], &mplhs[2], nlhs, mprhs[0], mprhs[1], mprhs[2], mprhs[3]);
    mlfRestorePreviousContext(0, 4, mprhs[0], mprhs[1], mprhs[2], mprhs[3]);
    plhs[0] = mplhs[0];
    for (i = 1; i < 3 && i < nlhs; ++i) {
        plhs[i] = mplhs[i];
    }
    for (; i < 3; ++i) {
        mxDestroyArray(mplhs[i]);
    }
}

/*
 * The function "mlfPrognoz_maxr_findcursost" contains the normal interface for
 * the "prognoz_maxr/findcursost" M-function from file
 * "d:\dayly\20080807\markovchains1_1mex20080807\prognoz_maxr.m" (lines
 * 243-258). This function processes any input arguments and passes them to the
 * implementation version of the function, appearing above.
 */
static mxArray * mlfPrognoz_maxr_findcursost(mxArray * * place,
                                             mxArray * ysost,
                                             mxArray * dt,
                                             mxArray * cursost) {
    int nargout = 1;
    mxArray * vector_col = NULL;
    mxArray * place__ = NULL;
    mlfEnterNewContext(1, 3, place, ysost, dt, cursost);
    if (place != NULL) {
        ++nargout;
    }
    vector_col
      = Mprognoz_maxr_findcursost(&place__, nargout, ysost, dt, cursost);
    mlfRestorePreviousContext(1, 3, place, ysost, dt, cursost);
    if (place != NULL) {
        mclCopyOutputArg(place, place__);
    } else {
        mxDestroyArray(place__);
    }
    return mlfReturnValue(vector_col);
}

/*
 * The function "mlxPrognoz_maxr_findcursost" contains the feval interface for
 * the "prognoz_maxr/findcursost" M-function from file
 * "d:\dayly\20080807\markovchains1_1mex20080807\prognoz_maxr.m" (lines
 * 243-258). The feval function calls the implementation version of
 * prognoz_maxr/findcursost through this function. This function processes any
 * input arguments and passes them to the implementation version of the
 * function, appearing above.
 */
static void mlxPrognoz_maxr_findcursost(int nlhs,
                                        mxArray * plhs[],
                                        int nrhs,
                                        mxArray * prhs[]) {
    mxArray * mprhs[3];
    mxArray * mplhs[2];
    int i;
    if (nlhs > 2) {
        mlfError(
          mxCreateString(
            "Run-time Error: File: prognoz_maxr/findcursost Line: 243 C"
            "olumn: 1 The function \"prognoz_maxr/findcursost\" was cal"
            "led with more than the declared number of outputs (2)."),
          NULL);
    }
    if (nrhs > 3) {
        mlfError(
          mxCreateString(
            "Run-time Error: File: prognoz_maxr/findcursost Line: 243 "
            "Column: 1 The function \"prognoz_maxr/findcursost\" was c"
            "alled with more than the declared number of inputs (3)."),
          NULL);
    }
    for (i = 0; i < 2; ++i) {
        mplhs[i] = NULL;
    }
    for (i = 0; i < 3 && i < nrhs; ++i) {
        mprhs[i] = prhs[i];
    }
    for (; i < 3; ++i) {
        mprhs[i] = NULL;
    }
    mlfEnterNewContext(0, 3, mprhs[0], mprhs[1], mprhs[2]);
    mplhs[0]
      = Mprognoz_maxr_findcursost(
          &mplhs[1], nlhs, mprhs[0], mprhs[1], mprhs[2]);
    mlfRestorePreviousContext(0, 3, mprhs[0], mprhs[1], mprhs[2]);
    plhs[0] = mplhs[0];
    for (i = 1; i < 2 && i < nlhs; ++i) {
        plhs[i] = mplhs[i];
    }
    for (; i < 2; ++i) {
        mxDestroyArray(mplhs[i]);
    }
}

/*
 * The function "Mprognoz_maxr" is the implementation version of the
 * "prognoz_maxr" M-function from file
 * "d:\dayly\20080807\markovchains1_1mex20080807\prognoz_maxr.m" (lines 1-67).
 * It contains the actual compiled code for that M-function. It is a static
 * function and must only be called from one of the interface functions,
 * appearing below.
 */
/*
 * function[mas_newsost,mas_sredn,r_min,r_max,r_avg]=prognoz_maxr(y_urez,dt,r,s,nprognoz,tbeg);
 */
static mxArray * Mprognoz_maxr(mxArray * * mas_sredn,
                               mxArray * * r_min,
                               mxArray * * r_max,
                               mxArray * * r_avg,
                               int nargout_,
                               mxArray * y_urez,
                               mxArray * dt,
                               mxArray * r,
                               mxArray * s,
                               mxArray * nprognoz,
                               mxArray * tbeg) {
    mexLocalFunctionTable save_local_function_table_
      = mclSetCurrentLocalFunctionTable(&_local_function_table_prognoz_maxr);
    mxArray * mas_newsost = NULL;
    mxArray * nextsost = NULL;
    mxArray * place = NULL;
    mxArray * rmax = NULL;
    mxArray * vectorver = NULL;
    mxArray * lastsost = NULL;
    mxArray * beg = NULL;
    mxArray * i = NULL;
    mxArray * sumr = NULL;
    mxArray * minlen = NULL;
    mxArray * sost4prognoz = NULL;
    mxArray * kkk = NULL;
    mxArray * matrix_kol = NULL;
    mxArray * stdotklon_all = NULL;
    mxArray * stdotklon_group = NULL;
    mxArray * sredn_sost = NULL;
    mxArray * ysost = NULL;
    mxArray * dy = NULL;
    mxArray * ans = NULL;
    mxArray * N1 = NULL;
    mclCopyArray(&y_urez);
    mclCopyArray(&dt);
    mclCopyArray(&r);
    mclCopyArray(&s);
    mclCopyArray(&nprognoz);
    mclCopyArray(&tbeg);
    /*
     * % Функция прогнозирования, с использованием цепи максимального порядка.
     * % Пытаемся найти все повторения предыстории (не менее указанного количества
     * % повторений) и по их исходах прогнозируется вероятность следующего
     * % состояния.
     * %y_urez - ряд для прогноза ,dt - дискретизация ряда, которую нужно
     * %проделать,r - порядок цепи,s - количество уровней квантования,n -
     * %,bif_flag - флаг бифуркаций. Если 0 - выбирается меньшая, 1 - большая.
     * %tbeg - место начала прогноза
     * %Глобальная переменная.
     * %Блок дискретизации приращений. Из урезанного временного ряда получаем
     * %массив приращений с шагом дх.
     * N1=length(y_urez);
     */
    mlfAssign(&N1, mlfScalar(mclLengthInt(mclVa(y_urez, "y_urez"))));
    /*
     * global type_prirash;
     * if isempty(type_prirash)
     */
    if (mlfTobool(mlfIsempty(mclVg(&type_prirash, "type_prirash")))) {
        /*
         * type_prirash=0;
         */
        mlfAssign(mclPrepareGlobal(&type_prirash), _mxarray0_);
    /*
     * end
     */
    }
    /*
     * if type_prirash==0
     */
    if (mclEqBool(mclVg(&type_prirash, "type_prirash"), _mxarray0_)) {
        /*
         * dy=y_urez(dt+1:N1)-y_urez(1:N1-dt);% абсолютные приращения.
         */
        mlfAssign(
          &dy,
          mclMinus(
            mclArrayRef1(
              mclVa(y_urez, "y_urez"),
              mlfColon(
                mclPlus(mclVa(dt, "dt"), _mxarray1_), mclVv(N1, "N1"), NULL)),
            mclArrayRef1(
              mclVa(y_urez, "y_urez"),
              mlfColon(
                _mxarray1_,
                mclMinus(mclVv(N1, "N1"), mclVa(dt, "dt")),
                NULL))));
    /*
     * else
     */
    } else {
        /*
         * dy=(y_urez(dt+1:N1)-y_urez(1:N1-dt))./y_urez(dt+1:N1);% Относительные приращения
         */
        mlfAssign(
          &dy,
          mclRdivide(
            mclMinus(
              mclArrayRef1(
                mclVa(y_urez, "y_urez"),
                mlfColon(
                  mclPlus(mclVa(dt, "dt"), _mxarray1_), mclVv(N1, "N1"), NULL)),
              mclArrayRef1(
                mclVa(y_urez, "y_urez"),
                mlfColon(
                  _mxarray1_,
                  mclMinus(mclVv(N1, "N1"), mclVa(dt, "dt")),
                  NULL))),
            mclArrayRef1(
              mclVa(y_urez, "y_urez"),
              mlfColon(
                mclPlus(mclVa(dt, "dt"), _mxarray1_), mclVv(N1, "N1"), NULL))));
    /*
     * end
     */
    }
    /*
     * 
     * 
     * % Блок преобразования приращений в номера состояний, подсчет вероятностей
     * % переходов
     * %raspr=raspred_veroyatn(dy,10);
     * [ysost,sredn_sost,stdotklon_group,stdotklon_all,matrix_kol]=dy2sost(dy,s,r,dt);
     */
    mlfAssign(
      &ysost,
      mlfDy2sost(
        &sredn_sost,
        &stdotklon_group,
        &stdotklon_all,
        &matrix_kol,
        mclVv(dy, "dy"),
        mclVa(s, "s"),
        mclVa(r, "r"),
        mclVa(dt, "dt")));
    /*
     * % блок прогнозирования. 
     * mas_sredn=sredn_sost;
     */
    mlfAssign(mas_sredn, mclVv(sredn_sost, "sredn_sost"));
    /*
     * %Готовим начальные состояния
     * kkk=ceil(tbeg/dt)-1;
     */
    mlfAssign(
      &kkk,
      mclMinus(
        mlfCeil(mclMrdivide(mclVa(tbeg, "tbeg"), mclVa(dt, "dt"))),
        _mxarray1_));
    /*
     * sost4prognoz=ysost(tbeg-kkk*dt:dt:tbeg-dt);
     */
    mlfAssign(
      &sost4prognoz,
      mclArrayRef1(
        mclVv(ysost, "ysost"),
        mlfColon(
          mclMinus(
            mclVa(tbeg, "tbeg"), mclMtimes(mclVv(kkk, "kkk"), mclVa(dt, "dt"))),
          mclVa(dt, "dt"),
          mclMinus(mclVa(tbeg, "tbeg"), mclVa(dt, "dt")))));
    /*
     * minlen=floor(length(sost4prognoz))-1;
     */
    mlfAssign(
      &minlen,
      mlfScalar(
        svDoubleScalarMinus(
          svDoubleScalarFloor(
            (double) mclLengthInt(mclVv(sost4prognoz, "sost4prognoz"))),
          1.0)));
    /*
     * mas_newsost=[];
     */
    mlfAssign(&mas_newsost, _mxarray2_);
    /*
     * global bif_flag; 
     * bif_flag=1;
     */
    mlfAssign(mclPrepareGlobal(&bif_flag), _mxarray1_);
    /*
     * %h=waitbar(0,strcat('Calculating dt=',num2str(dt)));
     * r_min=99999;
     */
    mlfAssign(r_min, _mxarray3_);
    /*
     * r_max=0;
     */
    mlfAssign(r_max, _mxarray0_);
    /*
     * r_avg=0;
     */
    mlfAssign(r_avg, _mxarray0_);
    /*
     * sumr=0;
     */
    mlfAssign(&sumr, _mxarray0_);
    /*
     * for i=1:nprognoz
     */
    {
        int v_ = mclForIntStart(1);
        int e_ = mclForIntEnd(mclVa(nprognoz, "nprognoz"));
        if (v_ > e_) {
            mlfAssign(&i, _mxarray2_);
        } else {
            /*
             * beg=length(sost4prognoz)-minlen;
             * lastsost=sost4prognoz(beg:beg+minlen);
             * [vectorver,rmax,place]=findnextver(ysost,dt,lastsost,1);
             * nextsost=vector2sost(vectorver);
             * mas_newsost=[mas_newsost,nextsost];
             * sost4prognoz=[sost4prognoz,nextsost];
             * % Подсчет статистики по р для исследования параметров с и к.
             * if (rmax>r_max)
             * r_max=rmax;
             * end
             * if (rmax<r_min)
             * r_min=rmax;
             * end
             * sumr=sumr+rmax;
             * %fprintf(1,'%d\n',nextsost);
             * %waitbar(i/nprognoz,h);
             * %i
             * %nprognoz
             * end
             */
            for (; ; ) {
                mlfAssign(
                  &beg,
                  mclMinus(
                    mlfScalar(
                      mclLengthInt(mclVv(sost4prognoz, "sost4prognoz"))),
                    mclVv(minlen, "minlen")));
                mlfAssign(
                  &lastsost,
                  mclArrayRef1(
                    mclVv(sost4prognoz, "sost4prognoz"),
                    mlfColon(
                      mclVv(beg, "beg"),
                      mclPlus(mclVv(beg, "beg"), mclVv(minlen, "minlen")),
                      NULL)));
                mlfAssign(
                  &vectorver,
                  mlfPrognoz_maxr_findnextver(
                    &rmax,
                    &place,
                    mclVv(ysost, "ysost"),
                    mclVa(dt, "dt"),
                    mclVv(lastsost, "lastsost"),
                    _mxarray1_));
                mlfAssign(
                  &nextsost,
                  mlfPrognoz_maxr_vector2sost(mclVv(vectorver, "vectorver")));
                mlfAssign(
                  &mas_newsost,
                  mlfHorzcat(
                    mclVv(mas_newsost, "mas_newsost"),
                    mclVv(nextsost, "nextsost"),
                    NULL));
                mlfAssign(
                  &sost4prognoz,
                  mlfHorzcat(
                    mclVv(sost4prognoz, "sost4prognoz"),
                    mclVv(nextsost, "nextsost"),
                    NULL));
                if (mclGtBool(mclVv(rmax, "rmax"), mclVv(*r_max, "r_max"))) {
                    mlfAssign(r_max, mclVv(rmax, "rmax"));
                }
                if (mclLtBool(mclVv(rmax, "rmax"), mclVv(*r_min, "r_min"))) {
                    mlfAssign(r_min, mclVv(rmax, "rmax"));
                }
                mlfAssign(
                  &sumr, mclPlus(mclVv(sumr, "sumr"), mclVv(rmax, "rmax")));
                if (v_ == e_) {
                    break;
                }
                ++v_;
            }
            mlfAssign(&i, mlfScalar(v_));
        }
    }
    /*
     * r_avg=sumr/nprognoz;
     */
    mlfAssign(
      r_avg, mclMrdivide(mclVv(sumr, "sumr"), mclVa(nprognoz, "nprognoz")));
    mclValidateOutput(mas_newsost, 1, nargout_, "mas_newsost", "prognoz_maxr");
    mclValidateOutput(*mas_sredn, 2, nargout_, "mas_sredn", "prognoz_maxr");
    mclValidateOutput(*r_min, 3, nargout_, "r_min", "prognoz_maxr");
    mclValidateOutput(*r_max, 4, nargout_, "r_max", "prognoz_maxr");
    mclValidateOutput(*r_avg, 5, nargout_, "r_avg", "prognoz_maxr");
    mxDestroyArray(N1);
    mxDestroyArray(ans);
    mxDestroyArray(dy);
    mxDestroyArray(ysost);
    mxDestroyArray(sredn_sost);
    mxDestroyArray(stdotklon_group);
    mxDestroyArray(stdotklon_all);
    mxDestroyArray(matrix_kol);
    mxDestroyArray(kkk);
    mxDestroyArray(sost4prognoz);
    mxDestroyArray(minlen);
    mxDestroyArray(sumr);
    mxDestroyArray(i);
    mxDestroyArray(beg);
    mxDestroyArray(lastsost);
    mxDestroyArray(vectorver);
    mxDestroyArray(rmax);
    mxDestroyArray(place);
    mxDestroyArray(nextsost);
    mxDestroyArray(tbeg);
    mxDestroyArray(nprognoz);
    mxDestroyArray(s);
    mxDestroyArray(r);
    mxDestroyArray(dt);
    mxDestroyArray(y_urez);
    mclSetCurrentLocalFunctionTable(save_local_function_table_);
    return mas_newsost;
    /*
     * %close(h);
     * 
     * 
     */
}

/*
 * The function "Mprognoz_maxr_vector2sost" is the implementation version of
 * the "prognoz_maxr/vector2sost" M-function from file
 * "d:\dayly\20080807\markovchains1_1mex20080807\prognoz_maxr.m" (lines
 * 67-144). It contains the actual compiled code for that M-function. It is a
 * static function and must only be called from one of the interface functions,
 * appearing below.
 */
/*
 * function newsost=vector2sost(vector_ver);
 */
static mxArray * Mprognoz_maxr_vector2sost(int nargout_, mxArray * vector_ver) {
    mexLocalFunctionTable save_local_function_table_
      = mclSetCurrentLocalFunctionTable(&_local_function_table_prognoz_maxr);
    mxArray * newsost = NULL;
    mxArray * kk = NULL;
    mxArray * bestcenters = NULL;
    mxArray * blizhnsost = NULL;
    mxArray * sost_sredn = NULL;
    mxArray * maxclusters = NULL;
    mxArray * ans = NULL;
    mxArray * mid = NULL;
    mxArray * sumthreshold = NULL;
    mxArray * nmaxsost = NULL;
    mxArray * jj = NULL;
    mxArray * sostmax = NULL;
    mxArray * numsost = NULL;
    mxArray * newsost2 = NULL;
    mxArray * summ = NULL;
    mxArray * newsostrnd = NULL;
    mxArray * newsostsum = NULL;
    mxArray * verthreshold = NULL;
    mclCopyArray(&vector_ver);
    /*
     * % Функция определения наиболее вероятного следующего состояния по вектору
     * % вероятностей перехода в другие состояния.
     * %verthreshold=max(matrix_ver(numsost_prev,1:numsost));
     * verthreshold=max(vector_ver);
     */
    mlfAssign(
      &verthreshold, mlfMax(NULL, mclVa(vector_ver, "vector_ver"), NULL, NULL));
    /*
     * newsostsum=sum(vector_ver);
     */
    mlfAssign(&newsostsum, mlfSum(mclVa(vector_ver, "vector_ver"), NULL));
    /*
     * newsostrnd=round(random('unif',1,newsostsum));
     */
    mlfAssign(
      &newsostrnd,
      mlfRound(
        mlfRandom(
          _mxarray4_,
          _mxarray1_,
          mclVv(newsostsum, "newsostsum"),
          NULL,
          NULL,
          NULL)));
    /*
     * summ=0;
     */
    mlfAssign(&summ, _mxarray0_);
    /*
     * newsost2=0;
     */
    mlfAssign(&newsost2, _mxarray0_);
    /*
     * numsost=length(vector_ver);
     */
    mlfAssign(
      &numsost, mlfScalar(mclLengthInt(mclVa(vector_ver, "vector_ver"))));
    /*
     * sostmax=[];
     */
    mlfAssign(&sostmax, _mxarray2_);
    /*
     * for jj=1:numsost
     */
    {
        int v_ = mclForIntStart(1);
        int e_ = mclForIntEnd(mclVv(numsost, "numsost"));
        if (v_ > e_) {
            mlfAssign(&jj, _mxarray2_);
        } else {
            /*
             * if (vector_ver(jj)>=verthreshold)
             * sostmax=[sostmax,jj];
             * end
             * summ=summ+vector_ver(jj);
             * if ((summ>newsostrnd)&&(newsost2==numsost))
             * newsost2=jj;
             * end
             * end
             */
            for (; ; ) {
                if (mclGeBool(
                      mclIntArrayRef1(mclVa(vector_ver, "vector_ver"), v_),
                      mclVv(verthreshold, "verthreshold"))) {
                    mlfAssign(
                      &sostmax,
                      mlfHorzcat(
                        mclVv(sostmax, "sostmax"), mlfScalar(v_), NULL));
                }
                mlfAssign(
                  &summ,
                  mclPlus(
                    mclVv(summ, "summ"),
                    mclIntArrayRef1(mclVa(vector_ver, "vector_ver"), v_)));
                if (mclScalarToBool(
                      mclGt(
                        mclVv(summ, "summ"), mclVv(newsostrnd, "newsostrnd")))
                    && mclScalarToBool(
                         mclEq(
                           mclVv(newsost2, "newsost2"),
                           mclVv(numsost, "numsost")))) {
                    mlfAssign(&newsost2, mlfScalar(v_));
                }
                if (v_ == e_) {
                    break;
                }
                ++v_;
            }
            mlfAssign(&jj, mlfScalar(v_));
        }
    }
    /*
     * nmaxsost=length(sostmax);
     */
    mlfAssign(&nmaxsost, mlfScalar(mclLengthInt(mclVv(sostmax, "sostmax"))));
    /*
     * 
     * %inogda weroyatnosti ravny 0. W etom sluchae my ne znaem, kuda poyti.
     * %Predlagaem 
     * %global masstat;
     * %r=length(masstat)+1;
     * sumthreshold=2; % количество появления события, которое считаем очень редким и вынуждены рассмотреть цепи меньших порядков.
     */
    mlfAssign(&sumthreshold, _mxarray6_);
    /*
     * mid=round(length(sostmax)/2); 
     */
    mlfAssign(
      &mid,
      mlfScalar(
        svDoubleScalarRound(
          svDoubleScalarRdivide(
            (double) mclLengthInt(mclVv(sostmax, "sostmax")), 2.0))));
    /*
     * if ((mid>0)&&(mid<=length(sostmax)))
     */
    if (mclScalarToBool(mclGt(mclVv(mid, "mid"), _mxarray0_))
        && mclScalarToBool(
             mclLe(
               mclVv(mid, "mid"),
               mlfScalar(mclLengthInt(mclVv(sostmax, "sostmax")))))) {
        /*
         * newsost=sostmax(mid);%naibolee weroyatnoe - posredine
         */
        mlfAssign(
          &newsost, mclArrayRef1(mclVv(sostmax, "sostmax"), mclVv(mid, "mid")));
    /*
     * else
     */
    } else {
        /*
         * -99999
         */
        mclPrintAns(&ans, _mxarray7_);
    /*
     * end
     */
    }
    /*
     * % Ситуация нескольких наиболее вероятных состояний. Выбор одного или двух
     * % (в случае бифуркации).
     * if (nmaxsost>1)
     */
    if (mclGtBool(mclVv(nmaxsost, "nmaxsost"), _mxarray1_)) {
        /*
         * sostmax;
         */
        mclVv(sostmax, "sostmax");
        /*
         * % Алгоритм: 1) найти наибольшие кластеры (группы соседних точек с
         * % наибольшим количеством)
         * maxclusters=getclusters(sostmax,numsost);
         */
        mlfAssign(
          &maxclusters,
          mlfPrognoz_maxr_getclusters(
            mclVv(sostmax, "sostmax"), mclVv(numsost, "numsost")));
        /*
         * sost_sredn=round(numsost/2);
         */
        mlfAssign(
          &sost_sredn,
          mlfRound(mclMrdivide(mclVv(numsost, "numsost"), _mxarray6_)));
        /*
         * blizhnsost=numsost;
         */
        mlfAssign(&blizhnsost, mclVv(numsost, "numsost"));
        /*
         * bestcenters=[];
         */
        mlfAssign(&bestcenters, _mxarray2_);
        /*
         * for kk=1:length(maxclusters)
         */
        {
            int v_ = mclForIntStart(1);
            int e_ = mclLengthInt(mclVv(maxclusters, "maxclusters"));
            if (v_ > e_) {
                mlfAssign(&kk, _mxarray2_);
            } else {
                /*
                 * if (abs(maxclusters(kk).center-sost_sredn)<blizhnsost)
                 * bestcenters=maxclusters(kk).center;
                 * blizhnsost=abs(maxclusters(kk).center-sost_sredn);
                 * else
                 * if (maxclusters(kk).center-sost_sredn==blizhnsost)
                 * bestcenters=[bestcenters,maxclusters(kk).center];
                 * end
                 * end
                 * end
                 */
                for (; ; ) {
                    if (mclLtBool(
                          mlfAbs(
                            mclFeval(
                              mclValueVarargout(),
                              mlxMinus,
                              mlfIndexRef(
                                mclVv(maxclusters, "maxclusters"),
                                "(?).center",
                                mlfScalar(v_)),
                              mclVv(sost_sredn, "sost_sredn"),
                              NULL)),
                          mclVv(blizhnsost, "blizhnsost"))) {
                        mlfAssign(
                          &bestcenters,
                          mlfIndexRef(
                            mclVv(maxclusters, "maxclusters"),
                            "(?).center",
                            mlfScalar(v_)));
                        mlfAssign(
                          &blizhnsost,
                          mlfAbs(
                            mclFeval(
                              mclValueVarargout(),
                              mlxMinus,
                              mlfIndexRef(
                                mclVv(maxclusters, "maxclusters"),
                                "(?).center",
                                mlfScalar(v_)),
                              mclVv(sost_sredn, "sost_sredn"),
                              NULL)));
                    } else {
                        if (mclEqBool(
                              mclFeval(
                                mclValueVarargout(),
                                mlxMinus,
                                mlfIndexRef(
                                  mclVv(maxclusters, "maxclusters"),
                                  "(?).center",
                                  mlfScalar(v_)),
                                mclVv(sost_sredn, "sost_sredn"),
                                NULL),
                              mclVv(blizhnsost, "blizhnsost"))) {
                            mlfAssign(
                              &bestcenters,
                              mlfHorzcat(
                                mclVv(bestcenters, "bestcenters"),
                                mlfIndexRef(
                                  mclVv(maxclusters, "maxclusters"),
                                  "(?).center",
                                  mlfScalar(v_)),
                                NULL));
                        }
                    }
                    if (v_ == e_) {
                        break;
                    }
                    ++v_;
                }
                mlfAssign(&kk, mlfScalar(v_));
            }
        }
        /*
         * newsost=bestcenters;
         */
        mlfAssign(&newsost, mclVv(bestcenters, "bestcenters"));
        /*
         * global bif_flag; %Выбираем одну из бифуркаций, в зависимости от глобальных настроек (значения глобальной переменной bif_flag)
         * if (length(newsost)>1)
         */
        if (mclLengthInt(mclVv(newsost, "newsost")) > 1) {
            /*
             * if isempty(bif_flag) %не задана переменная для выбора вида бифуркации.
             */
            if (mlfTobool(mlfIsempty(mclVg(&bif_flag, "bif_flag")))) {
                /*
                 * newsost=newsost(1);
                 */
                mlfAssign(
                  &newsost, mclIntArrayRef1(mclVv(newsost, "newsost"), 1));
            /*
             * else
             */
            } else {
                /*
                 * newsost=newsost(2);
                 */
                mlfAssign(
                  &newsost, mclIntArrayRef1(mclVv(newsost, "newsost"), 2));
            /*
             * end
             */
            }
        /*
         * end
         */
        }
    /*
     * 
     * % 2) Из них выбрать тот, который ближе к центру.
     * % 3) Если всего 2 кластера и оба на одинаковом расстоянии от центра -
     * % делается бифуркация (выбирается 2 варианта)
     * % 4) при выборе состояния из кластера выбирается точка середины
     * % кластера.
     * end
     */
    }
    /*
     * % wariant # 2 сгенерировать следующее состояние случайно, но по
     * % вероятностям, указанных в векторе переходов.
     * if (newsost2>0)
     */
    if (mclGtBool(mclVv(newsost2, "newsost2"), _mxarray0_)) {
    /*
     * %newsost=newsost2;%Принимаем во внимание следуюшее по 2-й методике.
     * %Если закоментировать предыдущую строку, будет считаться 1-я методика -
     * %наиболее вероятное состояние.
     * end
     */
    }
    mclValidateOutput(
      newsost, 1, nargout_, "newsost", "prognoz_maxr/vector2sost");
    mxDestroyArray(verthreshold);
    mxDestroyArray(newsostsum);
    mxDestroyArray(newsostrnd);
    mxDestroyArray(summ);
    mxDestroyArray(newsost2);
    mxDestroyArray(numsost);
    mxDestroyArray(sostmax);
    mxDestroyArray(jj);
    mxDestroyArray(nmaxsost);
    mxDestroyArray(sumthreshold);
    mxDestroyArray(mid);
    mxDestroyArray(ans);
    mxDestroyArray(maxclusters);
    mxDestroyArray(sost_sredn);
    mxDestroyArray(blizhnsost);
    mxDestroyArray(bestcenters);
    mxDestroyArray(kk);
    mxDestroyArray(vector_ver);
    mclSetCurrentLocalFunctionTable(save_local_function_table_);
    return newsost;
    /*
     * 
     */
}

/*
 * The function "Mprognoz_maxr_getclusters" is the implementation version of
 * the "prognoz_maxr/getclusters" M-function from file
 * "d:\dayly\20080807\markovchains1_1mex20080807\prognoz_maxr.m" (lines
 * 144-208). It contains the actual compiled code for that M-function. It is a
 * static function and must only be called from one of the interface functions,
 * appearing below.
 */
/*
 * function  maxclusters=getclusters(sostmax,nsost);
 */
static mxArray * Mprognoz_maxr_getclusters(int nargout_,
                                           mxArray * sostmax,
                                           mxArray * nsost) {
    mexLocalFunctionTable save_local_function_table_
      = mclSetCurrentLocalFunctionTable(&_local_function_table_prognoz_maxr);
    mxArray * maxclusters = NULL;
    mxArray * ncl = NULL;
    mxArray * str = NULL;
    mxArray * i = NULL;
    mxArray * maxelems = NULL;
    mxArray * clusters = NULL;
    mxArray * ncluster = NULL;
    mxArray * elements = NULL;
    mxArray * n = NULL;
    mclCopyArray(&sostmax);
    mclCopyArray(&nsost);
    /*
     * % находим все кластеры 
     * n=length(sostmax);
     */
    mlfAssign(&n, mlfScalar(mclLengthInt(mclVa(sostmax, "sostmax"))));
    /*
     * elements=sostmax(1);
     */
    mlfAssign(&elements, mclIntArrayRef1(mclVa(sostmax, "sostmax"), 1));
    /*
     * ncluster=1;
     */
    mlfAssign(&ncluster, _mxarray1_);
    /*
     * clusters=[];
     */
    mlfAssign(&clusters, _mxarray2_);
    /*
     * maxelems=0;
     */
    mlfAssign(&maxelems, _mxarray0_);
    /*
     * for i=2:n
     */
    {
        int v_ = mclForIntStart(2);
        int e_ = mclForIntEnd(mclVv(n, "n"));
        if (v_ > e_) {
            mlfAssign(&i, _mxarray2_);
        } else {
            /*
             * if (sostmax(i-1)+1==sostmax(i))%кластер продолжаетсz
             * elements=[elements,sostmax(i)];
             * ncluster=ncluster+1;
             * else % кластер закончился
             * str=[];
             * str.n=ncluster;
             * str.elements=elements;
             * if (mod(ncluster,2)==0) %Если кол-во элементов в кластере четное - неизвестно какой из центральных брать.
             * if (elements(ceil(ncluster/2))<round(nsost/2))
             * str.center=elements(ceil(ncluster/2)+1);%слева от центра. Берем правую точку.
             * else
             * str.center=elements(ceil(ncluster/2));%справа от центра. Берем левую точку.  
             * end 
             * else % Если нечетное - точно есть центральное значение.
             * str.center=elements(ceil(ncluster/2));
             * end
             * clusters=[clusters,str];
             * if (ncluster>maxelems)
             * maxelems=ncluster;
             * end
             * elements=sostmax(i);
             * ncluster=1;
             * end
             * end
             */
            for (; ; ) {
                if (mclEqBool(
                      mclPlus(
                        mclIntArrayRef1(mclVa(sostmax, "sostmax"), v_ - 1),
                        _mxarray1_),
                      mclIntArrayRef1(mclVa(sostmax, "sostmax"), v_))) {
                    mlfAssign(
                      &elements,
                      mlfHorzcat(
                        mclVv(elements, "elements"),
                        mclIntArrayRef1(mclVa(sostmax, "sostmax"), v_),
                        NULL));
                    mlfAssign(
                      &ncluster,
                      mclPlus(mclVv(ncluster, "ncluster"), _mxarray1_));
                } else {
                    mlfAssign(&str, _mxarray2_);
                    mlfIndexAssign(&str, ".n", mclVv(ncluster, "ncluster"));
                    mlfIndexAssign(
                      &str, ".elements", mclVv(elements, "elements"));
                    if (mclEqBool(
                          mlfMod(mclVv(ncluster, "ncluster"), _mxarray6_),
                          _mxarray0_)) {
                        if (mclLtBool(
                              mclArrayRef1(
                                mclVv(elements, "elements"),
                                mlfCeil(
                                  mclMrdivide(
                                    mclVv(ncluster, "ncluster"), _mxarray6_))),
                              mlfRound(
                                mclMrdivide(
                                  mclVa(nsost, "nsost"), _mxarray6_)))) {
                            mlfIndexAssign(
                              &str,
                              ".center",
                              mclArrayRef1(
                                mclVv(elements, "elements"),
                                mclPlus(
                                  mlfCeil(
                                    mclMrdivide(
                                      mclVv(ncluster, "ncluster"), _mxarray6_)),
                                  _mxarray1_)));
                        } else {
                            mlfIndexAssign(
                              &str,
                              ".center",
                              mclArrayRef1(
                                mclVv(elements, "elements"),
                                mlfCeil(
                                  mclMrdivide(
                                    mclVv(ncluster, "ncluster"), _mxarray6_))));
                        }
                    } else {
                        mlfIndexAssign(
                          &str,
                          ".center",
                          mclArrayRef1(
                            mclVv(elements, "elements"),
                            mlfCeil(
                              mclMrdivide(
                                mclVv(ncluster, "ncluster"), _mxarray6_))));
                    }
                    mlfAssign(
                      &clusters,
                      mlfHorzcat(
                        mclVv(clusters, "clusters"), mclVv(str, "str"), NULL));
                    if (mclGtBool(
                          mclVv(ncluster, "ncluster"),
                          mclVv(maxelems, "maxelems"))) {
                        mlfAssign(&maxelems, mclVv(ncluster, "ncluster"));
                    }
                    mlfAssign(
                      &elements,
                      mclIntArrayRef1(mclVa(sostmax, "sostmax"), v_));
                    mlfAssign(&ncluster, _mxarray1_);
                }
                if (v_ == e_) {
                    break;
                }
                ++v_;
            }
            mlfAssign(&i, mlfScalar(v_));
        }
    }
    /*
     * str=[];
     */
    mlfAssign(&str, _mxarray2_);
    /*
     * str.n=ncluster;
     */
    mlfIndexAssign(&str, ".n", mclVv(ncluster, "ncluster"));
    /*
     * str.elements=elements;
     */
    mlfIndexAssign(&str, ".elements", mclVv(elements, "elements"));
    /*
     * if (mod(ncluster,2)==0) %Если кол-во элементов в кластере четное - неизвестно какой из центральных брать.
     */
    if (mclEqBool(
          mlfMod(mclVv(ncluster, "ncluster"), _mxarray6_), _mxarray0_)) {
        /*
         * if (elements(ceil(ncluster/2))<round(nsost/2))
         */
        if (mclLtBool(
              mclArrayRef1(
                mclVv(elements, "elements"),
                mlfCeil(mclMrdivide(mclVv(ncluster, "ncluster"), _mxarray6_))),
              mlfRound(mclMrdivide(mclVa(nsost, "nsost"), _mxarray6_)))) {
            /*
             * str.center=elements(ceil(ncluster/2)+1);%слева от центра. Берем правую точку.
             */
            mlfIndexAssign(
              &str,
              ".center",
              mclArrayRef1(
                mclVv(elements, "elements"),
                mclPlus(
                  mlfCeil(mclMrdivide(mclVv(ncluster, "ncluster"), _mxarray6_)),
                  _mxarray1_)));
        /*
         * else
         */
        } else {
            /*
             * str.center=elements(ceil(ncluster/2));%справа от центра. Берем левую точку.  
             */
            mlfIndexAssign(
              &str,
              ".center",
              mclArrayRef1(
                mclVv(elements, "elements"),
                mlfCeil(mclMrdivide(mclVv(ncluster, "ncluster"), _mxarray6_))));
        /*
         * end 
         */
        }
    /*
     * else % Если нечетное - точно есть центральное значение.
     */
    } else {
        /*
         * str.center=elements(ceil(ncluster/2));
         */
        mlfIndexAssign(
          &str,
          ".center",
          mclArrayRef1(
            mclVv(elements, "elements"),
            mlfCeil(mclMrdivide(mclVv(ncluster, "ncluster"), _mxarray6_))));
    /*
     * end
     */
    }
    /*
     * clusters=[clusters,str];
     */
    mlfAssign(
      &clusters,
      mlfHorzcat(mclVv(clusters, "clusters"), mclVv(str, "str"), NULL));
    /*
     * if (ncluster>maxelems)
     */
    if (mclGtBool(mclVv(ncluster, "ncluster"), mclVv(maxelems, "maxelems"))) {
        /*
         * maxelems=ncluster;
         */
        mlfAssign(&maxelems, mclVv(ncluster, "ncluster"));
    /*
     * end
     */
    }
    /*
     * % Выбор максимальных кластеров
     * ncl=length(clusters);
     */
    mlfAssign(&ncl, mlfScalar(mclLengthInt(mclVv(clusters, "clusters"))));
    /*
     * maxclusters=[];
     */
    mlfAssign(&maxclusters, _mxarray2_);
    /*
     * for i=1:ncl
     */
    {
        int v_ = mclForIntStart(1);
        int e_ = mclForIntEnd(mclVv(ncl, "ncl"));
        if (v_ > e_) {
            mlfAssign(&i, _mxarray2_);
        } else {
            /*
             * if (clusters(i).n==maxelems)
             * maxclusters=[maxclusters,clusters(i)];
             * end
             * end
             */
            for (; ; ) {
                if (mlfTobool(
                      mclFeval(
                        mclValueVarargout(),
                        mlxEq,
                        mlfIndexRef(
                          mclVv(clusters, "clusters"), "(?).n", mlfScalar(v_)),
                        mclVv(maxelems, "maxelems"),
                        NULL))) {
                    mlfAssign(
                      &maxclusters,
                      mlfHorzcat(
                        mclVv(maxclusters, "maxclusters"),
                        mclIntArrayRef1(mclVv(clusters, "clusters"), v_),
                        NULL));
                }
                if (v_ == e_) {
                    break;
                }
                ++v_;
            }
            mlfAssign(&i, mlfScalar(v_));
        }
    }
    mclValidateOutput(
      maxclusters, 1, nargout_, "maxclusters", "prognoz_maxr/getclusters");
    mxDestroyArray(n);
    mxDestroyArray(elements);
    mxDestroyArray(ncluster);
    mxDestroyArray(clusters);
    mxDestroyArray(maxelems);
    mxDestroyArray(i);
    mxDestroyArray(str);
    mxDestroyArray(ncl);
    mxDestroyArray(nsost);
    mxDestroyArray(sostmax);
    mclSetCurrentLocalFunctionTable(save_local_function_table_);
    return maxclusters;
    /*
     * 
     * %function centers=getcenters(maxclusters);
     * % возвращает центры кластеров
     * 
     * %% Ошибка! В случае, когда кластер с четным количеством эл-тов попадает
     * %% ровно на центр распределения. Необходимо брать 2 центральных варианта.
     * %% вариант 2 - рассмотрен в рукописях номер 13. 
     * 
     */
}

/*
 * The function "Mprognoz_maxr_findnextver" is the implementation version of
 * the "prognoz_maxr/findnextver" M-function from file
 * "d:\dayly\20080807\markovchains1_1mex20080807\prognoz_maxr.m" (lines
 * 208-243). It contains the actual compiled code for that M-function. It is a
 * static function and must only be called from one of the interface functions,
 * appearing below.
 */
/*
 * function [vectorver,rmax,place]=findnextver(ysost,dt,sost4prognoz,minnum);
 */
static mxArray * Mprognoz_maxr_findnextver(mxArray * * rmax,
                                           mxArray * * place,
                                           int nargout_,
                                           mxArray * ysost,
                                           mxArray * dt,
                                           mxArray * sost4prognoz,
                                           mxArray * minnum) {
    mexLocalFunctionTable save_local_function_table_
      = mclSetCurrentLocalFunctionTable(&_local_function_table_prognoz_maxr);
    mxArray * vectorver = NULL;
    mxArray * cursost = NULL;
    mxArray * rmin = NULL;
    mxArray * sposob = NULL;
    mxArray * vector_col = NULL;
    mxArray * i = NULL;
    mxArray * maxlength = NULL;
    mxArray * len = NULL;
    mclCopyArray(&ysost);
    mclCopyArray(&dt);
    mclCopyArray(&sost4prognoz);
    mclCopyArray(&minnum);
    /*
     * % Функция определения следующего состояния.
     * %Тестирование процесса выбора значения.
     * %vectorver=[0.3 0.5 0.1 0.6 0.6]; %тест выбора максимума Наче работает.
     * len=length(sost4prognoz);
     */
    mlfAssign(
      &len, mlfScalar(mclLengthInt(mclVa(sost4prognoz, "sost4prognoz"))));
    /*
     * maxlength=length(ysost)/dt;
     */
    mlfAssign(
      &maxlength,
      mclMrdivide(
        mlfScalar(mclLengthInt(mclVa(ysost, "ysost"))), mclVa(dt, "dt")));
    /*
     * i=len-1;
     */
    mlfAssign(&i, mclMinus(mclVv(len, "len"), _mxarray1_));
    /*
     * place=[];
     */
    mlfAssign(place, _mxarray2_);
    /*
     * vector_col=0;
     */
    mlfAssign(&vector_col, _mxarray0_);
    /*
     * sposob=0; %способ приближения к нужному р. 0 - уменьшением в 2 р, 1 - уменьшение на 1 единицу
     */
    mlfAssign(&sposob, _mxarray0_);
    /*
     * rmin=1;
     */
    mlfAssign(&rmin, _mxarray1_);
    /*
     * rmax=len-1;
     */
    mlfAssign(rmax, mclMinus(mclVv(len, "len"), _mxarray1_));
    /*
     * if (len>0)
     */
    if (mclGtBool(mclVv(len, "len"), _mxarray0_)) {
        /*
         * while (rmax-rmin>1)
         */
        while (mclGtBool(
                 mclMinus(mclVv(*rmax, "rmax"), mclVv(rmin, "rmin")),
                 _mxarray1_)) {
            /*
             * %for i=len-1:-1:0 %цикл для длины предыстории.
             * %i
             * i=floor((rmin+rmax)/2);% srednee
             */
            mlfAssign(
              &i,
              mlfFloor(
                mclMrdivide(
                  mclPlus(mclVv(rmin, "rmin"), mclVv(*rmax, "rmax")),
                  _mxarray6_)));
            /*
             * cursost=sost4prognoz(len-i:len);
             */
            mlfAssign(
              &cursost,
              mclArrayRef1(
                mclVa(sost4prognoz, "sost4prognoz"),
                mlfColon(
                  mclMinus(mclVv(len, "len"), mclVv(i, "i")),
                  mclVv(len, "len"),
                  NULL)));
            /*
             * [vector_col,place]=findcursost(ysost,dt,cursost);
             */
            mlfAssign(
              &vector_col,
              mlfPrognoz_maxr_findcursost(
                place,
                mclVa(ysost, "ysost"),
                mclVa(dt, "dt"),
                mclVv(cursost, "cursost")));
            /*
             * if (sum(vector_col)>=minnum)
             */
            if (mclGeBool(
                  mlfSum(mclVv(vector_col, "vector_col"), NULL),
                  mclVa(minnum, "minnum"))) {
                /*
                 * rmin=i;
                 */
                mlfAssign(&rmin, mclVv(i, "i"));
            /*
             * else 
             */
            } else {
                /*
                 * rmax=i;
                 */
                mlfAssign(rmax, mclVv(i, "i"));
            /*
             * end
             */
            }
        /*
         * end
         */
        }
        /*
         * if (sum(vector_col)>0)
         */
        if (mclGtBool(
              mlfSum(mclVv(vector_col, "vector_col"), NULL), _mxarray0_)) {
            /*
             * vectorver=vector_col./(sum(vector_col));
             */
            mlfAssign(
              &vectorver,
              mclRdivide(
                mclVv(vector_col, "vector_col"),
                mlfSum(mclVv(vector_col, "vector_col"), NULL)));
        /*
         * else
         */
        } else {
            /*
             * vectorver=ones(1,max(ysost));
             */
            mlfAssign(
              &vectorver,
              mlfOnes(
                _mxarray1_,
                mlfMax(NULL, mclVa(ysost, "ysost"), NULL, NULL),
                NULL));
        /*
         * end
         */
        }
    /*
     * else
     */
    } else {
        /*
         * vectorver=ones(1,max(ysost));
         */
        mlfAssign(
          &vectorver,
          mlfOnes(
            _mxarray1_, mlfMax(NULL, mclVa(ysost, "ysost"), NULL, NULL), NULL));
    /*
     * end
     */
    }
    /*
     * rmax=i+1;
     */
    mlfAssign(rmax, mclPlus(mclVv(i, "i"), _mxarray1_));
    mclValidateOutput(
      vectorver, 1, nargout_, "vectorver", "prognoz_maxr/findnextver");
    mclValidateOutput(*rmax, 2, nargout_, "rmax", "prognoz_maxr/findnextver");
    mclValidateOutput(*place, 3, nargout_, "place", "prognoz_maxr/findnextver");
    mxDestroyArray(len);
    mxDestroyArray(maxlength);
    mxDestroyArray(i);
    mxDestroyArray(vector_col);
    mxDestroyArray(sposob);
    mxDestroyArray(rmin);
    mxDestroyArray(cursost);
    mxDestroyArray(minnum);
    mxDestroyArray(sost4prognoz);
    mxDestroyArray(dt);
    mxDestroyArray(ysost);
    mclSetCurrentLocalFunctionTable(save_local_function_table_);
    return vectorver;
    /*
     * 
     */
}

/*
 * The function "Mprognoz_maxr_findcursost" is the implementation version of
 * the "prognoz_maxr/findcursost" M-function from file
 * "d:\dayly\20080807\markovchains1_1mex20080807\prognoz_maxr.m" (lines
 * 243-258). It contains the actual compiled code for that M-function. It is a
 * static function and must only be called from one of the interface functions,
 * appearing below.
 */
/*
 * function  [vector_col,place]=findcursost(ysost,dt,cursost);
 */
static mxArray * Mprognoz_maxr_findcursost(mxArray * * place,
                                           int nargout_,
                                           mxArray * ysost,
                                           mxArray * dt,
                                           mxArray * cursost) {
    mexLocalFunctionTable save_local_function_table_
      = mclSetCurrentLocalFunctionTable(&_local_function_table_prognoz_maxr);
    mxArray * vector_col = NULL;
    mxArray * nextsost = NULL;
    mxArray * currrsost = NULL;
    mxArray * i = NULL;
    mxArray * lasti = NULL;
    mxArray * history = NULL;
    mxArray * numsost = NULL;
    mclCopyArray(&ysost);
    mclCopyArray(&dt);
    mclCopyArray(&cursost);
    /*
     * % Находит все повторения данной предыстории в истории и возвращает вектор
     * % кол-ва выпадения для всех вариантов следующих событий. 
     * numsost=max(ysost);
     */
    mlfAssign(&numsost, mlfMax(NULL, mclVa(ysost, "ysost"), NULL, NULL));
    /*
     * history=length(cursost);
     */
    mlfAssign(&history, mlfScalar(mclLengthInt(mclVa(cursost, "cursost"))));
    /*
     * vector_col=zeros(1,numsost);
     */
    mlfAssign(
      &vector_col, mlfZeros(_mxarray1_, mclVv(numsost, "numsost"), NULL));
    /*
     * lasti=length(ysost)-(history+1)*dt;
     */
    mlfAssign(
      &lasti,
      mclMinus(
        mlfScalar(mclLengthInt(mclVa(ysost, "ysost"))),
        mclMtimes(
          mclPlus(mclVv(history, "history"), _mxarray1_), mclVa(dt, "dt"))));
    /*
     * place=[];
     */
    mlfAssign(place, _mxarray2_);
    /*
     * for i=1:lasti;
     */
    {
        int v_ = mclForIntStart(1);
        int e_ = mclForIntEnd(mclVv(lasti, "lasti"));
        if (v_ > e_) {
            mlfAssign(&i, _mxarray2_);
        } else {
            /*
             * currrsost=ysost(i:dt:i+(history+1)*dt);
             * if (sum(abs(cursost-currrsost(1:history)))/history<=0.01) %найденно нужное состояние
             * nextsost=currrsost(history+1);
             * vector_col(nextsost)=vector_col(nextsost)+1;
             * place=[place,i];
             * end
             * end
             */
            for (; ; ) {
                mlfAssign(
                  &currrsost,
                  mclArrayRef1(
                    mclVa(ysost, "ysost"),
                    mlfColon(
                      mlfScalar(v_),
                      mclVa(dt, "dt"),
                      mclPlus(
                        mlfScalar(v_),
                        mclMtimes(
                          mclPlus(mclVv(history, "history"), _mxarray1_),
                          mclVa(dt, "dt"))))));
                if (mclLeBool(
                      mclMrdivide(
                        mlfSum(
                          mlfAbs(
                            mclMinus(
                              mclVa(cursost, "cursost"),
                              mclArrayRef1(
                                mclVv(currrsost, "currrsost"),
                                mlfColon(
                                  _mxarray1_,
                                  mclVv(history, "history"),
                                  NULL)))),
                          NULL),
                        mclVv(history, "history")),
                      _mxarray8_)) {
                    mlfAssign(
                      &nextsost,
                      mclArrayRef1(
                        mclVv(currrsost, "currrsost"),
                        mclPlus(mclVv(history, "history"), _mxarray1_)));
                    mclArrayAssign1(
                      &vector_col,
                      mclPlus(
                        mclArrayRef1(
                          mclVv(vector_col, "vector_col"),
                          mclVv(nextsost, "nextsost")),
                        _mxarray1_),
                      mclVv(nextsost, "nextsost"));
                    mlfAssign(
                      place,
                      mlfHorzcat(mclVv(*place, "place"), mlfScalar(v_), NULL));
                }
                if (v_ == e_) {
                    break;
                }
                ++v_;
            }
            mlfAssign(&i, mlfScalar(v_));
        }
    }
    mclValidateOutput(
      vector_col, 1, nargout_, "vector_col", "prognoz_maxr/findcursost");
    mclValidateOutput(*place, 2, nargout_, "place", "prognoz_maxr/findcursost");
    mxDestroyArray(numsost);
    mxDestroyArray(history);
    mxDestroyArray(lasti);
    mxDestroyArray(i);
    mxDestroyArray(currrsost);
    mxDestroyArray(nextsost);
    mxDestroyArray(cursost);
    mxDestroyArray(dt);
    mxDestroyArray(ysost);
    mclSetCurrentLocalFunctionTable(save_local_function_table_);
    return vector_col;
}
