int TreeIdSolver_RNE::CartToJnt(const KDL::JntArray &q, const KDL::JntArray &q_dot, const KDL::JntArray &q_dotdot, const Twist& base_velocity, const Twist& base_acceleration, const Wrenches& f_ext,JntArray &torques, Wrench& base_force)
    {
        if( q.rows() != undirected_tree.getNrOfDOFs() ||
            q_dot.rows() != q.rows()                  ||
            q_dotdot.rows() != q.rows()               ||
            f_ext.size() != undirected_tree.getNrOfLinks() ||
            torques.rows() != q.rows() ) return -1; 
        
        base_force = Wrench::Zero();

        rneaKinematicLoop(undirected_tree,q,q_dot,q_dotdot,traversal,base_velocity,base_acceleration,v,a);
        
        rneaDynamicLoop(undirected_tree,q,traversal,v,a,f_ext,f,torques,base_force);
        
        return 0;
    }
    int ChainIdSolver_RNE_FB::CartToJnt(const KDL::JntArray &q, const KDL::JntArray &q_dot, const KDL::JntArray &q_dotdot,  const Twist& base_velocity, const Twist& base_acceleration, const Wrenches& f_ext, KDL::JntArray &torques, Wrench& base_force)
    {
        //Check sizes when in debug mode
        if(q.rows()!=nj || q_dot.rows()!=nj || q_dotdot.rows()!=nj || torques.rows()!=nj || f_ext.size()!=ns)
            return -1;
        unsigned int j=0;

        //Sweep from root to leaf
        for(unsigned int i=0;i<ns;i++){
            double q_,qdot_,qdotdot_;
            Segment segm;
            segm = chain.getSegment(i);
            if(segm.getJoint().getType()!=Joint::None){
                q_=q(j);
                qdot_=q_dot(j);
                qdotdot_=q_dotdot(j);
                j++;
            }else
                q_=qdot_=qdotdot_=0.0;
            
            //Calculate segment properties: X,S,vj,cj
            X[i]=segm.pose(q_);//Remark this is the inverse of the
                                                //frame for transformations from 
                                                //the parent to the current coord frame
            //Transform velocity and unit velocity to segment frame
            Twist vj=X[i].M.Inverse(segm.twist(q_,qdot_));
            S[i]=X[i].M.Inverse(segm.twist(q_,1.0));
            //We can take cj=0, see remark section 3.5, page 55 since the unit velocity vector S of our joints is always time constant
            //calculate velocity and acceleration of the segment (in segment coordinates)
            if(i==0){
                v[i]=X[i].Inverse(base_velocity)+vj;
                a[i]=X[i].Inverse(base_acceleration)+S[i]*qdotdot_+v[i]*vj;
            }else{
                v[i]=X[i].Inverse(v[i-1])+vj;
                a[i]=X[i].Inverse(a[i-1])+S[i]*qdotdot_+v[i]*vj;
            }
            //Calculate the force for the joint
            //Collect RigidBodyInertia and external forces
            RigidBodyInertia Ii=segm.getInertia();
            f[i]=Ii*a[i]+v[i]*(Ii*v[i])-f_ext[i];
            //std::cout << "aLink " << segm.getName() << "\na= " << a[i]  << "\nv= " << v[i] << "\nf= " << f[i] << "\nf_ext= " << f_ext[i]  << std::endl;
            //std::cout << "a["<<i<<"]=" << a[i] << "\n f["<<i<<"]=" << f[i] << "\n S["<<i<<"]=" << S[i] << std::endl;
        }
        //Sweep from leaf to root
        j=nj-1;
        for(int i=ns-1;i>=0;i--){
        	Segment segm;
        	segm = chain.getSegment(i);
            if(segm.getJoint().getType()!=Joint::None)
                torques(j--)=dot(S[i],f[i]);
            if(i!=0)
                f[i-1]=f[i-1]+X[i]*f[i];
        }
        base_force = X[0]*f[0];
        //debug
        for(int i=0; i < (int)ns; i++) {
            Segment segm;
        	segm = chain.getSegment(i);
            //std::cout << "bLink " << segm.getName() << " a= " << a[i] << " f= " << f[i] << std::endl;
        }
        
	return 0;
    }
