static Code line_search_backtracking_owlqn(
            int n,
            double[] x,
            ref double f,
            double[] g,
            double[] s,
            ref double stp,
             double[] xp,
             double[] gp,
            double[] wp,
            ref callback_data_t cd,
             ref lbfgs_parameter_t param
            )
        {
            int i, count = 0;
            double width = 0.5, norm = 0.0;
            double finit = f, dgtest;

            /* Check the input parameters for errors. */
            if (stp <= 0.0)
            {
                return Code.LBFGSERR_INVALIDPARAMETERS;
            }

            /* Choose the orthant for the new point. */
            for (i = 0; i < n; ++i)
            {
                wp[i] = (xp[i] == 0.0) ? -gp[i] : xp[i];
            }

            for (; ; )
            {
                /* Update the current point. */
                veccpy(x, xp, n);
                vecadd(x, s, stp, n);

                /* The current point is projected onto the orthant. */
                owlqn_project(x, wp, param.orthantwise_start, param.orthantwise_end);

                /* Evaluate the function and gradient values. */
                f = cd.proc_evaluate(cd.instance, x, g, cd.n, stp);

                /* Compute the L1 norm of the variables and add it to the object value. */
                norm = owlqn_x1norm(x, param.orthantwise_start, param.orthantwise_end);
                f += norm * param.orthantwise_c;

                ++count;

                dgtest = 0.0;
                for (i = 0; i < n; ++i)
                {
                    dgtest += (x[i] - xp[i]) * gp[i];
                }

                if (f <= finit + param.ftol * dgtest)
                {
                    /* The sufficient decrease condition. */
                    return (Code)count;
                }

                if (stp < param.min_step)
                {
                    /* The step is the minimum value. */
                    return Code.LBFGSERR_MINIMUMSTEP;
                }
                if (stp > param.max_step)
                {
                    /* The step is the maximum value. */
                    return Code.LBFGSERR_MAXIMUMSTEP;
                }
                if (param.max_linesearch <= count)
                {
                    /* Maximum number of iteration. */
                    return Code.LBFGSERR_MAXIMUMLINESEARCH;
                }

                stp *= width;
            }
        }
        internal static int main(double[] start, Func<double[], double> fn, Func<double[], double[]> gn,
            EventHandler<OptimizationProgressEventArgs> progress, lbfgs_parameter_t param)
        {
            double fx = 0;

            lbfgs_evaluate_t target = NewMethod(fn, gn);
            lbfgs_progress_t prog = ProgressMethod(progress);


            /*
                Start the L-BFGS optimization; this will invoke the callback functions
                evaluate() and progress() when necessary.
             */
            var ret = lbfgs(start.Length, start, ref fx, target,
                prog, null, param);

            if ((int)ret < 0)
                fx = fn(start);

            if (progress != null)
                progress(null, new OptimizationProgressEventArgs(0, 0, null, 0, start, 0, fx, 0, false));

            //lbfgs_free(x);
            return (int)ret;
        }
        /*
                static double[] LBFGS_malloc(int n)
                {
                    return new double[n];
                }

                static void LBFGS_free(double[] x)
                {
                }
        */
        static Code lbfgs(
            int n,
            double[] x,
            ref double ptr_fx,
            lbfgs_evaluate_t proc_evaluate,
            lbfgs_progress_t proc_progress,
            object instance,
            lbfgs_parameter_t _param
            )
        {
            Code ret;
            int i, j, k, end, bound;
            Code ls;
            double step;

            /* ant parameters and their default values. */
            lbfgs_parameter_t param = (_param != null) ? (_param) : _defparam;
            int m = param.m;

            double[] xp = null;
            double[] g = null, gp = null, pg = null;
            double[] d = null, w = null, pf = null;
            iteration_data_t[] lm = null;
            iteration_data_t it = null;
            double ys, yy;
            double xnorm, gnorm, beta;
            double fx = 0.0;
            double rate = 0.0;
            line_search_proc linesearch = line_search_morethuente;

            /* ruct a callback data. */
            callback_data_t cd = new callback_data_t();
            cd.n = n;
            cd.instance = instance;
            cd.proc_evaluate = proc_evaluate;
            cd.proc_progress = proc_progress;



            if (param.max_step < param.min_step)
            {
                return Code.LBFGSERR_INVALID_MAXSTEP;
            }
            if (param.ftol < 0.0)
            {
                return Code.LBFGSERR_INVALID_FTOL;
            }


            if (param.linesearch == LineSearch.RegularWolfe ||
                param.linesearch == LineSearch.StrongWolfe)
            {
                if (param.wolfe <= param.ftol || 1.0 <= param.wolfe)
                {
                    return Code.LBFGSERR_INVALID_WOLFE;
                }
            }

            if (param.orthantwise_start < 0 || n < param.orthantwise_start)
            {
                return Code.LBFGSERR_INVALID_ORTHANTWISE_START;
            }
            if (param.orthantwise_end < 0)
            {
                param.orthantwise_end = n;
            }
            if (n < param.orthantwise_end)
            {
                return Code.LBFGSERR_INVALID_ORTHANTWISE_END;
            }

            if (param.orthantwise_c != 0.0)
            {
                switch (param.linesearch)
                {
                    case LineSearch.RegularWolfe:
                        linesearch = line_search_backtracking_owlqn;
                        break;
                    default:
                        /* Only the backtracking method is available. */
                        return Code.LBFGSERR_INVALID_LINESEARCH;
                }
            }
            else
            {
                switch (param.linesearch)
                {
                    case LineSearch.Default:
                        linesearch = line_search_morethuente;
                        break;
                    case LineSearch.BacktrackingArmijo:
                    case LineSearch.RegularWolfe:
                    case LineSearch.StrongWolfe:
                        linesearch = line_search_backtracking;
                        break;
                    default:
                        return Code.LBFGSERR_INVALID_LINESEARCH;
                }
            }

            /* Allocate working space. */
            xp = (double[])vecalloc(n * sizeof(double));
            g = (double[])vecalloc(n * sizeof(double));
            gp = (double[])vecalloc(n * sizeof(double));
            d = (double[])vecalloc(n * sizeof(double));
            w = (double[])vecalloc(n * sizeof(double));
            if (xp == null || g == null || gp == null || d == null || w == null)
            {
                ret = Code.LBFGSERR_OUTOFMEMORY;
                goto lbfgs_exit;
            }

            if (param.orthantwise_c != 0.0)
            {
                /* Allocate working space for OW-LQN. */
                pg = (double[])vecalloc(n * sizeof(double));
                if (pg == null)
                {
                    ret = Code.LBFGSERR_OUTOFMEMORY;
                    goto lbfgs_exit;
                }
            }

            /* Allocate limited memory storage. */
            lm = new iteration_data_t[m];

            if (lm == null)
            {
                ret = Code.LBFGSERR_OUTOFMEMORY;
                goto lbfgs_exit;
            }

            /* Initialize the limited memory. */
            for (i = 0; i < m; ++i)
            {
                it = lm[i] = new iteration_data_t();
                it.alpha = 0;
                it.ys = 0;
                it.s = (double[])vecalloc(n * sizeof(double));
                it.y = (double[])vecalloc(n * sizeof(double));
                if (it.s == null || it.y == null)
                {
                    ret = Code.LBFGSERR_OUTOFMEMORY;
                    goto lbfgs_exit;
                }
            }

            /* Allocate an array for storing previous values of the objective function. */
            if (0 < param.past)
            {
                pf = (double[])vecalloc(param.past * sizeof(double));
            }

            /* Evaluate the function value and its gradient. */
            fx = cd.proc_evaluate(cd.instance, x, g, cd.n, 0);
            if (0.0 != param.orthantwise_c)
            {
                /* Compute the L1 norm of the variable and add it to the object value. */
                xnorm = owlqn_x1norm(x, param.orthantwise_start, param.orthantwise_end);
                fx += xnorm * param.orthantwise_c;
                owlqn_pseudo_gradient(
                    pg, x, g, n,
                    param.orthantwise_c, param.orthantwise_start, param.orthantwise_end
                    );
            }

            /* Store the initial value of the objective function. */
            if (pf != null)
            {
                pf[0] = fx;
            }

            /*
                Compute the direction;
                we assume the initial hessian matrix H_0 as the identity matrix.
             */
            if (param.orthantwise_c == 0.0)
            {
                vecncpy(d, g, n);
            }
            else
            {
                vecncpy(d, pg, n);
            }

            /*
               Make sure that the initial variables are not a minimizer.
             */
            vec2norm(out xnorm, x, n);
            if (param.orthantwise_c == 0.0)
            {
                vec2norm(out gnorm, g, n);
            }
            else
            {
                vec2norm(out gnorm, pg, n);
            }
            if (xnorm < 1.0) xnorm = 1.0;
            if (gnorm / xnorm <= param.epsilon)
            {
                ret = Code.LBFGS_ALREADY_MINIMIZED;
                goto lbfgs_exit;
            }

            /* Compute the initial step:
                step = 1.0 / System.Math.Sqrt(vecdot(d, d, n))
             */
            vec2norminv(out step, d, n);

            k = 1;
            end = 0;
            for (; ; )
            {
                /* Store the current position and gradient vectors. */
                veccpy(xp, x, n);
                veccpy(gp, g, n);

                /* Search for an optimal step. */
                if (param.orthantwise_c == 0.0)
                {
                    ls = linesearch(n, x, ref fx, g,
                        d, ref step, xp, gp, w, ref cd, ref param);
                }
                else
                {
                    ls = linesearch(n, x, ref fx, g, d, ref step,
                        xp, pg, w, ref cd, ref param);
                    owlqn_pseudo_gradient(
                        pg, x, g, n,
                        param.orthantwise_c, param.orthantwise_start, param.orthantwise_end
                        );
                }
                if (ls < 0)
                {
                    /* Revert to the previous point. */
                    veccpy(x, xp, n);
                    veccpy(g, gp, n);
                    ret = (Code)ls;
                    goto lbfgs_exit;
                }

                /* Compute x and g norms. */
                vec2norm(out xnorm, x, n);
                if (param.orthantwise_c == 0.0)
                {
                    vec2norm(out gnorm, g, n);
                }
                else
                {
                    vec2norm(out gnorm, pg, n);
                }

                /* Report the progress. */
                if (cd.proc_progress != null)
                {
                    if ((ret = cd.proc_progress(cd.instance, x, g, fx, xnorm,
                        gnorm, step, cd.n, k, ls)) != 0)
                    {
                        goto lbfgs_exit;
                    }
                }

                /*
                    Convergence test.
                    The criterion is given by the following formula:
                        |g(x)| / \max(1, |x|) < \epsilon
                 */
                if (xnorm < 1.0)
                    xnorm = 1.0;

                if (Double.IsNaN(xnorm) || double.IsNaN(gnorm))
                {
                    ret = Code.LBFGSERR_UNKNOWNERROR;
                    break;
                }

                if (gnorm / xnorm <= param.epsilon)
                {
                    /* Convergence. */
                    ret = Code.LBFGS_SUCCESS;
                    break;
                }

                /*
                    Test for stopping criterion.
                    The criterion is given by the following formula:
                        (f(past_x) - f(x)) / f(x) < \delta
                 */
                if (pf != null)
                {
                    /* We don't test the stopping criterion while k < past. */
                    if (param.past <= k)
                    {
                        /* Compute the relative improvement from the past. */
                        rate = (pf[k % param.past] - fx) / fx;

                        /* The stopping criterion. */
                        if (rate < param.delta)
                        {
                            ret = Code.LBFGS_STOP;
                            break;
                        }
                    }

                    /* Store the current value of the objective function. */
                    pf[k % param.past] = fx;
                }

                if (param.max_iterations != 0 && param.max_iterations < k + 1)
                {
                    /* Maximum number of iterations. */
                    ret = Code.LBFGSERR_MAXIMUMITERATION;
                    break;
                }

                /*
                    Update vectors s and y:
                        s_{k+1} = x_{k+1} - x_{k} = \step * d_{k}.
                        y_{k+1} = g_{k+1} - g_{k}.
                 */
                it = lm[end];
                vecdiff(it.s, x, xp, n);
                vecdiff(it.y, g, gp, n);

                /*
                    Compute scalars ys and yy:
                        ys = y^t \cdot s = 1 / \rho.
                        yy = y^t \cdot y.
                    Notice that yy is used for scaling the hessian matrix H_0 (Cholesky factor).
                 */
                vecdot(out ys, it.y, it.s, n);
                vecdot(out yy, it.y, it.y, n);
                it.ys = ys;

                /*
                    Recursive formula to compute dir = -(H \cdot g).
                        This is described in page 779 of:
                        Jorge Nocedal.
                        Updating Quasi-Newton Matrices with Limited Storage.
                        Mathematics of Computation, Vol. 35, No. 151,
                        pp. 773--782, 1980.
                 */
                bound = (m <= k) ? m : k;
                ++k;
                end = (end + 1) % m;

                /* Compute the steepest direction. */
                if (param.orthantwise_c == 0.0)
                {
                    /* Compute the negative of gradients. */
                    vecncpy(d, g, n);
                }
                else
                {
                    vecncpy(d, pg, n);
                }

                j = end;
                for (i = 0; i < bound; ++i)
                {
                    j = (j + m - 1) % m;    /* if (--j == -1) j = m-1; */
                    it = lm[j];
                    /* \alpha_{j} = \rho_{j} s^{t}_{j} \cdot q_{k+1}. */
                    vecdot(out it.alpha, it.s, d, n);
                    it.alpha /= it.ys;
                    /* q_{i} = q_{i+1} - \alpha_{i} y_{i}. */
                    vecadd(d, it.y, -it.alpha, n);
                }

                vecscale(d, ys / yy, n);

                for (i = 0; i < bound; ++i)
                {
                    it = lm[j];
                    /* \beta_{j} = \rho_{j} y^t_{j} \cdot \gamma_{i}. */
                    vecdot(out beta, it.y, d, n);
                    beta /= it.ys;
                    /* \gamma_{i+1} = \gamma_{i} + (\alpha_{j} - \beta_{j}) s_{j}. */
                    vecadd(d, it.s, it.alpha - beta, n);
                    j = (j + 1) % m;        /* if (++j == m) j = 0; */
                }

                /*
                    rain the search direction for orthant-wise updates.
                 */
                if (param.orthantwise_c != 0.0)
                {
                    for (i = param.orthantwise_start; i < param.orthantwise_end; ++i)
                    {
                        if (d[i] * pg[i] >= 0)
                        {
                            d[i] = 0;
                        }
                    }
                }

                /*
                    Now the search direction d is ready. We try step = 1 first.
                 */
                step = 1.0;
            }

        lbfgs_exit:
            /* Return the final value of the objective function. */
            ptr_fx = fx;

            return ret;
        }
        static Code line_search_backtracking(
            int n,
            double[] x,
            ref double f,
            double[] g,
            double[] s,
            ref double stp,
             double[] xp,
             double[] gp,
            double[] wp,
            ref callback_data_t cd,
             ref lbfgs_parameter_t param
            )
        {
            int count = 0;
            double width, dg;
            double finit, dginit = 0.0, dgtest;
            double dec = 0.5, inc = 2.1;

            /* Check the input parameters for errors. */
            if (stp <= 0.0)
            {
                return Code.LBFGSERR_INVALIDPARAMETERS;
            }

            /* Compute the initial gradient in the search direction. */
            vecdot(out dginit, g, s, n);

            /* Make sure that s points to a descent direction. */
            if (0 < dginit)
            {
                return Code.LBFGSERR_INCREASEGRADIENT;
            }

            /* The initial value of the objective function. */
            finit = f;
            dgtest = param.ftol * dginit;

            for (; ; )
            {
                veccpy(x, xp, n);
                vecadd(x, s, stp, n);

                /* Evaluate the function and gradient values. */
                f = cd.proc_evaluate(cd.instance, x, g, cd.n, stp);

                ++count;

                if (f > finit + stp * dgtest)
                {
                    width = dec;
                }
                else
                {
                    /* The sufficient decrease condition (Armijo condition). */
                    if (param.linesearch == LineSearch.BacktrackingArmijo)
                    {
                        /* Exit with the Armijo condition. */
                        return (Code)count;
                    }

                    /* Check the Wolfe condition. */
                    vecdot(out dg, g, s, n);
                    if (dg < param.wolfe * dginit)
                    {
                        width = inc;
                    }
                    else
                    {
                        if (param.linesearch == LineSearch.RegularWolfe)
                        {
                            /* Exit with the regular Wolfe condition. */
                            return (Code)count;
                        }

                        /* Check the strong Wolfe condition. */
                        if (dg > -param.wolfe * dginit)
                        {
                            width = dec;
                        }
                        else
                        {
                            /* Exit with the strong Wolfe condition. */
                            return (Code)count;
                        }
                    }
                }

                if (stp < param.min_step)
                {
                    /* The step is the minimum value. */
                    return Code.LBFGSERR_MINIMUMSTEP;
                }
                if (stp > param.max_step)
                {
                    /* The step is the maximum value. */
                    return Code.LBFGSERR_MAXIMUMSTEP;
                }
                if (param.max_linesearch <= count)
                {
                    /* Maximum number of iteration. */
                    return Code.LBFGSERR_MAXIMUMLINESEARCH;
                }

                (stp) *= width;
            }
        }
        static Code line_search_morethuente(
            int n,
            double[] x,
            ref double f,
            double[] g,
            double[] s,
            ref double stp,
             double[] xp,
             double[] gp,
            double[] wa,
            ref callback_data_t cd,
             ref lbfgs_parameter_t param
            )
        {
            int count = 0;
            int brackt, stage1;
            Code uinfo = 0;
            double dg;
            double stx, fx, dgx;
            double sty, fy, dgy;
            double fxm, dgxm, fym, dgym, fm, dgm;
            double finit, ftest1, dginit, dgtest;
            double width, prev_width;
            double stmin, stmax;

            /* Check the input parameters for errors. */
            if (stp <= 0.0)
            {
                return Code.LBFGSERR_INVALIDPARAMETERS;
            }

            /* Compute the initial gradient in the search direction. */
            vecdot(out dginit, g, s, n);

            /* Make sure that s points to a descent direction. */
            if (0 < dginit)
            {
                return Code.LBFGSERR_INCREASEGRADIENT;
            }

            /* Initialize local variables. */
            brackt = 0;
            stage1 = 1;
            finit = f;
            dgtest = param.ftol * dginit;
            width = param.max_step - param.min_step;
            prev_width = 2.0 * width;

            /*
                The variables stx, fx, dgx contain the values of the step,
                function, and directional derivative at the best step.
                The variables sty, fy, dgy contain the value of the step,
                function, and derivative at the other endpoint of
                the interval of uncertainty.
                The variables stp, f, dg contain the values of the step,
                function, and derivative at the current step.
            */
            stx = sty = 0.0;
            fx = fy = finit;
            dgx = dgy = dginit;

            for (; ; )
            {
                /*
                    Set the minimum and maximum steps to correspond to the
                    present interval of uncertainty.
                 */
                if (brackt != 0)
                {
                    stmin = System.Math.Min(stx, sty);
                    stmax = System.Math.Max(stx, sty);
                }
                else
                {
                    stmin = stx;
                    stmax = stp + 4.0 * (stp - stx);
                }

                /* Clip the step in the range of [stpmin, stpmax]. */
                if (stp < param.min_step) stp = param.min_step;
                if (param.max_step < stp) stp = param.max_step;

                /*
                    If an unusual termination is to occur then let
                    stp be the lowest point obtained so far.
                 */
                if ((brackt > 0 && ((stp <= stmin || stmax <= stp) ||
                    param.max_linesearch <= count + 1 || uinfo != 0)) || (brackt > 0 && (stmax - stmin <= param.xtol * stmax)))
                {
                    stp = stx;
                }

                /*
                    Compute the current value of x:
                        x <- x + (stp) * s.
                 */
                veccpy(x, xp, n);
                vecadd(x, s, stp, n);

                /* Evaluate the function and gradient values. */
                f = cd.proc_evaluate(cd.instance, x, g, cd.n, stp);
                vecdot(out dg, g, s, n);

                ftest1 = finit + stp * dgtest;
                ++count;

                /* Test for errors and convergence. */
                if (brackt > 0 && ((stp <= stmin || stmax <= stp) || uinfo != 0))
                {
                    /* Rounding errors prevent further progress. */
                    return Code.LBFGSERR_ROUNDING_ERROR;
                }
                if (stp == param.max_step && f <= ftest1 && dg <= dgtest)
                {
                    /* The step is the maximum value. */
                    return Code.LBFGSERR_MAXIMUMSTEP;
                }
                if (stp == param.min_step && (ftest1 < f || dgtest <= dg))
                {
                    /* The step is the minimum value. */
                    return Code.LBFGSERR_MINIMUMSTEP;
                }
                if (brackt > 0 && (stmax - stmin) <= param.xtol * stmax)
                {
                    /* Relative width of the interval of uncertainty is at most xtol. */
                    return Code.LBFGSERR_WIDTHTOOSMALL;
                }
                if (param.max_linesearch <= count)
                {
                    /* Maximum number of iteration. */
                    return Code.LBFGSERR_MAXIMUMLINESEARCH;
                }
                if (f <= ftest1 && Math.Abs(dg) <= param.gtol * (-dginit))
                {
                    /* The sufficient decrease condition and the directional derivative condition hold. */
                    return (Code)count;
                }

                /*
                    In the first stage we seek a step for which the modified
                    function has a nonpositive value and nonnegative derivative.
                 */
                if (stage1 > 0 && f <= ftest1 && Math.Min(param.ftol, param.gtol) * dginit <= dg)
                {
                    stage1 = 0;
                }

                /*
                    A modified function is used to predict the step only if
                    we have not obtained a step for which the modified
                    function has a nonpositive function value and nonnegative
                    derivative, and if a lower function value has been
                    obtained but the decrease is not sufficient.
                 */
                if (stage1 > 0 && ftest1 < f && f <= fx)
                {
                    /* Define the modified function and derivative values. */
                    fm = f - stp * dgtest;
                    fxm = fx - stx * dgtest;
                    fym = fy - sty * dgtest;
                    dgm = dg - dgtest;
                    dgxm = dgx - dgtest;
                    dgym = dgy - dgtest;

                    /*
                        Call update_trial_interval() to update the interval of
                        uncertainty and to compute the new step.
                     */
                    uinfo = update_trial_interval(
                        ref stx, ref fxm, ref dgxm,
                        ref sty, ref fym, ref dgym,
                        ref stp, ref fm, ref dgm,
                        stmin, stmax, ref brackt
                        );

                    /* Reset the function and gradient values for f. */
                    fx = fxm + stx * dgtest;
                    fy = fym + sty * dgtest;
                    dgx = dgxm + dgtest;
                    dgy = dgym + dgtest;
                }
                else
                {
                    /*
                        Call update_trial_interval() to update the interval of
                        uncertainty and to compute the new step.
                     */
                    uinfo = update_trial_interval(
                        ref stx, ref fx, ref dgx,
                        ref sty, ref fy, ref dgy,
                        ref stp, ref f, ref dg,
                        stmin, stmax, ref brackt
                        );
                }

                /*
                    Force a sufficient decrease in the interval of uncertainty.
                 */
                if (brackt > 0)
                {
                    if (0.66 * prev_width <= Math.Abs(sty - stx))
                    {
                        stp = stx + 0.5 * (sty - stx);
                    }
                    prev_width = width;
                    width = Math.Abs(sty - stx);
                }
            }

        }