//#include <chainidsolver_constraint_vereshchagin.hpp>
int main()
{

    using namespace KDL;


    //Definition of kinematic chain
    //-----------------------------------------------------------------------------------------------//
    //Joint (const JointType &type=None, const double &scale=1, const double &offset=0,
    //       const double &inertia=0, const double &damping=0, const double &stiffness=0)
    Joint rotJoint0 = Joint(Joint::RotZ, 1, 0, 0.01);
    Joint rotJoint1 = Joint(Joint::RotZ, 1, 0, 0.01);
    //Joint rotJoint1 = Joint(Joint::None,1,0,0.01);

    Frame refFrame(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, 0.0, 0.0));
    Frame frame1(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, -0.2, 0.0));
    Frame frame2(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, -0.2, 0.0));
    //Segment (const Joint &joint=Joint(Joint::None),
    //         const Frame &f_tip=Frame::Identity(), const RigidBodyInertia &I=RigidBodyInertia::Zero())
    Segment segment1 = Segment(rotJoint0, frame1);
    Segment segment2 = Segment(rotJoint1, frame2);

    // 	RotationalInertia (double Ixx=0, double Iyy=0, double Izz=0, double Ixy=0, double Ixz=0, double Iyz=0)
    RotationalInertia rotInerSeg1(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); //around symmetry axis of rotation
    //RigidBodyInertia (double m=0, const Vector &oc=Vector::Zero(), const RotationalInertia &Ic=RotationalInertia::Zero())
    RigidBodyInertia inerSegment1(1.0, Vector(0.0, -0.2, 0.0), rotInerSeg1);
    RigidBodyInertia inerSegment2(1.0, Vector(0.0, -0.2, 0.0), rotInerSeg1);
    segment1.setInertia(inerSegment1);
    segment2.setInertia(inerSegment2);

    Chain chain;
    chain.addSegment(segment1);
    //chain.addSegment(segment2);
    //----------------------------------------------------------------------------------------------//

    //Definition of constraints and external disturbances
    //--------------------------------------------------------------------------------------//
    JntArray arrayOfJoints(chain.getNrOfJoints());
    //Constraint force matrix at the end-effector
    //What is the convention for the spatial force matrix; is it the same as in thesis?
    Vector constrainXLinear(0.0, 1.0, 0.0);
    Vector constrainXAngular(0.0, 0.0, 0.0);
    Vector constrainYLinear(0.0, 0.0, 0.0);
    Vector constrainYAngular(0.0, 0.0, 0.0);
    Vector constrainZLinear(0.0, 0.0, 0.0);
    Vector constrainZAngular(0.0, 0.0, 0.0);
    const Twist constraintForcesX(constrainXLinear, constrainXAngular);
    const Twist constraintForcesY(constrainYLinear, constrainYAngular);
    const Twist constraintForcesZ(constrainZLinear, constrainZAngular);
    Jacobian alpha(1);
    alpha.setColumn(0, constraintForcesX);
    //alpha.setColumn(1,constraintForcesY);
    //alpha.setColumn(2,constraintForcesZ);

    //Acceleration energy at  the end-effector
    JntArray betha(1); //set to zero
    betha(0) = 0.0;
    //betha(1) = 0.0;
    //betha(2) = 0.0;

    //arm root acceleration
    Vector linearAcc(0.0, 10, 0.0); //gravitational acceleration along Y
    Vector angularAcc(0.0, 0.0, 0.0);
    Twist twist1(linearAcc, angularAcc);

    //external forces on the arm
    Vector externalForce1(0.0, 0.0, 0.0);
    Vector externalTorque1(0.0, 0.0, 0.0);
    Vector externalForce2(0.0, 0.0, 0.0);
    Vector externalTorque2(0.0, 0.0, 0.0);
    Wrench externalNetForce1(externalForce1, externalTorque1);
    Wrench externalNetForce2(externalForce2, externalTorque2);
    Wrenches externalNetForce;
    externalNetForce.push_back(externalNetForce1);
    //externalNetForce.push_back(externalNetForce2);
    //-------------------------------------------------------------------------------------//

    //solvers
    ChainFkSolverPos_recursive fksolver(chain);
    //ChainFkSolverVel_recursive fksolverVel(chain);
    int numberOfConstraints = 1;
    ChainIdSolver_Vereshchagin constraintSolver(chain, twist1, numberOfConstraints);

    // Initial arm position configuration/constraint
    Frame frameInitialPose;
    JntArray jointInitialPose(chain.getNrOfJoints());
    jointInitialPose(0) = M_PI/6.0; // initial joint0 pose
    //jointInitialPose(1) = M_PI/6.0;                          //initial joint1 pose, negative in clockwise

    //cartesian space/link accelerations
    Twist accLink0;
    Twist accLink1;
    Twists cartAcc;
    cartAcc.push_back(accLink0);
    //cartAcc.push_back(accLink1);

    //arm joint rate configuration and initial values are zero
    JntArray qDot(chain.getNrOfJoints());
    //arm joint accelerations returned by the solver
    JntArray qDotDot(chain.getNrOfJoints());
    
    //arm joint torques returned by the solver
    JntArray qTorque(chain.getNrOfJoints());

    arrayOfJoints(0) = jointInitialPose(0);
    //arrayOfJoints(1) = jointInitialPose(1);

    //Calculate joint values for each cartesian position
    Frame frameEEPose;
    Twist frameEEVel;
    double TimeConstant = 1; //Time required to complete the task move(frameinitialPose, framefinalPose) default T=10.0
    double timeDelta = 0.002;
    bool status;

    Frame cartX1;
    Frame cartX2;
    Frames cartX;
    cartX.push_back(cartX1);
    cartX.push_back(cartX2);
    Twists cartXDot;
    cartXDot.push_back(accLink0);
    cartXDot.push_back(accLink1);

    Twists cartXDotDot;
    cartXDotDot.push_back(accLink0);
    cartXDotDot.push_back(accLink1);


    for (double t = 0.0; t <= 5*TimeConstant; t = t + timeDelta)
    {
        //at time t0, inputs are arrayOfjoints(0,pi/2.0), qdot(0,0)
        //qDot(0) = 0.5;
        // qDot(1) = 0.5;

        //printf("Inside the main loop %f  %f\n",qTorque(0), qTorque(1));
        

        //NOTE AZAMAT:what is qTorque? in implementation returned qTorque is constraint torque generated by the virtual constraint forces.
        // these torques are required to satify a virtual constraint and basically are real torques applied to joints to achieve
        // these constraint. But if additionally to the constraint generated torques we also had internal motor torques, then should not they
        //be added together?
        
        //qTorque(1) = qTorque(1)+internalJointTorque1;

        // In what frame of reference are the results expressed?

        status = constraintSolver.CartToJnt(arrayOfJoints, qDot, qDotDot, alpha, betha, externalNetForce, qTorque);
        if (status >= 0)
        {
            //For 2-dof arm
            //printf("%f          %f %f       %f %f       %f %f           %f %f           %f %f\n",t , arrayOfJoints(0), arrayOfJoints(1), qDot(0), qDot(1), qDotDot(0), qDotDot(1), qTorque(0), qTorque(1), frameEEPose.p.x(), frameEEPose.p.y());
            //printf("%f          %f %f       %f %f       %f %f\n", t, cartAcc[0].vel.x(), cartAcc[0].vel.y(), cartAcc[0].rot.z(), cartAcc[1].vel.x(), cartAcc[1].vel.y(), cartAcc[1].rot.z());

            //For 1-dof
            
            printf("Joint actual %f          %f       %f        %f            %f\n", t, arrayOfJoints(0), qDot(0), qDotDot(0), qTorque(0));
            std::cout<<std::endl;
        }
        constraintSolver.getLinkCartesianPose(cartX);
        constraintSolver.getLinkCartesianVelocity(cartXDot);
        constraintSolver.getLinkCartesianAcceleration(cartXDotDot);
        constraintSolver.getLinkAcceleration(cartAcc);
        printf("Cartesian acc local %f          %f       %f        %f\n", t, cartAcc[0].vel.x(), cartAcc[0].vel.y(), cartAcc[0].rot.z());
        printf("Cartesian actual %f          %f      %f     %f      %f\n", t, cartX[0].p.x(), cartX[0].p.y(), cartXDot[0].vel[0], cartXDot[0].vel[1]);
        std::cout<<std::endl;
        //printf("External torque %f\n", externalNetForce[0].torque.z());
        //Integration at the given "instanteneous" interval for joint position and velocity.
        //These will be inputs for the next time instant
        //actually here it should be a time interval and not time from the beginning, that is why timeDelta;
        arrayOfJoints(0) = arrayOfJoints(0) + (qDot(0) + qDotDot(0) * timeDelta / 2.0) * timeDelta;
        qDot(0) = qDot(0) + qDotDot(0) * timeDelta;
        //arrayOfJoints(1) = arrayOfJoints(1) + (qDot(1) + qDotDot(1)*timeDelta/2.0)*timeDelta;
        //qDot(1) = qDot(1)+qDotDot(1)*timeDelta;



        //For cartesian space control one needs to calculate from the obtained joint space value, new cartesian space poses.
        //Then based on the difference of the signal (desired-actual) we define a regulation function (controller)
        // this difference should be compensated either by constraint forces or by joint torques.
        // The current version of the algorithm assumes that we don't have control over torques, thus change in constraint forces
        //should be a valid option.
    }

    //torque1=[(m1+m2)a1^2+m2a2^2+2m2a1a2cos2]qDotDot1+[m2a2^2+m2a1a2cos2]qDotDot2-m2a1a2(2qDot1qDot2+qDot2^2)sin2+(m1+m2)ga1cos2+m2ga2cos(1+2)

    //torque2=[m2a2^2+m2a1a2cos2]qDotDot1+m2a2^2qDotDot2+m2a1a2qDot1^2sin2+m2ga2cos(1+2)

    return 0;
}
int main()
{

    using namespace KDL;


    //Definition of kinematic chain
    //-----------------------------------------------------------------------------------------------//
    //Joint (const JointType &type=None, const double &scale=1, const double &offset=0, const double &inertia=0, const double &damping=0, const double &stiffness=0)
    Joint rotJoint0 = Joint(Joint::RotZ, 1, 0, 0.01);
    Joint rotJoint1 = Joint(Joint::RotZ, 1, 0, 0.01);

    Frame refFrame(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, 0.0, 0.0));
    Frame frame1(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, -0.4, 0.0));
    Frame frame2(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, -0.4, 0.0));
    //Segment (const Joint &joint=Joint(Joint::None), const Frame &f_tip=Frame::Identity(), const RigidBodyInertia &I=RigidBodyInertia::Zero())
    Segment segment1 = Segment(rotJoint0, frame1);
    Segment segment2 = Segment(rotJoint1, frame2);

    // 	RotationalInertia (double Ixx=0, double Iyy=0, double Izz=0, double Ixy=0, double Ixz=0, double Iyz=0)
    RotationalInertia rotInerSeg1(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); //around symmetry axis of rotation
    //RigidBodyInertia (double m=0, const Vector &oc=Vector::Zero(), const RotationalInertia &Ic=RotationalInertia::Zero())
    RigidBodyInertia inerSegment1(0.3, Vector(0.0, -0.4, 0.0), rotInerSeg1);
    RigidBodyInertia inerSegment2(0.3, Vector(0.0, -0.4, 0.0), rotInerSeg1);
    segment1.setInertia(inerSegment1);
    segment2.setInertia(inerSegment2);

    Chain chain;
    chain.addSegment(segment1);
    chain.addSegment(segment2);
    //~Definition of kinematic chain
    //----------------------------------------------------------------------------------------------//



    //Definition of constraints and external disturbances
    //--------------------------------------------------------------------------------------//

    //Constraint force matrix at the end-effector
    //What is the convention for the spatial force matrix; is it the same as in thesis?
    //NOTE AZAMAT: Constraint are also defined in local reference frame?!
    Vector constrainXLinear(1.0, 0.0, 0.0);
    Vector constrainXAngular(0.0, 0.0, 0.0);
    Vector constrainYLinear(0.0, 0.0, 0.0);
    Vector constrainYAngular(0.0, 0.0, 0.0);
    Vector constrainZLinear(0.0, 0.0, 0.0);
    Vector constrainZAngular(0.0, 0.0, 0.0);
    Twist constraintForcesX(constrainXLinear, constrainXAngular);
    Twist constraintForcesY(constrainYLinear, constrainYAngular);
    Twist constraintForcesZ(constrainZLinear, constrainZAngular);
    Jacobian alpha(3);
    alpha.setColumn(0, constraintForcesX);
    alpha.setColumn(1, constraintForcesY);
    alpha.setColumn(2, constraintForcesZ);

    //Acceleration energy at  the end-effector
    JntArray betha(3); //set to zero
    betha(0) = 0.0;
    betha(1) = 0.0;
    betha(2) = 0.0;

    //arm root acceleration
    Vector linearAcc(0.0, 9.8, 0.0); //gravitational acceleration along Y
    Vector angularAcc(0.0, 0.0, 0.0);
    Twist twist1(linearAcc, angularAcc);

    //external forces on the arm
    Vector externalForce1(0.0, 0.0, 0.0);
    Vector externalTorque1(0.0, 0.0, 0.0);
    Vector externalForce2(0.0, 0.0, 0.0);
    Vector externalTorque2(0.0, 0.0, 0.0);
    Wrench externalNetForce1(externalForce1, externalTorque1);
    Wrench externalNetForce2(externalForce2, externalTorque2);
    Wrenches externalNetForce;
    externalNetForce.push_back(externalNetForce1);
    externalNetForce.push_back(externalNetForce2);
    //~Definition of constraints and external disturbances
    //-------------------------------------------------------------------------------------//


    //Definition of solver and initial configuration
    //-------------------------------------------------------------------------------------//
    int numberOfConstraints = 3;
    ChainIdSolver_Vereshchagin constraintSolver(chain, twist1, numberOfConstraints);

    //These arrays of joint values contains values for 3
    //consequetive steps
    int k = 3;
    JntArray jointPoses[k];
    JntArray jointRates[k];
    JntArray jointAccelerations[k];
    JntArray jointTorques[k];
    JntArray biasqDotDot(chain.getNrOfJoints());
    for (int i = 0; i < k; i++)
    {
        JntArray jointValues(chain.getNrOfJoints());
        jointPoses[i] = jointValues;
        jointRates[i] = jointValues;
        jointAccelerations[i] = jointValues;
        jointTorques[i] = jointValues;
    }


    //cartesian space/link values
    Frames cartX[k];
    Twists cartXDot[k];
    Twists cartXDotDot[k];
    Twist accLink;
    for (int i = 0; i < k; i++) //i is number of variables (actual, desired, error)
    {
        for (int j = 0; j < k - 1; j++) //j is number of links
        {
            cartX[i].push_back(frame1);
            cartXDot[i].push_back(accLink);
            cartXDotDot[i].push_back(accLink);
        }

    }

    //at time=0.0 positions, rates and accelerations
    JntArray jointInitialPose(chain.getNrOfJoints());
    jointInitialPose(0) = 0.0; // initial joint0 pose
    jointInitialPose(1) = M_PI / 6.0; //initial joint1 pose, negative in clockwise
    //j0=0.0, j1=pi/6.0 correspond to x = 0.2, y = -0.7464
    //j0=pi/6.0, j1=pi/6.0 correspond to x = 0.5464, y = -0.5464
    //~Definition of solver and initial configuration
    //-------------------------------------------------------------------------------------//

    //First iteration to kick start integration process, because we need 0,1 iterations for the integration process
    //We use Euler method for the iteration 0
    double timeDelta = 0.001; //sampling interval/step size
    double TimeConstant = 60; //Time required to complete the task
    double Kp = 150.0;
    double Kv = 10.0;

    //Interpolator parameters:
    double b0_y = -0.7464102; //should come from initial joint configuration
    double b1_y = 0.0;
    double b2_y = 0.0; //((0.5 + 0.7464)*3.0 / TimeConstant * TimeConstant);
    double b3_y = 0.0; //-((0.5 + 0.7464)*2.0 / TimeConstant * TimeConstant * TimeConstant);

    double b0_x = 0.2; //should come from initial joint configuration
    double b1_x = 0.0;
    double b2_x = 0.0; //((0.5 + 0.7464)*3.0 / TimeConstant * TimeConstant);
    double b3_x = 0.0; //-((0.5 + 0.7464)*2.0 / TimeConstant * TimeConstant * TimeConstant);

    //Desired
    cartX[1][1].p[0] = b0_x;
    cartX[1][1].p[1] = b0_y;
    cartXDot[1][1].vel[0] = 0.0;
    cartXDot[1][1].vel[1] = 0.0;
    cartXDotDot[1][1].vel[0] = 0.0;
    cartXDotDot[1][1].vel[1] = 0.0;
    
    //step 0
    jointPoses[0](0) = jointInitialPose(0);
    jointPoses[0](1) = jointInitialPose(1);

    constraintSolver.CartToJnt(jointPoses[0], jointRates[0], jointAccelerations[0], cartXDotDot[0], alpha, betha, externalNetForce, jointTorques[0]);
    //Actual
    constraintSolver.getLinkCartesianPose(cartX[0]);
    constraintSolver.getLinkCartesianVelocity(cartXDot[0]);
    
    //Error
    cartX[2][1].p[0] = cartX[1][1].p[0] - cartX[0][1].p[0];
    cartX[2][1].p[1] = cartX[1][1].p[1] - cartX[0][1].p[1];
    cartXDot[2][1].vel[0] = cartXDot[1][1].vel[0] - cartXDot[0][1].vel[0];
    cartXDot[2][1].vel[1] = cartXDot[1][1].vel[1] - cartXDot[0][1].vel[1];
    cartXDotDot[2][1].vel[0] = cartXDotDot[1][1].vel[0] - cartXDotDot[0][1].vel[0];
    cartXDotDot[2][1].vel[1] = cartXDotDot[1][1].vel[1] - cartXDotDot[0][1].vel[1];
    printf("Iter 0:   %f      %f     %f         %f        %f      %f\n", cartX[2][1].p[0], cartX[2][1].p[1], cartXDot[2][1].vel[0], cartXDot[2][1].vel[1], cartXDotDot[2][1].vel[1], cartXDotDot[2][1].vel[1]);

    //Regulator or controller
    betha(0) = alpha(0, 0)*((Kp / 10000.0) * cartXDotDot[2][1].vel[0] + (Kv / 200.0) * cartXDot[2][1].vel[0] + (2 * Kp) * cartX[2][1].p[0]);
    betha(1) = alpha(1, 1)*((Kp / 10000.0) * cartXDotDot[2][1].vel[1] + (Kv / 250.0) * cartXDot[2][1].vel[1] + (1.5 * Kp) * cartX[2][1].p[1]);



    //step 1
    jointRates[1](0) = jointRates[0](0) + timeDelta * jointAccelerations[0](0);
    jointRates[1](1) = jointRates[0](1) + timeDelta * jointAccelerations[0](1);
    jointPoses[1](0) = jointPoses[0](0) + timeDelta * jointRates[0](0);
    jointPoses[1](1) = jointPoses[0](1) + timeDelta * jointRates[0](1);

    constraintSolver.CartToJnt(jointPoses[1], jointRates[1], jointAccelerations[1], cartXDotDot[0], alpha, betha, externalNetForce, jointTorques[0]);
    //Actual
    constraintSolver.getLinkCartesianPose(cartX[0]);
    constraintSolver.getLinkCartesianVelocity(cartXDot[0]);
    
    //Error
    cartX[2][1].p[0] = cartX[1][1].p[0] - cartX[0][1].p[0];
    cartX[2][1].p[1] = cartX[1][1].p[1] - cartX[0][1].p[1];
    cartXDot[2][1].vel[0] = cartXDot[1][1].vel[0] - cartXDot[0][1].vel[0];
    cartXDot[2][1].vel[1] = cartXDot[1][1].vel[1] - cartXDot[0][1].vel[1];
    cartXDotDot[2][1].vel[0] = cartXDotDot[1][1].vel[0] - cartXDotDot[0][1].vel[0];
    cartXDotDot[2][1].vel[1] = cartXDotDot[1][1].vel[1] - cartXDotDot[0][1].vel[1];
    printf("Iter 0:   %f      %f     %f         %f        %f      %f\n", cartX[2][1].p[0], cartX[2][1].p[1], cartXDot[2][1].vel[0], cartXDot[2][1].vel[1], cartXDotDot[2][1].vel[1], cartXDotDot[2][1].vel[1]);

    //Regulator or controller
    betha(0) = alpha(0, 0)*((Kp / 10000.0) * cartXDotDot[2][1].vel[0] + (Kv / 200.0) * cartXDot[2][1].vel[0] + (2 * Kp) * cartX[2][1].p[0]);
    betha(1) = alpha(1, 1)*((Kp / 10000.0) * cartXDotDot[2][1].vel[1] + (Kv / 250.0) * cartXDot[2][1].vel[1] + (1.5 * Kp) * cartX[2][1].p[1]);

    //Definition of process main loop
    //-------------------------------------------------------------------------------------//
    for (double t = 2 * timeDelta; t <= TimeConstant; t = t + timeDelta)
    {
        //Interpolation q = a0+a1t+a2t^2+a3t^3
        //Desired
        cartX[1][1].p[0] = b0_x + b1_x * t + b2_x * t * t + b3_x * t * t*t;
        cartX[1][1].p[1] = b0_y + b1_y * t + b2_y * t * t + b3_y * t * t*t;
        cartXDot[1][1].vel[0] = b1_x + 2 * b2_x * t + 3 * b3_x * t*t;
        cartXDot[1][1].vel[1] = b1_y + 2 * b2_y * t + 3 * b3_y * t*t;
        cartXDotDot[1][1].vel[0] = 2 * b2_x + 6 * b3_x*t;
        cartXDotDot[1][1].vel[1] = 2 * b2_y + 6 * b3_y*t;

        // AB 2 order: predictor
        jointRates[2](0) = jointRates[1](0) + timeDelta * (1.5 * jointAccelerations[1](0) - 0.5 * jointAccelerations[0](0));
        jointRates[2](1) = jointRates[1](1) + timeDelta * (1.5 * jointAccelerations[1](1) - 0.5 * jointAccelerations[0](1));
        jointPoses[2](0) = jointPoses[1](0) + timeDelta * (1.5 * jointRates[1](0) - 0.5 * jointRates[0](0));
        jointPoses[2](1) = jointPoses[1](1) + timeDelta * (1.5 * jointRates[1](1) - 0.5 * jointRates[0](1));
        jointTorques[1] = jointTorques[0]; //correction is done on pose,vel and acc, so we need old torques with corrected pose, vel to get corrected acc
        // printf("Prediction: %f          %f %f       %f %f       %f %f           %f %f\n", t, jointPoses[2](0), jointPoses[2](1), jointRates[2](0), jointRates[2](1), jointAccelerations[1](0), jointAccelerations[1](1), jointTorques[0](0), jointTorques[0](1));

        //Function evaluation
        constraintSolver.CartToJnt(jointPoses[2], jointRates[2], jointAccelerations[2], cartXDotDot[0], alpha, betha, externalNetForce, jointTorques[0]);
        //     printf("Evaluation 1: %f          %f %f       %f %f       %f %f           %f %f\n", t, jointPoses[2](0), jointPoses[2](1), jointRates[2](0), jointRates[2](1), jointAccelerations[2](0), jointAccelerations[2](1), jointTorques[0](0), jointTorques[0](1));

        //AM 2 order: corrector
        jointPoses[2](0) = jointPoses[1](0) + timeDelta * ((5 / 12.0) * jointRates[2](0) + (2 / 3.0) * jointRates[1](0) - (1 / 12.0) * jointRates[0](0));
        jointPoses[2](1) = jointPoses[1](1) + timeDelta * ((5 / 12.0) * jointRates[2](1) + (2 / 3.0) * jointRates[1](1) - (1 / 12.0) * jointRates[0](1));
        jointPoses[0] = jointPoses[1];
        jointPoses[1] = jointPoses[2];
        jointRates[2](0) = jointRates[1](0) + timeDelta * ((5 / 12.0) * jointAccelerations[2](0) + (2 / 3.0) * jointAccelerations[1](0) - (1 / 12.0) * jointAccelerations[0](0));
        jointRates[2](1) = jointRates[1](1) + timeDelta * ((5 / 12.0) * jointAccelerations[2](1) + (2 / 3.0) * jointAccelerations[1](1) - (1 / 12.0) * jointAccelerations[0](1));
        jointRates[0] = jointRates[1]; //memorize n+1
        jointRates[1] = jointRates[2]; //memorize n+2
        // printf("Correction : %f          %f %f       %f %f       %f %f           %f %f\n", t, jointPoses[2](0), jointPoses[2](1), jointRates[2](0), jointRates[2](1), jointAccelerations[2](0), jointAccelerations[2](1), jointTorques[0](0), jointTorques[0](1));

        //Function evaluation give final corrected acc n+2
        constraintSolver.CartToJnt(jointPoses[2], jointRates[2], jointAccelerations[2], cartXDotDot[0], alpha, betha, externalNetForce, jointTorques[1]);
        //printf("%f          %f      %f       %f     %f       %f     %f           %f     %f\n", t, jointPoses[2](0), jointPoses[2](1), jointRates[2](0), jointRates[2](1), jointAccelerations[2](0), jointAccelerations[2](1), jointTorques[1](0), jointTorques[1](1));

        jointAccelerations[0] = jointAccelerations[1]; //memorize n+1
        jointAccelerations[1] = jointAccelerations[2]; //memoze n+2
        jointTorques[0] = jointTorques[1];

        constraintSolver.initial_upwards_sweep(jointPoses[1], jointRates[1], jointAccelerations[1], externalNetForce);
        //Actual
        constraintSolver.getLinkCartesianPose(cartX[0]);
        constraintSolver.getLinkCartesianVelocity(cartXDot[0]);

        //Error
        cartX[2][1].p[0] = cartX[1][1].p[0] - cartX[0][1].p[0];
        cartX[2][1].p[1] = cartX[1][1].p[1] - cartX[0][1].p[1];
        cartXDot[2][1].vel[0] = cartXDot[1][1].vel[0] - cartXDot[0][1].vel[0];
        cartXDot[2][1].vel[1] = cartXDot[1][1].vel[1] - cartXDot[0][1].vel[1];
        cartXDotDot[2][1].vel[0] = cartXDotDot[1][1].vel[0] - cartXDotDot[0][1].vel[0];
        cartXDotDot[2][1].vel[1] = cartXDotDot[1][1].vel[1] - cartXDotDot[0][1].vel[1];
        printf("%f          %f      %f     %f         %f        %f      %f\n", t, cartX[2][1].p[0], cartX[2][1].p[1], cartXDot[2][1].vel[0], cartXDot[2][1].vel[1], cartXDotDot[2][1].vel[1], cartXDotDot[2][1].vel[1]);

        //Regulator or controller
        betha(0) = alpha(0, 0)*((Kp / 40000.0) * cartXDotDot[2][1].vel[0] + (Kv / 4000.0) * cartXDot[2][1].vel[0] + (Kp) * cartX[2][1].p[0]);
        betha(1) = alpha(1, 1)*((Kp / 20000.0) * cartXDotDot[2][1].vel[1] + (Kv / 500.0) * cartXDot[2][1].vel[1] + (0.75 * Kp) * cartX[2][1].p[1]);

    }

    return 0;
}
int main()
{

    using namespace KDL;


    //Definition of kinematic chain
    //-----------------------------------------------------------------------------------------------//
    //Joint (const JointType &type=None, const double &scale=1, const double &offset=0, const double &inertia=0, const double &damping=0, const double &stiffness=0)
    Joint rotJoint0 = Joint(Joint::RotZ, 1, 0, 0.01);
    Joint rotJoint1 = Joint(Joint::RotZ, 1, 0, 0.01);

    Frame refFrame(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, 0.0, 0.0));
    Frame frame1(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, -0.4, 0.0));
    Frame frame2(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, -0.4, 0.0));
    //Segment (const Joint &joint=Joint(Joint::None), const Frame &f_tip=Frame::Identity(), const RigidBodyInertia &I=RigidBodyInertia::Zero())
    Segment segment1 = Segment(rotJoint0, frame1);
    Segment segment2 = Segment(rotJoint1, frame2);

    // 	RotationalInertia (double Ixx=0, double Iyy=0, double Izz=0, double Ixy=0, double Ixz=0, double Iyz=0)
    RotationalInertia rotInerSeg1(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); //around symmetry axis of rotation
    //RigidBodyInertia (double m=0, const Vector &oc=Vector::Zero(), const RotationalInertia &Ic=RotationalInertia::Zero())
    RigidBodyInertia inerSegment1(0.3, Vector(0.0, -0.4, 0.0), rotInerSeg1);
    RigidBodyInertia inerSegment2(0.3, Vector(0.0, -0.4, 0.0), rotInerSeg1);
    segment1.setInertia(inerSegment1);
    segment2.setInertia(inerSegment2);

    Chain chain;
    chain.addSegment(segment1);
    chain.addSegment(segment2);
    //~Definition of kinematic chain
    //----------------------------------------------------------------------------------------------//



    //Definition of constraints and external disturbances
    //--------------------------------------------------------------------------------------//
    //Constraint force matrix at the end-effector
    //What is the convention for the spatial force matrix; is it the same as in thesis?
    //NOTE AZAMAT: Constraint are also defined in local reference frame?!
    Vector constrainXLinear(0.0, 0.0, 0.0);
    Vector constrainXAngular(0.0, 0.0, 0.0);
    Vector constrainYLinear(0.0, 1.0, 0.0);
    Vector constrainYAngular(0.0, 0.0, 0.0);
    Vector constrainZLinear(0.0, 0.0, 0.0);
    Vector constrainZAngular(0.0, 0.0, 0.0);
    Twist constraintForcesX(constrainXLinear, constrainXAngular);
    Twist constraintForcesY(constrainYLinear, constrainYAngular);
    //Twist constraintForcesZ(constrainZLinear, constrainZAngular);
    Jacobian alpha(1);
    //alpha.setColumn(0, constraintForcesX);
    alpha.setColumn(0, constraintForcesY);


    //Acceleration energy at  the end-effector
    JntArray betha(1); //set to zero
    betha(0) = 0.0;
    //betha(1) = 0.0;
    //betha(2) = 0.0;

    //arm root acceleration
    Vector linearAcc(0.0, 10, 0.0); //gravitational acceleration along Y
    Vector angularAcc(0.0, 0.0, 0.0);
    Twist twist1(linearAcc, angularAcc);

    //external forces on the arm
    Vector externalForce1(0.0, 0.0, 0.0);
    Vector externalTorque1(0.0, 0.0, 0.0);
    Vector externalForce2(0.0, 0.0, 0.0);
    Vector externalTorque2(0.0, 0.0, 0.0);
    Wrench externalNetForce1(externalForce1, externalTorque1);
    Wrench externalNetForce2(externalForce2, externalTorque2);
    Wrenches externalNetForce;
    externalNetForce.push_back(externalNetForce1);
    externalNetForce.push_back(externalNetForce2);
    //~Definition of constraints and external disturbances
    //-------------------------------------------------------------------------------------//


    //Definition of solver and initial configuration
    //-------------------------------------------------------------------------------------//
    int numberOfConstraints = 1;
    ChainIdSolver_Vereshchagin constraintSolver(chain, twist1, numberOfConstraints);
    
    //These arrays of joint values contain actual and desired values
    //actual is generated by a solver and integrator
    //desired is given by an interpolator
    //error is the difference between desired-actual
    int k = 3;
    JntArray jointPoses[k];
    JntArray jointRates[k];
    JntArray jointAccelerations[k];
    JntArray jointTorques[k];
    JntArray biasqDotDot(chain.getNrOfJoints());
    for (int i = 0; i < k; i++)
    {
        JntArray jointValues(chain.getNrOfJoints());
        jointPoses[i] = jointValues;
        jointRates[i] = jointValues;
        jointAccelerations[i] = jointValues;
        jointTorques[i] = jointValues;
    }

    //cartesian space/link values
    k = 4;
    Frames cartX[k];
    Twists cartXDot[k];
    Twists cartXDotDot[k];
    Twist accLink;
    for (int i = 0; i < k; i++) //i is number of variables (actual, desired, error)
    {
        for (int j = 0; j < k-1; j++) //j is number of links
        {
            cartX[i].push_back(frame1);
            cartXDot[i].push_back(accLink);
            cartXDotDot[i].push_back(accLink);
        }

    }


    // Initial arm position configuration/constraint
    JntArray jointInitialPose(chain.getNrOfJoints());
    jointInitialPose(0) = 0.0; // initial joint0 pose
    jointInitialPose(1) = M_PI/6.0; //initial joint1 pose, negative in clockwise
    //j0=0.0, j1=pi/6.0 correspond to x = 0.2, y = -0.7464
    //j0=2*pi/3.0, j1=pi/4.0 correspond to x = 0.44992, y = 0.58636

    //actual
    jointPoses[0](0) = jointInitialPose(0);
    jointPoses[0](1) = jointInitialPose(1);
    //desired
    jointPoses[1](0) = jointInitialPose(0);
    jointPoses[1](1) = jointInitialPose(1);

   
    //~Definition of solver and initial configuration
    //-------------------------------------------------------------------------------------//



    //Definition of process main loop
    //-------------------------------------------------------------------------------------//
    double taskTimeConstant = 2; //Time required to complete the task move(frameinitialPose, framefinalPose) default T=10.0
    double simulationTime = 2.5*taskTimeConstant;
    double timeDelta = 0.001;
    bool status;
    
    double ksi = 1; //damping factor
    double Kp = 0.02/(taskTimeConstant*taskTimeConstant);
    double Kv = 1*ksi/taskTimeConstant;
    double Ki = 1.0;
    double Ka = 0.0;


    //Interpolator parameters:
    double b0_y = -0.7464102; //should come from initial joint configuration
    double b1_y = 0.0;
    double b2_y = 0.0;//((0.5 + 0.7464)*3.0 / TimeConstant * TimeConstant);
    double b3_y = 0.0;//-((0.5 + 0.7464)*2.0 / TimeConstant * TimeConstant * TimeConstant);

    double b0_x = 0.2; //should come from initial joint configuration
    double b1_x = 0.0;
    double b2_x = 0.0;//((0.5 + 0.7464)*3.0 / TimeConstant * TimeConstant);
    double b3_x = 0.0;//-((0.5 + 0.7464)*2.0 / TimeConstant * TimeConstant * TimeConstant);

    /*
    double a0_q0 = jointPoses[1](0);
    double a1_q0 = 0.0;
    double a2_q0 = ((qFinalPose(0) - jointPoses[1](0))*3.0 / TimeConstant * TimeConstant);
    double a3_q0 = -((qFinalPose(0) - jointPoses[1](0))*2.0 / TimeConstant * TimeConstant * TimeConstant);

    double a0_q1 = jointPoses[1](1);
    double a1_q1 = 0.0;
    double a2_q1 = ((qFinalPose(1) - jointPoses[1](1))*3.0 / TimeConstant * TimeConstant);
    double a3_q1 = -((qFinalPose(1) - jointPoses[1](1))*2.0 / TimeConstant * TimeConstant * TimeConstant);
     */

    
    for (double t = 0.0; t <=simulationTime; t = t + timeDelta)
    {

        //Interpolation (Desired) q = a0+a1t+a2t^2+a3t^3
        //Do we feed these values? then         jointPoses[0] = jointPoses[1];         jointRates[0] = jointRates[1];
        // But I don't think so, in control desired trajectory plays role of the reference that the controller should strive for from its actual (previous, current) state.

        cartX[1][1].p[0] = b0_x + b1_x * t + b2_x * t * t + b3_x * t * t*t;
        cartX[1][1].p[1] = b0_y + b1_y * t + b2_y * t * t + b3_y * t * t*t;
        cartXDot[1][1].vel[0] = b1_x + 2 * b2_x * t + 3 * b3_x * t*t;
        cartXDot[1][1].vel[1] = b1_y + 2 * b2_y * t + 3 * b3_y * t*t;
        cartXDotDot[1][1].vel[0] = 2 * b2_x + 6 * b3_x*t;
        cartXDotDot[1][1].vel[1] = 2 * b2_y + 6 * b3_y*t;
       // printf("Desired Cartesian values: %f          %f      %f     %f         %f        %f      %f\n", t, cartX[1][1].p[0], cartX[1][1].p[1], cartXDot[1][1].vel[0], cartXDot[1][1].vel[1], cartXDotDot[1][1].vel[0], cartXDotDot[1][1].vel[1]);


        status = constraintSolver.CartToJnt(jointPoses[0], jointRates[0], jointAccelerations[0], alpha, betha, externalNetForce, jointTorques[0]);
        /*
        constraintSolver.initial_upwards_sweep(jointPoses[0], jointRates[0], jointAccelerations[0], externalNetForce);
        constraintSolver.downwards_sweep(alpha, jointTorques[0]);
        constraintSolver.constraint_calculation(betha);
        constraintSolver.final_upwards_sweep(jointAccelerations[0], cartXDotDot[0], jointTorques[0]);
       */
        //Integration(robot joint values for rates and poses; actual) at the given "instanteneous" interval for joint position and velocity.
        jointRates[0](0) = jointRates[0](0) + jointAccelerations[0](0) * timeDelta; //Euler Forward
        jointPoses[0](0) = jointPoses[0](0) + (jointRates[0](0) - jointAccelerations[0](0) * timeDelta / 2.0) * timeDelta; //Trapezoidal rule
        jointRates[0](1) = jointRates[0](1) + jointAccelerations[0](1) * timeDelta; //Euler Forward
        jointPoses[0](1) = jointPoses[0](1) + (jointRates[0](1) - jointAccelerations[0](1) * timeDelta / 2.0) * timeDelta;
        //printf("Joint %f          %f      %f       %f     %f       %f      %f     %f      %f\n", t, jointPoses[0](0), jointPoses[0](1), jointRates[0](0), jointRates[0](1), jointAccelerations[0](0), jointAccelerations[0](1), jointTorques[0](0), jointTorques[0](1));
        
        constraintSolver.initial_upwards_sweep(jointPoses[0], jointRates[0], jointAccelerations[0], externalNetForce);
        constraintSolver.getLinkCartesianPose(cartX[0]);
        constraintSolver.getLinkCartesianVelocity(cartXDot[0]);
        constraintSolver.getLinkCartesianAcceleration(cartXDotDot[0]);
        //printf("Cartesian actual %f          %f      %f     %f         %f        %f      %f     %f\n", t, cartX[0][1].p.x(), cartX[0][1].p.y(), cartXDot[0][1].vel[0], cartXDot[0][1].vel[1], cartXDotDot[0][1].vel[0], cartXDotDot[0][1].vel[1], cartXDotDot[0][1].rot[2]);

        //Error
        /*
        jointPoses[2](0) = jointPoses[1](0) - jointPoses[0](0);
        jointPoses[2](1) = jointPoses[1](1) - jointPoses[0](1);
        jointRates[2](0) = jointRates[1](0) - jointRates[0](0);
        jointRates[2](1) = jointRates[1](1) - jointRates[0](1);
        jointAccelerations[2](0) = jointAccelerations[1](0) - jointAccelerations[0](0);
        jointAccelerations[2](1) = jointAccelerations[1](1) - jointAccelerations[0](1);
        printf("Errors: %f          %f      %f          %f     %f       %f      %f\n", t, jointPoses[2](0), jointPoses[2](1), jointRates[2](0), jointRates[2](1), jointAccelerations[2](0), jointAccelerations[2](1));
        */
        //e = d - a
        cartX[2][1].p[0] = cartX[1][1].p[0] - cartX[0][1].p[0];
        cartX[2][1].p[1] = cartX[1][1].p[1] - cartX[0][1].p[1];
        cartXDot[2][1].vel[0] = cartXDot[1][1].vel[0] - cartXDot[0][1].vel[0];
        cartXDot[2][1].vel[1] = cartXDot[1][1].vel[1] - cartXDot[0][1].vel[1];
        cartXDotDot[2][1].vel[0] = cartXDotDot[1][1].vel[0] - cartXDotDot[0][1].vel[0];
        cartXDotDot[2][1].vel[1] = cartXDotDot[1][1].vel[1] - cartXDotDot[0][1].vel[1];
        cartXDotDot[2][1].rot[2] = cartXDotDot[1][1].rot[2] - cartXDotDot[0][1].rot[2];
        cartX[3][1].p[0] += timeDelta*cartX[2][1].p[0]; //for integral term;
        cartX[3][1].p[1] += timeDelta*cartX[2][1].p[1];
        printf("Cartesian error  %f          %f      %f     %f         %f        %f      %f     %f\n", t, cartX[2][1].p[0], cartX[2][1].p[1], cartXDot[2][1].vel[0], cartXDot[2][1].vel[1], cartXDotDot[2][1].vel[1], cartXDotDot[2][1].vel[1], cartXDotDot[2][1].rot[2]);
        //Regulator or controller
        //externalNetForce[1].force[0] =  ( (Kv)*cartXDot[2][1].vel[0] + (Kp)*cartX[2][1].p[0] + Ki*cartX[3][1].p[0]);

        
        betha(0) = ( (Kv)*cartXDot[2][1].vel[1] - (Ka)*cartXDot[2][1].rot[2] + (Kp)*cartX[2][1].p[1]);// + Ki*cartX[3][1].p[0]);
        //betha(1) = betha(1) +(  (Kv)*cartXDot[2][1].vel[1] + (Kp)*cartX[2][1].p[1]);// + Ki*cartX[3][1].p[0]);
        //printf("betha   %f      %f\n", betha(0), betha(1));
    }
    //~Definition of process main loop
    //-------------------------------------------------------------------------------------//





    return 0;
}
void SolverTest::VereshchaginTest()
{

    Vector constrainXLinear(1.0, 0.0, 0.0);
    Vector constrainXAngular(0.0, 0.0, 0.0);
    Vector constrainYLinear(0.0, 0.0, 0.0);
    Vector constrainYAngular(0.0, 0.0, 0.0);
    // Vector constrainZLinear(0.0, 0.0, 0.0);
    //Vector constrainZAngular(0.0, 0.0, 0.0);
    Twist constraintForcesX(constrainXLinear, constrainXAngular);
    Twist constraintForcesY(constrainYLinear, constrainYAngular);
    //Twist constraintForcesZ(constrainZLinear, constrainZAngular);
    Jacobian alpha(1);
    //alpha.setColumn(0, constraintForcesX);
    alpha.setColumn(0, constraintForcesX);
    //alpha.setColumn(0, constraintForcesZ);

    //Acceleration energy at  the end-effector
    JntArray betha(1); //set to zero
    betha(0) = 0.0;
    //betha(1) = 0.0;
    //betha(2) = 0.0;

    //arm root acceleration
    Vector linearAcc(0.0, 10, 0.0); //gravitational acceleration along Y
    Vector angularAcc(0.0, 0.0, 0.0);
    Twist twist1(linearAcc, angularAcc);

    //external forces on the arm
    Vector externalForce1(0.0, 0.0, 0.0);
    Vector externalTorque1(0.0, 0.0, 0.0);
    Vector externalForce2(0.0, 0.0, 0.0);
    Vector externalTorque2(0.0, 0.0, 0.0);
    Wrench externalNetForce1(externalForce1, externalTorque1);
    Wrench externalNetForce2(externalForce2, externalTorque2);
    Wrenches externalNetForce;
    externalNetForce.push_back(externalNetForce1);
    externalNetForce.push_back(externalNetForce2);
    //~Definition of constraints and external disturbances
    //-------------------------------------------------------------------------------------//


    //Definition of solver and initial configuration
    //-------------------------------------------------------------------------------------//
    int numberOfConstraints = 1;
    ChainIdSolver_Vereshchagin constraintSolver(chaindyn, twist1, numberOfConstraints);

    //These arrays of joint values contain actual and desired values
    //actual is generated by a solver and integrator
    //desired is given by an interpolator
    //error is the difference between desired-actual
    //in this test only the actual values are printed.
    const int k = 1;
    JntArray jointPoses[k];
    JntArray jointRates[k];
    JntArray jointAccelerations[k];
    JntArray jointTorques[k];
    for (int i = 0; i < k; i++)
    {
        JntArray jointValues(chaindyn.getNrOfJoints());
        jointPoses[i] = jointValues;
        jointRates[i] = jointValues;
        jointAccelerations[i] = jointValues;
        jointTorques[i] = jointValues;
    }

    // Initial arm position configuration/constraint
    JntArray jointInitialPose(chaindyn.getNrOfJoints());
    jointInitialPose(0) = 0.0; // initial joint0 pose
    jointInitialPose(1) = M_PI/6.0; //initial joint1 pose, negative in clockwise
    //j0=0.0, j1=pi/6.0 correspond to x = 0.2, y = -0.7464
    //j0=2*pi/3.0, j1=pi/4.0 correspond to x = 0.44992, y = 0.58636

    //actual
    jointPoses[0](0) = jointInitialPose(0);
    jointPoses[0](1) = jointInitialPose(1);

    //~Definition of solver and initial configuration
    //-------------------------------------------------------------------------------------//


    //Definition of process main loop
    //-------------------------------------------------------------------------------------//
    //Time required to complete the task move(frameinitialPose, framefinalPose)
    double taskTimeConstant = 0.1;
    double simulationTime = 1*taskTimeConstant;
    double timeDelta = 0.01;
    int status;

    const std::string msg = "Assertion failed, check matrix and array sizes";

    for (double t = 0.0; t <=simulationTime; t = t + timeDelta)
    {
        status = constraintSolver.CartToJnt(jointPoses[0], jointRates[0], jointAccelerations[0], alpha, betha, externalNetForce, jointTorques[0]);

        CPPUNIT_ASSERT((status == 0));
        if (status != 0)
        {
            std::cout << "Check matrix and array sizes. Something does not match " << std::endl;
            exit(1);
        }
        else
        {
            //Integration(robot joint values for rates and poses; actual) at the given "instanteneous" interval for joint position and velocity.
            jointRates[0](0) = jointRates[0](0) + jointAccelerations[0](0) * timeDelta; //Euler Forward
            jointPoses[0](0) = jointPoses[0](0) + (jointRates[0](0) - jointAccelerations[0](0) * timeDelta / 2.0) * timeDelta; //Trapezoidal rule
            jointRates[0](1) = jointRates[0](1) + jointAccelerations[0](1) * timeDelta; //Euler Forward
            jointPoses[0](1) = jointPoses[0](1) + (jointRates[0](1) - jointAccelerations[0](1) * timeDelta / 2.0) * timeDelta;
            //printf("time, j0_pose, j1_pose, j0_rate, j1_rate, j0_acc, j1_acc, j0_constraintTau, j1_constraintTau \n");
            printf("%f          %f      %f       %f     %f       %f      %f     %f      %f\n", t, jointPoses[0](0), jointPoses[0](1), jointRates[0](0), jointRates[0](1), jointAccelerations[0](0), jointAccelerations[0](1), jointTorques[0](0), jointTorques[0](1));
        }
    }
}
int main()
{

    using namespace KDL;

    //Definition of kinematic chain
    KDL::Tree youBotTree;
    
    //note that it seems youbot_arm.urdf and youbot.urdf use different values.
    //parser's assumption is that it return joints which are not of type None.
    if (!kdl_parser::treeFromFile("/home/azamat/programming/ros-diamondback/youbot-ros-pkg/youbot_common/youbot_description/robots/youbot.urdf", youBotTree))
   {
        std::cout << "Failed to construct kdl tree" << std::endl;
        return false;
   }
   // else
   // {
   //      std::cout << "succeeded " << youBotTree.getNrOfJoints()<< std::endl;
   //      std::cout << "succeeded " << youBotTree.getNrOfSegments()<< std::endl;
   // }
 
    KDL::Chain chain;
    youBotTree.getChain("arm_link_0","arm_link_5",chain);
    unsigned int numberOfJoints = chain.getNrOfJoints();
    unsigned int numberOfLinks = chain.getNrOfSegments();
    // std::cout << "number of chain links " << numberOfLinks << std::endl;
    // std::cout << "number of chain joints " << numberOfJoints << std::endl;
    //~Definition of kinematic chain

    //Definition of constraints and external disturbances
    //--------------------------------------------------------------------------------------//
    //Constraint force matrix at the end-effector
    //What is the convention for the spatial force matrix; is it the same as in thesis?
    //NOTE AZAMAT: Constraint are also defined in local reference frame?!
    unsigned int numberOfConstraints = 2;
    Twist constraintForce;
    Twists constraintForces;
    for (unsigned int i = 0; i < numberOfJoints; i++)
    {   
        SetToZero(constraintForce);
        constraintForces.push_back(constraintForce);
    }

    constraintForces[0].vel[0] = 0;
    constraintForces[1].vel[1] = 0;
    constraintForces[2].vel[2] = 0;

    #ifdef X_CONSTRAINT_SET
        constraintForces[0].vel[0] = 1;
    #endif //~X_CONSTRAINT_SET

    #ifdef Y_CONSTRAINT_SET
        constraintForces[1].vel[1] = 1;
    #endif //~Y_CONSTRAINT_SET

    #ifdef Z_CONSTRAINT_SET
        constraintForces[2].vel[2] = 1;
    #endif //~Z_CONSTRAINT_SET

    //Acceleration energy and constraint matrix at  the end-effector
    Jacobian alpha(numberOfConstraints);
    JntArray betha(numberOfConstraints); //set to zero
    JntArray bethaControl(numberOfConstraints); 
    for (unsigned int i = 0; i < numberOfConstraints; i++)
    {
        alpha.setColumn(i, constraintForces[i]);
        betha(i) = 0.0;
        bethaControl(i) = 0.0;

    }
    //arm root acceleration
    Vector linearAcc(0.0, 0.0, 9.8); //gravitational acceleration along Z
    Vector angularAcc(0.0, 0.0, 0.0);
    Twist twist0(linearAcc, angularAcc);

    //external forces on the arm
    Wrench externalNetForce;
    Wrenches externalNetForces;
    for (unsigned int i = 0; i < numberOfLinks; i++)
    {
        externalNetForces.push_back(externalNetForce);
    }
    //~Definition of constraints and external disturbances


    //Definition of solver and initial configuration
    //-------------------------------------------------------------------------------------//

    ChainIdSolver_Vereshchagin constraintSolver(chain, twist0, numberOfConstraints);

    //These arrays of joint values contain actual and desired values
    //actual is generated by a solver and integrator
    //desired is given by an interpolator
    //error is the difference between desired-actual
    //0-actual, 1-desired, 2-error, 3-sum of error
    unsigned int k = 4;
    JntArray jointPoses[k];
    JntArray jointRates[k];
    JntArray jointAccelerations[k];
    JntArray jointTorques[k];
    JntArray jointControlTorques[k];
    for (unsigned int i = 0; i < k; i++)
    {
        JntArray jointValues(numberOfJoints);
        jointPoses[i] = jointValues;
        jointRates[i] = jointValues;
        jointAccelerations[i] = jointValues;
        jointTorques[i] = jointValues;
        jointControlTorques[i] = jointValues;
    }

    //cartesian space/link values
    //0-actual, 1-desire, 2-error, 3-errorsum
    Frames cartX[k];
    Twists cartXDot[k];
    Twists cartXDotDot[k];
    Twist accLink;
    KDL::Frame frameTemp;
    for (unsigned int i = 0; i < k; i++) //i is number of variables (actual, desired, error)
    {
        for (unsigned int j = 0; j < numberOfLinks; j++) //j is number of links
        {
            cartX[i].push_back(frameTemp);
            cartXDot[i].push_back(accLink);
            cartXDotDot[i].push_back(accLink);
        }

    }


    // Initial arm position configuration/constraint, negative in clockwise
    JntArray jointInitialPose(numberOfJoints);
    jointInitialPose(0) = -M_PI/4.0;
    jointInitialPose(1) = M_PI / 6.0;
    jointInitialPose(2) = M_PI / 12.0;
    jointInitialPose(3) = -M_PI / 3.0;
    jointInitialPose(4) = M_PI / 18.0;
    //corresponds to x=0.031827      y = -0.007827     z = 0.472972
    JntArray jointFinalPose(numberOfJoints);
    jointFinalPose(0) = M_PI / 2.0;
    jointFinalPose(1) = M_PI / 2.5;
    jointFinalPose(2) = 0.0;
    jointFinalPose(3) = 0.0;
    jointFinalPose(4) = 0.0;
    // corresponds to 0.024000      -0.367062     0.242885 

    for (unsigned int i = 0; i < numberOfJoints; i++)
    {
        //actual initial
        jointPoses[0](i) = jointInitialPose(i);
        //desired initial
        jointPoses[1](i) = jointInitialPose(i);
    }

    
    //test
    #ifdef FKPOSE_TEST
        ChainFkSolverPos_recursive fksolver(chain);
        Frame tempEE;
        fksolver.JntToCart(jointPoses[0], tempEE, 5);
        std::cout << tempEE << std::endl;
        fksolver.JntToCart(jointFinalPose, tempEE, 5);
        std::cout << tempEE << std::endl;
    #endif //~FKPOSE_TEST
    //~Definition of solver and initial configuration
    //-------------------------------------------------------------------------------------//


    //Definition of process main loop
    //-------------------------------------------------------------------------------------//
    double taskTimeConstant = 2; //Time required to complete the task move(frameinitialPose, framefinalPose) default T=10.0
    double simulationTime = 2.5 * taskTimeConstant;
    double timeDelta = 0.001;
    double timeToSettle = 0.5;
    int status;
    double alfa(0.0), beta(0.0), gamma(0.0);
    //Controller gain configurations
    
    double ksi[3] = {1.0, 1.0, 1.0}; //damping factor
    double Kp[3];
    Kp[0] = 240.1475/(timeToSettle*timeToSettle);//0.1475
    Kp[1] = 140.0/(timeToSettle*timeToSettle);
    Kp[2] = 240.0/(timeToSettle*timeToSettle);
    double Kv[3];
    Kv[0] = 55.2245*ksi[0]/timeToSettle;//2.2245
    Kv[1] = 30.6*ksi[1]/timeToSettle;
    Kv[2] = 30.6*ksi[1]/timeToSettle;
    double Ki[3] = {0.0, 0.0, 0.0};
    double K = 0.005;
    
    //For joint space control without constraints using computed torque
    // double ksi[2] = {1.0, 1.0}; //damping factor
    double Kpq[numberOfJoints];
    Kpq[0] = 2.5/(timeToSettle*timeToSettle); 
    Kpq[1] = 2.2/(timeToSettle*timeToSettle);
    Kpq[2] = 20.1/(timeToSettle*timeToSettle);
    Kpq[3] = 40.1/(timeToSettle*timeToSettle);
    Kpq[4] = 40.1/(timeToSettle*timeToSettle);
   
    double Kvq[numberOfJoints];
    Kvq[0] = .5*ksi[0]/timeToSettle;   
    Kvq[1] = 1.0*ksi[1]/timeToSettle;
    Kvq[2] = 3.0*ksi[1]/timeToSettle;
    Kvq[3] = 3.0*ksi[1]/timeToSettle;
    Kvq[4] = 3.0*ksi[1]/timeToSettle;
   
    //Interpolator parameters: 
    // Initial x=0.031827      y = -0.007827     z = 0.472972 
    // Final     0.024000          -0.367062         0.242885 
    //cartesian space
    double b0_x = 0.031827; //should come from initial joint configuration
    double b1_x = 0.0;
    double b2_x = ((0.031827 - b0_x)*3.0 / (simulationTime * simulationTime)); 
    double b3_x = -((0.031827 - b0_x)*2.0 / (simulationTime * simulationTime * simulationTime));

    double b0_y = -0.007827; //should come from initial joint configuration            
    double b1_y = 0.0;
    double b2_y =  ((-0.007827 - b0_y)*3.0 / (simulationTime * simulationTime)); 
    double b3_y = -((-0.007827 - b0_y)*2.0 / (simulationTime * simulationTime * simulationTime));

    double b0_z = 0.472972; //should come from initial joint configuration
    double b1_z = 0.0;
    double b2_z = ((0.242885 - b0_z)*3.0 / (simulationTime * simulationTime)); 
    double b3_z = -((0.242885 - b0_z)*2.0 / (simulationTime * simulationTime * simulationTime));


    //joint space
    double a0_q0 = jointInitialPose(0);
    double a1_q0 = 0.0;
    double a2_q0 = ((jointFinalPose(0)  - jointInitialPose(0))*3.0 / (simulationTime * simulationTime));
    double a3_q0 = -((jointFinalPose(0) - jointInitialPose(0))*2.0 / (simulationTime * simulationTime * simulationTime));

    double a0_q1 = jointInitialPose(1);
    double a1_q1 = 0.0;
    double a2_q1 = ((jointFinalPose(1) - jointInitialPose(1))*3.0 / (simulationTime * simulationTime));
    double a3_q1 = -((jointFinalPose(1) - jointInitialPose(1))*2.0 / (simulationTime * simulationTime * simulationTime));
    
    double a0_q2 = jointInitialPose(2);
    double a1_q2 = 0.0;
    double a2_q2 = ((jointFinalPose(2) - jointInitialPose(2))*3.0 / (simulationTime * simulationTime));
    double a3_q2 = -((jointFinalPose(2) - jointInitialPose(2))*2.0 / (simulationTime * simulationTime * simulationTime));

    double a0_q3 = jointInitialPose(3);
    double a1_q3 = 0.0;
    double a2_q3 = ((jointFinalPose(3) - jointInitialPose(3))*3.0 / (simulationTime * simulationTime));
    double a3_q3 = -((jointFinalPose(3) - jointInitialPose(3))*2.0 / (simulationTime * simulationTime * simulationTime));


    double a0_q4 = jointInitialPose(4);
    double a1_q4 = 0.0;
    double a2_q4 = ((jointFinalPose(4) - jointInitialPose(4))*3.0 / (simulationTime * simulationTime));
    double a3_q4 = -((jointFinalPose(4) - jointInitialPose(4))*2.0 / (simulationTime * simulationTime * simulationTime));
    
    double feedforwardJointTorque0 = 0.0;
    double feedforwardJointTorque1 = 0.0;
    double feedforwardJointTorque2 = 0.0;
    double feedforwardJointTorque3 = 0.0;
    double feedforwardJointTorque4 = 0.0;
    //---------------------------------------------------------------------------------------//


    //Main simulation loop
    for (double t = 0.0; t <= simulationTime; t = t + timeDelta)
    {
        
        //Interpolation (Desired) q = a0+a1t+a2t^2+a3t^3
       
        cartX[1][4].p[0] = b0_x + b1_x * t + b2_x * t * t + b3_x * t * t*t;
        cartX[1][4].p[1] = b0_y + b1_y * t + b2_y * t * t + b3_y * t * t*t;
        cartX[1][4].p[2] = b0_z + b1_z * t + b2_z * t * t + b3_z * t * t*t;
        cartXDot[1][4].vel[0] = b1_x + 2 * b2_x * t + 3 * b3_x * t*t;
        cartXDot[1][4].vel[1] = b1_y + 2 * b2_y * t + 3 * b3_y * t*t;
        cartXDot[1][4].vel[2] = b1_z + 2 * b2_z * t + 3 * b3_z * t*t;
        cartXDotDot[1][4].vel[0] = 2 * b2_x + 6 * b3_x*t;
        cartXDotDot[1][4].vel[1] = 2 * b2_y + 6 * b3_y*t;
        cartXDotDot[1][4].vel[2] = 2 * b2_z + 6 * b3_z*t;

        #ifdef DESIRED_CARTESIAN_VALUES
            printf("%f          %f      %f     %f         %f        %f      %f\n", t, cartX[1][4].p[0], cartX[1][4].p[1], cartX[1][4].p[2], cartXDot[1][4].vel[0], cartXDot[1][4].vel[1], cartXDot[1][4].vel[2]);
        #endif //~DESIRED_CARTESIAN_VALUES

        jointPoses[1](0) = a0_q0 + a1_q0 * t + a2_q0 * t * t + a3_q0 * t * t*t;
        jointPoses[1](1) = a0_q1 + a1_q1 * t + a2_q1 * t * t + a3_q1 * t * t*t;
        jointPoses[1](2) = a0_q2 + a1_q2 * t + a2_q2 * t * t + a3_q2 * t * t*t;
        jointPoses[1](3) = a0_q3 + a1_q3 * t + a2_q3 * t * t + a3_q3 * t * t*t;
        jointPoses[1](4) = a0_q4 + a1_q4 * t + a2_q4 * t * t + a3_q4 * t * t*t;  
        
        jointRates[1](0) = a1_q0 + 2 * a2_q0 * t + 3 * a3_q0 * t*t;
        jointRates[1](1) = a1_q1 + 2 * a2_q1 * t + 3 * a3_q1 * t*t;
        jointRates[1](2) = a1_q2 + 2 * a2_q2 * t + 3 * a3_q2 * t*t;
        jointRates[1](3) = a1_q3 + 2 * a2_q3 * t + 3 * a3_q3 * t*t;
        jointRates[1](4) = a1_q4 + 2 * a2_q4 * t + 3 * a3_q4 * t*t;
        
        jointAccelerations[1](0) = 2 * a2_q0 + 6 * a3_q0*t;
        jointAccelerations[1](1) = 2 * a2_q1 + 6 * a3_q1*t;
        jointAccelerations[1](2) = 2 * a2_q2 + 6 * a3_q2*t;
        jointAccelerations[1](3) = 2 * a2_q3 + 6 * a3_q3*t;
        jointAccelerations[1](4) = 2 * a2_q4 + 6 * a3_q4*t;

        #ifdef DESIRED_JOINT_VALUES
            printf("%f       %f     %f      %f     %f    %f     %f     %f    %f     %f      %f\n", t,jointPoses[1](0), jointPoses[1](1),jointPoses[1](2), jointPoses[1](3), jointPoses[1](4),
            jointRates[1](0), jointRates[1](1), jointRates[1](2), jointRates[1](3), jointRates[1](4));
        #endif //~DESIRED_JOINT_VALUES

        status = constraintSolver.CartToJnt(jointPoses[0], jointRates[0], jointAccelerations[0], alpha, betha, bethaControl, externalNetForces, jointTorques[0], jointControlTorques[0]);
        constraintSolver.getLinkCartesianPose(cartX[0]);
        constraintSolver.getLinkCartesianVelocity(cartXDot[0]);
        constraintSolver.getLinkCartesianAcceleration(cartXDotDot[0]);
        cartX[0][4].M.GetEulerZYX(alfa,beta,gamma);

        #ifdef ACTUAL_CARTESIAN_VALUES
            printf("%f          %f      %f     %f         %f        %f      %f\n",  t, cartX[0][4].p[0], cartX[0][4].p[1], cartX[0][4].p[2], alfa, beta, gamma);
        #endif //~ACTUAL_CARTESIAN_VALUES  

        //Integration(robot joint values for rates and poses; actual) at the given "instanteneous" interval for joint position and velocity.
        for (unsigned int i = 0; i < numberOfJoints; i++)
        {
            jointRates[0](i) = jointRates[0](i) + jointAccelerations[0](i) * timeDelta; //Euler Forward
            jointPoses[0](i) = jointPoses[0](i) + (jointRates[0](i) - jointAccelerations[0](i) * timeDelta / 2.0) * timeDelta; //Trapezoidal rule
        }
        
        #ifdef ACTUAL_JOINT_VALUES
            printf("%f       %f     %f      %f     %f    %f     %f     %f      %f     %f    %f     %f      %f    %f       %f      %f     %f    %f      %f     %f    %f\n", 
            t,jointPoses[0](0), jointPoses[0](1),jointPoses[0](2), jointPoses[0](3), jointPoses[0](4), jointRates[0](0), jointRates[0](1), jointRates[0](2), jointRates[0](3), jointRates[0](4),
            jointAccelerations[0](0), jointAccelerations[0](1), jointAccelerations[0](2), jointAccelerations[0](3), jointAccelerations[0](4), jointTorques[0](0), jointTorques[0](1), jointTorques[0](2), jointTorques[0](3), jointTorques[0](4));
        #endif //~ACTUAL_JOINT_VALUES

        //Error
        for (unsigned int i = 0; i < numberOfJoints; i++)
        {
            jointPoses[2](i) = jointPoses[1](i) - jointPoses[0](i);
            jointRates[2](i) = jointRates[1](i) - jointRates[0](i);
            jointAccelerations[2](i) = jointAccelerations[1](i) - jointAccelerations[0](i);
            // jointPoses[3](i) += timeDelta * jointPoses[2](i);
        }

        #ifdef JOINT_ERROR_VALUES
           printf("%f      %f     %f    %f     %f     %f\n", t,jointPoses[2](0), jointPoses[2](1),jointPoses[2](2), jointPoses[2](3), jointPoses[2](4));
        #endif //~JOINT_ERROR_VALUES

        cartX[2][4].p[0] = cartX[1][4].p[0] - cartX[0][4].p[0];
        cartX[2][4].p[1] = cartX[1][4].p[1] - cartX[0][4].p[1];
        cartX[2][4].p[2] = cartX[1][4].p[2] - cartX[0][4].p[2];
        cartXDot[2][4].vel[0] = cartXDot[1][4].vel[0] - cartXDot[0][4].vel[0];
        cartXDot[2][4].vel[1] = cartXDot[1][4].vel[1] - cartXDot[0][4].vel[1];
        cartXDot[2][4].vel[2] = cartXDot[1][4].vel[2] - cartXDot[0][4].vel[2];
        cartXDotDot[2][4].vel[0] = cartXDotDot[1][4].vel[0] - cartXDotDot[0][4].vel[0];
        cartXDotDot[2][4].vel[1] = cartXDotDot[1][4].vel[1] - cartXDotDot[0][4].vel[1];
        cartXDotDot[2][4].vel[2] = cartXDotDot[1][4].vel[2] - cartXDotDot[0][4].vel[2];
        cartX[3][4].p[0] += timeDelta * cartX[2][4].p[0]; //for integral term;
        cartX[3][4].p[1] += timeDelta * cartX[2][4].p[1];
        cartX[3][4].p[2] += timeDelta * cartX[2][4].p[2];
        
        #ifdef CARTESIAN_ERROR_VALUES
            printf("%f          %f      %f     %f         %f        %f      %f\n", t, cartX[2][4].p[0], cartX[2][4].p[1], cartX[2][4].p[2], cartXDot[2][4].vel[0], cartXDot[2][4].vel[1], cartXDot[2][4].vel[2]);
         #endif //~CARTESIAN_ERROR_VALUES

        //Regulator or controller  
        //acceleration energy control
        betha(0) = alpha(0, 0)*(K * cartXDotDot[2][numberOfLinks-1].vel[0] + (Kv[0]) * cartXDot[2][numberOfLinks-1].vel[0] + (Kp[0]) * cartX[2][numberOfLinks-1].p[0]+ Ki[1] * cartX[3][numberOfLinks-1].p[0]); 
        betha(1) = alpha(1, 1)*(K * cartXDotDot[2][numberOfLinks-1].vel[1] + (Kv[1]) * cartXDot[2][numberOfLinks-1].vel[1] + (Kp[1]) * cartX[2][numberOfLinks-1].p[1] + Ki[1] * cartX[3][numberOfLinks-1].p[1]);
        
        // priority posture control
        // jointControlTorques[0](0) = jointAccelerations[1](0) + (Kpq[0])*jointPoses[2](0) + (Kvq[0])*jointRates[2](0);
        // jointControlTorques[0](1) = jointAccelerations[1](1) + (Kpq[1])*jointPoses[2](1) + (Kvq[1])*jointRates[2](1);//computed joint torque control
        // jointControlTorques[0](2) = jointAccelerations[1](2) + (Kpq[2])*jointPoses[2](2) + (Kvq[2])*jointRates[2](2);
        // jointControlTorques[0](3) = jointAccelerations[1](3) + (Kpq[3])*jointPoses[2](3) + (Kvq[3])*jointRates[2](3);
        // jointControlTorques[0](4) = jointAccelerations[1](4) + (Kpq[3])*jointPoses[2](4) + (Kvq[4])*jointRates[2](4);
        
        //priority constraint control
        // feedforwardJointTorque0 = jointAccelerations[1](0) + (Kpq[0])*jointPoses[2](0) + (Kvq[0])*jointRates[2](0);
        feedforwardJointTorque1 = jointAccelerations[1](1) + (Kpq[1])*jointPoses[2](1) + (Kvq[1])*jointRates[2](1);
        feedforwardJointTorque2 = jointAccelerations[1](2) + (Kpq[2])*jointPoses[2](2) + (Kvq[2])*jointRates[2](2);
        feedforwardJointTorque3 = jointAccelerations[1](3) + (Kpq[3])*jointPoses[2](3) + (Kvq[3])*jointRates[2](3);
        feedforwardJointTorque4 = jointAccelerations[1](4) + (Kpq[4])*jointPoses[2](4) + (Kvq[4])*jointRates[2](4);
        // jointTorques[0](0) = jointTorques[0](0) + feedforwardJointTorque0;
        jointTorques[0](1) = jointTorques[0](1) + feedforwardJointTorque1;
        jointTorques[0](2) = jointTorques[0](2) + feedforwardJointTorque2;
        jointTorques[0](3) = jointTorques[0](3) + feedforwardJointTorque3;
        jointTorques[0](4) = jointTorques[0](4) + feedforwardJointTorque4;
  
        //For cartesian space control one needs to calculate from the obtained joint space value, new cartesian space poses.
        //Then based on the difference of the signal (desired-actual) we define a regulation function (controller)
        // this difference should be compensated either by joint torques.
        // externalNetForces[numberOfLinks-1].force[0] = ((Kv[0]) * cartXDot[2][numberOfLinks-1].vel[0] + (Kp[0]) * cartX[2][numberOfLinks-1].p[0] );
        // externalNetForces[numberOfLinks-1].force[1] = ((Kv[1]) * cartXDot[2][numberOfLinks-1].vel[1] + (Kp[1]) * cartX[2][numberOfLinks-1].p[1] ); 
        externalNetForces[numberOfLinks-1].force[2] = ((Kv[2]) * cartXDot[2][numberOfLinks-1].vel[2] + (Kp[2]) * cartX[2][numberOfLinks-1].p[2] ); 
  

    }
    //~Definition of process main loop
    //-------------------------------------------------------------------------------------//





    return 0;
}
int main()
{

    using namespace KDL;


    //Definition of kinematic chain
    //-----------------------------------------------------------------------------------------------//
    //Joint (const JointType &type=None, const double &scale=1, const double &offset=0, const double &inertia=0, const double &damping=0, const double &stiffness=0)
    Joint rotJoint0 = Joint(Joint::RotZ, 1, 0, 0.01);
    Joint rotJoint1 = Joint(Joint::RotZ, 1, 0, 0.01);
    Joint rotJoint2 = Joint(Joint::RotZ, 1, 0, 0.01);
    Joint rotJoint3 = Joint(Joint::RotZ, 1, 0, 0.01);

    Frame refFrame(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, 0.0, 0.0));
    Frame frame1(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, -0.2, 0.0));
    Frame frame2(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, -0.2, 0.0));
    Frame frame3(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, -0.2, 0.0));
    Frame frame4(Rotation::RPY(0.0, 0.0, 0.0), Vector(0.0, -0.2, 0.0));
    //Segment (const Joint &joint=Joint(Joint::None), const Frame &f_tip=Frame::Identity(), const RigidBodyInertia &I=RigidBodyInertia::Zero())
    Segment segment1 = Segment(rotJoint0, frame1);
    Segment segment2 = Segment(rotJoint1, frame2);
    Segment segment3 = Segment(rotJoint2, frame3);
    Segment segment4 = Segment(rotJoint3, frame4);

    // 	RotationalInertia (double Ixx=0, double Iyy=0, double Izz=0, double Ixy=0, double Ixz=0, double Iyz=0)
    RotationalInertia rotInerSeg1(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); //around symmetry axis of rotation
    //RigidBodyInertia (double m=0, const Vector &oc=Vector::Zero(), const RotationalInertia &Ic=RotationalInertia::Zero())
    RigidBodyInertia inerSegment1(0.5, Vector(0.0, -0.2, 0.0), rotInerSeg1);
    RigidBodyInertia inerSegment2(0.5, Vector(0.0, -0.2, 0.0), rotInerSeg1);
    RigidBodyInertia inerSegment3(0.5, Vector(0.0, -0.2, 0.0), rotInerSeg1);
    RigidBodyInertia inerSegment4(0.5, Vector(0.0, -0.2, 0.0), rotInerSeg1);
    segment1.setInertia(inerSegment1);
    segment2.setInertia(inerSegment2);
    segment3.setInertia(inerSegment3);
    segment4.setInertia(inerSegment4);

    Chain chain;
    chain.addSegment(segment1);
    chain.addSegment(segment2);
    chain.addSegment(segment3);
    chain.addSegment(segment4);
    //~Definition of kinematic chain




    //Definition of constraints and external disturbances
    //--------------------------------------------------------------------------------------//
    //Constraint force matrix at the end-effector
    //What is the convention for the spatial force matrix; is it the same as in thesis?
    //NOTE AZAMAT: Constraint are also defined in local reference frame?!
    Vector constrainXLinear(1.0, 0.0, 0.0);
    Vector constrainXAngular(0.0, 0.0, 0.0);
    Vector constrainYLinear(0.0, 0.0, 0.0);
    Vector constrainYAngular(0.0, 0.0, 0.0);
    Vector constrainZLinear(0.0, 0.0, 0.0);
    Vector constrainZAngular(0.0, 0.0, 0.0);
    Twist constraintForcesX(constrainXLinear, constrainXAngular);
    Twist constraintForcesY(constrainYLinear, constrainYAngular);
    Twist constraintForcesZ(constrainZLinear, constrainZAngular);
    Jacobian alpha(1);
    alpha.setColumn(0, constraintForcesX);
    // alpha.setColumn(1, constraintForcesY);
    //Acceleration energy at  the end-effector
    JntArray betha(1); //set to zero
    betha(0) = 0.0;
    // betha(1) = 0.0;
    //betha(2) = 0.0;
    //arm root acceleration
    Vector linearAcc(0.0, 9.8, 0.0); //gravitational acceleration along Y
    Vector angularAcc(0.0, 0.0, 0.0);
    Twist twist1(linearAcc, angularAcc);
    //external forces on the arm
    Vector externalForce1(0.0, 0.0, 0.0);
    Vector externalTorque1(0.0, 0.0, 0.0);
    Vector externalForce2(0.0, 0.0, 0.0);
    Vector externalTorque2(0.0, 0.0, 0.0);
    Wrench externalNetForce1(externalForce1, externalTorque1);
    Wrench externalNetForce2(externalForce2, externalTorque2);
    Wrenches externalNetForce;
    externalNetForce.push_back(externalNetForce1);
    externalNetForce.push_back(externalNetForce2);
    externalNetForce.push_back(externalNetForce1);
    externalNetForce.push_back(externalNetForce2);
    //~Definition of constraints and external disturbances



    //Definition of solver and initial configuration
    //-------------------------------------------------------------------------------------//
    int numberOfConstraints = 1;
    ChainIdSolver_Vereshchagin constraintSolver(chain, twist1, numberOfConstraints);

    //These arrays of joint values contain actual and desired values
    //actual is generated by a solver and integrator
    //desired is given by an interpolator
    //error is the difference between desired-actual
    //0-actual, 1-desired, 2-error
    int k = 4;
    JntArray jointPoses[k];
    JntArray jointRates[k];
    JntArray jointAccelerations[k];
    JntArray jointTorques[k];
    JntArray biasqDotDot(chain.getNrOfJoints());
    for (int i = 0; i < k; i++)
    {
        JntArray jointValues(chain.getNrOfJoints());
        jointPoses[i] = jointValues;
        jointRates[i] = jointValues;
        jointAccelerations[i] = jointValues;
        jointTorques[i] = jointValues;
    }


    //cartesian space/link values
    //0-actual, 1-desire, 2-error, 3-errorsum
    k = 4;
    Frames cartX[k];
    Twists cartXDot[k];
    Twists cartXDotDot[k];
    Twist accLink;
    for (int i = 0; i < k; i++) //i is number of variables (actual, desired, error)
    {
        for (int j = 0; j < 4; j++) //j is number of links, in this case 4
        {
            cartX[i].push_back(frame1);
            cartXDot[i].push_back(accLink);
            cartXDotDot[i].push_back(accLink);
        }

    }


    // Initial arm position configuration/constraint, negative in clockwise
    JntArray jointFinalPose(chain.getNrOfJoints());
    jointFinalPose(0) = M_PI/2.0;
    jointFinalPose(1) = M_PI/24.0;
    jointFinalPose(2) = -M_PI/12.0;
    jointFinalPose(3) = M_PI/12.0;
    //correspond to x = 0.398289   y = 0.026105

    JntArray jointInitialPose(chain.getNrOfJoints());
    jointInitialPose(0) = 5*M_PI/6.0;
    jointInitialPose(1) = M_PI/12.0;
    jointInitialPose(2) = -M_PI/6.0;
    jointInitialPose(3) = -M_PI/3.0;
    //correspond to x = 0.151764      y= 0.366390

    //actual initial
    jointPoses[0](0) = jointInitialPose(0);
    jointPoses[0](1) = jointInitialPose(1);
    jointPoses[0](2) = jointInitialPose(2);
    jointPoses[0](3) = jointInitialPose(3);

    //desired initial
    // jointPoses[1](0) = jointInitialPose(0);
    // jointPoses[1](1) = jointInitialPose(1);
    //~Definition of solver and initial configuration
    //-------------------------------------------------------------------------------------//



    //Definition of process main loop
    //-------------------------------------------------------------------------------------//
    //-------------------------------------------------------------------------------------//
    double taskTimeConstant = 2.5; //Time required to complete the task move(frameinitialPose, framefinalPose) default T=10.0
    double simulationTime = 2*taskTimeConstant;
    double timeDelta = 0.001;
    double timeToSettle = 0.015;
    int status;

    double ksi[2] = {1.0, 1.0}; //damping factor
    double Kp[2];
    Kp[0] = 5.49996/(timeToSettle*timeToSettle); 
    Kp[1] = 1.352/(timeToSettle*timeToSettle);
    double Kv[2];
    Kv[0] = 18.4997*ksi[0]/timeToSettle; 
    Kv[1] = 7.5189*ksi[1]/timeToSettle;
    double Ki[2] = {0.0, 0.0};
    double K = 0.005;
    /*
    //For cartesian space control with constraints and using external forces
    double ksi[2] = {1.0, 1.0}; //damping factor
    double Kp[2];
    Kp[0] = 6000.0/(taskTimeConstant*taskTimeConstant);
    Kp[1] = 11000.0/(taskTimeConstant*taskTimeConstant);
    double Kv[2];
    Kv[0] = 130*ksi[0]/taskTimeConstant;
    Kv[1] = 160*ksi[1]/taskTimeConstant;
    double Ki[2] = {-5.01, -5.1};

    //For cartesian space control without constraints using external forces
    double ksi[2] = {1.0, 1.0}; //damping factor
    double Kp[2];
    Kp[0] = 7000.0/(taskTimeConstant*taskTimeConstant);
    Kp[1] = 12000.0/(taskTimeConstant*taskTimeConstant);
    double Kv[2];
    Kv[0] = 130*ksi[0]/taskTimeConstant;
    Kv[1] = 160*ksi[1]/taskTimeConstant;
    double Ki[2] = {-5.01, -5.1};

    //For joint space control without constraints using computed torque
    double ksi[2] = {1.0, 1.0}; //damping factor
    double Kp[2];
    Kp[0] = 4000.0/(taskTimeConstant*taskTimeConstant);
    Kp[1] = 3200.0/(taskTimeConstant*taskTimeConstant);
    double Kv[2];
    Kv[0] = 20*ksi[0]/taskTimeConstant;
    Kv[1] = 30*ksi[1]/taskTimeConstant;
    double Ki[2] = {33.5, 10.5};
    double Ka[2] = {0.0, 0.0};
    */
    //Interpolator parameters:
    
    double b0_y = 0.366390; //should come from initial joint configuration
    double b1_y = 0.0;
    double b2_y =  ((0.026105 - b0_y)*3.0 / (simulationTime * simulationTime)); //yFinal = 0.026105 x= 0.398289      
    double b3_y = -((0.026105 - b0_y)*2.0 / (simulationTime * simulationTime * simulationTime));

    double b0_x = 0.151764; //should come from initial joint configuration
    double b1_x = 0.0;
    double b2_x = ((0.151764 - b0_x)*3.0 / (simulationTime * simulationTime)); // Xfinal= xInitial = 0.151764
    double b3_x = -((0.151764 - b0_x)*2.0 / (simulationTime * simulationTime * simulationTime));
     
    /*
    double a0_q0 = jointInitialPose(0);
    double a1_q0 = 0.0;
    double a2_q0 = ((jointFinalPose(0)  - jointInitialPose(0))*3.0 / (simulationTime * simulationTime));
    double a3_q0 = -((jointFinalPose(0) - jointInitialPose(0))*2.0 / (simulationTime * simulationTime * simulationTime));

    double a0_q1 = jointInitialPose(1);
    double a1_q1 = 0.0;
    double a2_q1 = ((jointFinalPose(1) - jointInitialPose(1))*3.0 / (simulationTime * simulationTime));
    double a3_q1 = -((jointFinalPose(1) - jointInitialPose(1))*2.0 / (simulationTime * simulationTime * simulationTime));
    */

    double feedforwardJointTorque0 = 0.0;
    double feedforwardJointTorque1 = 0.0;


    for (double t = 0.0; t <= simulationTime; t = t + timeDelta)
    {
        /*
         * double j1 = 0;
        double j2 = 0;
        double j3 = 0;
        double j4 = 0;
        Eigen::MatrixXd chainJacobian(6, 2);
        chainJacobian.setZero();
        chainJacobian(5, 0) = 1;
        chainJacobian(5, 1) = 1;
        // Jacobian inverse
        j1 = -0.4 * sin(jointPoses[0](0)) - 0.4 * sin(jointPoses[0](1));
        j2 = -0.4 * sin(jointPoses[0](0) + jointPoses[0](0));
        j3 = 0.4 * cos(jointPoses[0](0)) + 0.4 * cos(jointPoses[0](0) + jointPoses[0](1));
        j4 = 0.4 * cos(jointPoses[0](0) + jointPoses[0](1));

        //printf("t, j1, j2, j3, j4   %f      %f          %f      %f      %f\n", t, j1, j2, j3, j4);

        chainJacobian(0, 0) = j1;
        chainJacobian(0, 1) = j2;
        chainJacobian(1, 0) = j3;
        chainJacobian(1, 1) = j4;

         */


        //Interpolation (Desired) q = a0+a1t+a2t^2+a3t^3
        //Do we feed these values? then         jointPoses[0] = jointPoses[1];         jointRates[0] = jointRates[1];
        // But I don't think so, in control desired trajectory plays role of the reference that the controller should strive for from its actual (previous, current) state.
        
        cartX[1][1].p[0] = b0_x + b1_x * t + b2_x * t * t + b3_x * t * t*t;
        cartX[1][1].p[1] = b0_y + b1_y * t + b2_y * t * t + b3_y * t * t*t;
        cartXDot[1][1].vel[0] = b1_x + 2 * b2_x * t + 3 * b3_x * t*t;
        cartXDot[1][1].vel[1] = b1_y + 2 * b2_y * t + 3 * b3_y * t*t;
        cartXDotDot[1][1].vel[0] = 2 * b2_x + 6 * b3_x*t;
        cartXDotDot[1][1].vel[1] = 2 * b2_y + 6 * b3_y*t;
        // printf("%f          %f      %f     %f         %f        %f      %f\n", t, cartX[1][1].p[0], cartX[1][1].p[1], cartXDot[1][1].vel[0], cartXDot[1][1].vel[1], cartXDotDot[1][1].vel[0], cartXDotDot[1][1].vel[1]);
        //printf("Desired Cartesian values: %f          %f      %f     %f         %f        %f      %f\n", t, cartX[1][1].p[0], cartX[1][1].p[1], cartXDot[1][1].vel[0], cartXDot[1][1].vel[1], cartXDotDot[1][1].vel[0], cartXDotDot[1][1].vel[1]);
        
        /*
        jointPoses[1](0) = a0_q0 + a1_q0 * t + a2_q0 * t * t + a3_q0 * t * t*t;
        jointPoses[1](1) = a0_q1 + a1_q1 * t + a2_q1 * t * t + a3_q1 * t * t*t;
        jointRates[1](0) = a1_q0 + 2 * a2_q0 * t + 3 * a3_q0 * t*t;
        jointRates[1](1) = a1_q1 + 2 * a2_q1 * t + 3 * a3_q1 * t*t;
        jointAccelerations[1](0) = 2 * a2_q0 + 6 * a3_q0*t;
        jointAccelerations[1](1) = 2 * a2_q1 + 6 * a3_q1*t;
        //printf("Desired joint values: %f         %f          %f      %f       %f     %f       %f\n", t, jointPoses[1](0), jointPoses[1](1), jointRates[1](0), jointRates[1](1), jointAccelerations[1](0), jointAccelerations[1](1));
        //printf("%f         %f          %f      %f       %f     %f       %f\n", t, jointPoses[1](0), jointPoses[1](1), jointRates[1](0), jointRates[1](1), jointAccelerations[1](0), jointAccelerations[1](1));
        */

        status = constraintSolver.CartToJnt(jointPoses[0], jointRates[0], jointAccelerations[0],alpha, betha, externalNetForce, jointTorques[0]);  

        constraintSolver.getLinkCartesianPose(cartX[0]);
        constraintSolver.getLinkCartesianVelocity(cartXDot[0]);
        constraintSolver.getLinkCartesianAcceleration(cartXDotDot[0]);
        printf("%f          %f      %f     %f         %f        %f      %f\n", t, cartX[0][1].p.x(), cartX[0][1].p.y(), cartXDot[0][1].vel[0], cartXDot[0][1].vel[1], cartXDotDot[0][1].vel[0], cartXDotDot[0][1].vel[1]);
        // printf("Actual cartesian values: %f          %f      %f     %f         %f        %f      %f\n", t, cartX[0][1].p.x(), cartX[0][1].p.y(), cartXDot[0][1].vel[0], cartXDot[0][1].vel[1], cartXDotDot[0][1].vel[0], cartXDotDot[0][1].vel[1]);

        //Integration(robot joint values for rates and poses; actual) at the given "instanteneous" interval for joint position and velocity.
        jointRates[0](0) = jointRates[0](0) + jointAccelerations[0](0) * timeDelta; //Euler Forward
        jointPoses[0](0) = jointPoses[0](0) + (jointRates[0](0) - jointAccelerations[0](0) * timeDelta / 2.0) * timeDelta; //Trapezoidal rule
        jointRates[0](1) = jointRates[0](1) + jointAccelerations[0](1) * timeDelta; //Euler Forward
        jointPoses[0](1) = jointPoses[0](1) + (jointRates[0](1) - jointAccelerations[0](1) * timeDelta / 2.0) * timeDelta;

        jointRates[0](2) = jointRates[0](2) + jointAccelerations[0](2) * timeDelta; //Euler Forward
        jointPoses[0](2) = jointPoses[0](2) + (jointRates[0](2) - jointAccelerations[0](2) * timeDelta / 2.0) * timeDelta; //Trapezoidal rule
        jointRates[0](3) = jointRates[0](3) + jointAccelerations[0](3) * timeDelta; //Euler Forward
        jointPoses[0](3) = jointPoses[0](3) + (jointRates[0](3) - jointAccelerations[0](3) * timeDelta / 2.0) * timeDelta;
        // printf("%f          %f      %f       %f     %f       %f      %f     %f      %f\n", t, jointPoses[0](0), jointPoses[0](1), jointPoses[0](2), jointPoses[0](3), jointAccelerations[0](0), jointAccelerations[0](1), jointAccelerations[0](2), jointAccelerations[0](3));
        //printf("Actual joint values: %f          %f      %f       %f     %f       %f      %f     %f      %f\n", t, jointPoses[0](0), jointPoses[0](1), jointRates[0](0), jointRates[0](1), jointAccelerations[0](0), jointAccelerations[0](1), jointTorques[0](0), jointTorques[0](1));
        //Error
        /*
        jointPoses[2](0) = jointPoses[1](0) - jointPoses[0](0);
        jointPoses[2](1) = jointPoses[1](1) - jointPoses[0](1);
        jointRates[2](0) = jointRates[1](0) - jointRates[0](0);
        jointRates[2](1) = jointRates[1](1) - jointRates[0](1);
        jointAccelerations[2](0) = jointAccelerations[1](0) - jointAccelerations[0](0);
        jointAccelerations[2](1) = jointAccelerations[1](1) - jointAccelerations[0](1);
        jointPoses[3](0) += timeDelta*jointPoses[2](0);
        jointPoses[3](1) += timeDelta*jointPoses[2](1);
        //printf("%f          %f      %f          %f     %f       %f      %f\n", t, jointPoses[2](0), jointPoses[2](1), jointRates[2](0), jointRates[2](1), jointAccelerations[2](0), jointAccelerations[2](1));
        */

        cartX[2][1].p[0] = cartX[1][1].p[0] - cartX[0][1].p[0];
        cartX[2][1].p[1] = cartX[1][1].p[1] - cartX[0][1].p[1];
        cartXDot[2][1].vel[0] = cartXDot[1][1].vel[0] - cartXDot[0][1].vel[0];
        cartXDot[2][1].vel[1] = cartXDot[1][1].vel[1] - cartXDot[0][1].vel[1];
        cartXDotDot[2][1].vel[0] = cartXDotDot[1][1].vel[0] - cartXDotDot[0][1].vel[0];
        cartXDotDot[2][1].vel[1] = cartXDotDot[1][1].vel[1] - cartXDotDot[0][1].vel[1];
        cartX[3][1].p[0] += timeDelta * cartX[2][1].p[0]; //for integral term;
        cartX[3][1].p[1] += timeDelta * cartX[2][1].p[1];
        //printf("%f          %f      %f     %f         %f        %f      %f\n", t, cartX[2][1].p[0], cartX[2][1].p[1], cartXDot[2][1].vel[0], cartXDot[2][1].vel[1], cartXDotDot[2][1].vel[1], cartXDotDot[2][1].vel[1]);

        //Regulator or controller
        //acceleration energy control
         // betha(0) = alpha(0, 0)*(K * cartXDotDot[2][1].vel[0] + (Kv[0]) * cartXDot[2][1].vel[0] + (Kp[0]) * cartX[2][1].p[0]+ Ki[1] * cartX[3][1].p[0]); // 0.5xgain
        // betha(1) = alpha(1, 1)*(K * cartXDotDot[2][1].vel[1] + (Kv[0]) * cartXDot[2][1].vel[1] + (Kp[1]) * cartX[2][1].p[1] + Ki[1] * cartX[3][1].p[0]);
        /*
        //computed joint torque control
        feedforwardJointTorque0 = jointAccelerations[1](0) + (Kp[0])*jointPoses[2](0) + (Kv[0])*jointRates[2](0) + (Ki[0])*jointPoses[3](0);
        feedforwardJointTorque1 = jointAccelerations[1](1) + (Kp[1])*jointPoses[2](1) + (Kv[1])*jointRates[2](1)+ (Ki[1])*jointPoses[3](1);
        jointTorques[0](0) = jointTorques[0](0) + feedforwardJointTorque0;
        jointTorques[0](1) = jointTorques[0](1) + feedforwardJointTorque1;

        //For cartesian space control one needs to calculate from the obtained joint space value, new cartesian space poses.
        //Then based on the difference of the signal (desired-actual) we define a regulation function (controller)
        // this difference should be compensated either by joint torques.
        externalNetForce[1].force[0] = cartXDotDot[1][1].vel[0] + ((Kv[0]) * cartXDot[2][1].vel[0] + (Kp[0]) * cartX[2][1].p[0] + (Ki[0]) * cartX[3][1].p[0]);
        externalNetForce[1].force[1] = cartXDotDot[1][1].vel[1] + ((Kv[1]) * cartXDot[2][1].vel[1] + (Kp[1]) * cartX[2][1].p[1] + (Ki[1]) * cartX[3][1].p[1]);
        */
        externalNetForce[1].force[0] = ((Kv[0]) * cartXDot[2][1].vel[0] + (Kp[0]) * cartX[2][1].p[0] );
        externalNetForce[1].force[1] = ((Kv[1]) * cartXDot[2][1].vel[1] + (Kp[1]) * cartX[2][1].p[1] ); //controlling y seems to help a little

    }
    //~Definition of process main loop
    //-------------------------------------------------------------------------------------//





    return 0;
}