mitk::ConnectomicsNetworkCreator::ImageLabelPairType mitk::ConnectomicsNetworkCreator::EndElementPositionLabelAvoidingWhiteMatter( TractType::Pointer singleTract )
{
  ImageLabelPairType labelpair;

  {// Note: .fib image tracts are safed using index coordinates
    mitk::Point3D firstElementFiberCoord, lastElementFiberCoord;
    mitk::Point3D firstElementSegCoord, lastElementSegCoord;
    itk::Index<3> firstElementSegIndex, lastElementSegIndex;

    if( singleTract->front().Size() != 3 )
    {
      MBI_ERROR << mitk::ConnectomicsConstantsManager::CONNECTOMICS_ERROR_INVALID_DIMENSION_NEED_3;
    }
    for( unsigned int index = 0; index < singleTract->front().Size(); index++ )
    {
      firstElementFiberCoord.SetElement( index, singleTract->front().GetElement( index ) );
      lastElementFiberCoord.SetElement( index, singleTract->back().GetElement( index ) );
    }

    // convert from fiber index coordinates to segmentation index coordinates
    FiberToSegmentationCoords( firstElementFiberCoord, firstElementSegCoord );
    FiberToSegmentationCoords( lastElementFiberCoord, lastElementSegCoord );

    for( int index = 0; index < 3; index++ )
    {
      firstElementSegIndex.SetElement( index, firstElementSegCoord.GetElement( index ) );
      lastElementSegIndex.SetElement( index, lastElementSegCoord.GetElement( index ) );
    }

    int firstLabel = m_SegmentationItk->GetPixel(firstElementSegIndex);
    int lastLabel = m_SegmentationItk->GetPixel(lastElementSegIndex );

    // Check whether the labels belong to the white matter (which means, that the fibers ended early)
    bool extendFront(false), extendEnd(false), retractFront(false), retractEnd(false);
    extendFront = !IsNonWhiteMatterLabel( firstLabel );
    extendEnd = !IsNonWhiteMatterLabel( lastLabel );
    retractFront = IsBackgroundLabel( firstLabel );
    retractEnd = IsBackgroundLabel( lastLabel );

    //if( extendFront || extendEnd )
    //{
    //MBI_INFO << "Before Start: " << firstLabel << " at " << firstElementSegIndex[ 0 ] << " " << firstElementSegIndex[ 1 ] << " " << firstElementSegIndex[ 2 ] << " End: " << lastLabel << " at " << lastElementSegIndex[ 0 ] << " " << lastElementSegIndex[ 1 ] << " " << lastElementSegIndex[ 2 ];
    //}
    if ( extendFront )
    {
      std::vector< int > indexVectorOfPointsToUse;

      //Use first two points for direction
      indexVectorOfPointsToUse.push_back( 1 );
      indexVectorOfPointsToUse.push_back( 0 );

      // label and coordinate temp storage
      int tempLabel( firstLabel );
      itk::Index<3> tempIndex = firstElementSegIndex;

      LinearExtensionUntilGreyMatter( indexVectorOfPointsToUse, singleTract, tempLabel, tempIndex );

      firstLabel = tempLabel;
      firstElementSegIndex = tempIndex;

    }

    if ( extendEnd )
    {
      std::vector< int > indexVectorOfPointsToUse;

      //Use last two points for direction
      indexVectorOfPointsToUse.push_back( singleTract->Size() - 2 );
      indexVectorOfPointsToUse.push_back( singleTract->Size() - 1 );

      // label and coordinate temp storage
      int tempLabel( lastLabel );
      itk::Index<3> tempIndex = lastElementSegIndex;

      LinearExtensionUntilGreyMatter( indexVectorOfPointsToUse, singleTract, tempLabel, tempIndex );

      lastLabel = tempLabel;
      lastElementSegIndex = tempIndex;
    }
        if ( retractFront )
    {
      // label and coordinate temp storage
      int tempLabel( firstLabel );
      itk::Index<3> tempIndex = firstElementSegIndex;

      RetractionUntilBrainMatter( true, singleTract, tempLabel, tempIndex );

      firstLabel = tempLabel;
      firstElementSegIndex = tempIndex;

    }

    if ( retractEnd )
    {
      // label and coordinate temp storage
      int tempLabel( lastLabel );
      itk::Index<3> tempIndex = lastElementSegIndex;

      RetractionUntilBrainMatter( false, singleTract, tempLabel, tempIndex );

      lastLabel = tempLabel;
      lastElementSegIndex = tempIndex;
    }
    //if( extendFront || extendEnd )
    //{
    //    MBI_INFO << "After Start: " << firstLabel << " at " << firstElementSegIndex[ 0 ] << " " << firstElementSegIndex[ 1 ] << " " << firstElementSegIndex[ 2 ] << " End: " << lastLabel << " at " << lastElementSegIndex[ 0 ] << " " << lastElementSegIndex[ 1 ] << " " << lastElementSegIndex[ 2 ];
    //}

    labelpair.first = firstLabel;
    labelpair.second = lastLabel;

    // Add property to property map
    CreateNewNode( firstLabel, firstElementSegIndex, m_UseCoMCoordinates );
    CreateNewNode( lastLabel, lastElementSegIndex, m_UseCoMCoordinates );
  }

  return labelpair;
}
void mitk::ConnectomicsNetworkCreator::RetractionUntilBrainMatter( bool retractFront, TractType::Pointer singleTract,
                                                                  int & label, itk::Index<3> & mitkIndex )
{
  int retractionStartIndex( singleTract->Size() - 1 );
  int retractionStepIndexSize( -1 );
  int retractionTerminationIndex( 0 );

  if( retractFront )
  {
    retractionStartIndex = 0;
    retractionStepIndexSize = 1;
    retractionTerminationIndex = singleTract->Size() - 1;
  }

  int currentRetractionIndex = retractionStartIndex;

  bool keepRetracting( true );

  mitk::Point3D currentPoint, nextPoint;
  std::vector< double > differenceVector;
  differenceVector.resize( singleTract->front().Size() );

  while( keepRetracting && ( currentRetractionIndex != retractionTerminationIndex ) )
  {
    // convert to segmentation coords
    mitk::Point3D currentPointFiberCoord, nextPointFiberCoord;
    for( unsigned int index = 0; index < singleTract->front().Size(); index++ )
    {
      currentPointFiberCoord.SetElement( index, singleTract->GetElement( currentRetractionIndex ).GetElement( index ) );
      nextPointFiberCoord.SetElement( index, singleTract->GetElement( currentRetractionIndex + retractionStepIndexSize ).GetElement( index ) );
    }

    FiberToSegmentationCoords( currentPointFiberCoord, currentPoint );
    FiberToSegmentationCoords( nextPointFiberCoord, nextPoint );

    // calculate straight line

    for( unsigned int index = 0; index < singleTract->front().Size(); index++ )
    {
      differenceVector[ index ] = nextPoint.GetElement( index ) - currentPoint.GetElement( index );
    }

    // calculate length of direction vector

    double length( 0.0 );
    double sum( 0.0 );

    for( unsigned int index = 0; index < differenceVector.size() ; index++ )
    {
      sum = sum + differenceVector[ index ] * differenceVector[ index ];
    }

    length = std::sqrt( sum );

    // retract
    itk::Index<3> tempIndex;
    int tempLabel( label );

    for( int parameter( 0 ) ; parameter < length ; parameter++ )
    {

      for( int index( 0 ); index < 3; index++ )
      {
        tempIndex.SetElement( index,
          currentPoint.GetElement( index ) + ( 1.0 + parameter ) / ( 1.0 + length ) * differenceVector[ index ] );
      }

      tempLabel = m_SegmentationItk->GetPixel( tempIndex );

      if( !IsBackgroundLabel( tempLabel ) )
      {
        // check whether result is within the search space
        {
          mitk::Point3D endPoint, foundPointSegmentation, foundPointFiber;
          for( unsigned int index = 0; index < singleTract->front().Size(); index++ )
          {
            // this is in fiber (world) coordinates
            endPoint.SetElement( index, singleTract->GetElement( retractionStartIndex ).GetElement( index ) );
          }

          for( int index( 0 ); index < 3; index++ )
          {
            foundPointSegmentation.SetElement( index,
              currentPoint.GetElement( index ) + ( 1.0 + parameter ) / ( 1.0 + length ) * differenceVector[ index ] );
          }

          SegmentationToFiberCoords( foundPointSegmentation, foundPointFiber );

          std::vector< double > finalDistance;
          finalDistance.resize( singleTract->front().Size() );
          for( unsigned int index = 0; index < singleTract->front().Size(); index++ )
          {
            finalDistance[ index ] = foundPointFiber.GetElement( index ) - endPoint.GetElement( index );
          }

          // calculate length of direction vector

          double finalLength( 0.0 );
          double finalSum( 0.0 );

          for( unsigned int index = 0; index < finalDistance.size() ; index++ )
          {
            finalSum = finalSum + finalDistance[ index ] * finalDistance[ index ];
          }
          finalLength = std::sqrt( finalSum );

          if( finalLength > m_EndPointSearchRadius )
          {
            // the found point was not within the search space
            return;
          }
        }

        label = tempLabel;
        mitkIndex = tempIndex;
        return;
      }
      // hit next point without finding brain matter
      currentRetractionIndex = currentRetractionIndex + retractionStepIndexSize;
      if( ( currentRetractionIndex < 1 ) || ( (unsigned int)currentRetractionIndex > ( singleTract->Size() - 2 ) ) )
      {
        keepRetracting = false;
      }
    }
  }
}
void mitk::ConnectomicsNetworkCreator::RetractionUntilBrainMatter( bool retractFront, TractType::Pointer singleTract, 
                                                                  int & label, mitk::Index3D & mitkIndex )
{
  int retractionStartIndex( singleTract->Size() - 1 );
  int retractionStepIndexSize( -1 );
  int retractionTerminationIndex( 0 );

  if( retractFront )
  {
    retractionStartIndex = 0;
    retractionStepIndexSize = 1;
    retractionTerminationIndex = singleTract->Size() - 1;
  }

  int currentRetractionIndex = retractionStartIndex;

  bool keepRetracting( true );

  mitk::Point3D currentPoint, nextPoint;
  std::vector< double > differenceVector;
  differenceVector.resize( singleTract->front().Size() );

  while( keepRetracting && ( currentRetractionIndex != retractionTerminationIndex ) )
  {
    // convert to segmentation coords
    mitk::Point3D currentPointFiberCoord, nextPointFiberCoord;
    for( int index = 0; index < singleTract->front().Size(); index++ )
    {
      currentPointFiberCoord.SetElement( index, singleTract->GetElement( currentRetractionIndex ).GetElement( index ) );
      nextPointFiberCoord.SetElement( index, singleTract->GetElement( currentRetractionIndex + retractionStepIndexSize ).GetElement( index ) );
    }

    FiberToSegmentationCoords( currentPointFiberCoord, currentPoint );
    FiberToSegmentationCoords( nextPointFiberCoord, nextPoint );

    // calculate straight line

    for( int index = 0; index < singleTract->front().Size(); index++ )
    {
      differenceVector[ index ] = nextPoint.GetElement( index ) - currentPoint.GetElement( index );
    }

    // calculate length of direction vector

    double length( 0.0 );
    double sum( 0.0 );

    for( int index = 0; index < differenceVector.size() ; index++ )
    {
      sum = sum + differenceVector[ index ] * differenceVector[ index ];
    }

    length = std::sqrt( sum );

    // retract
    mitk::Index3D tempIndex;
    int tempLabel( label );

    for( int parameter( 0 ) ; parameter < length ; parameter++ )
    {

      for( int index( 0 ); index < 3; index++ )
      {
        tempIndex.SetElement( index, 
          currentPoint.GetElement( index ) + ( 1.0 + parameter ) / ( 1.0 + length ) * differenceVector[ index ] );
      }

      tempLabel = m_Segmentation->GetPixelValueByIndex( tempIndex );

      if( !IsBackgroundLabel( tempLabel ) )
      {
        label = tempLabel;
        mitkIndex = tempIndex;
        return;
      }
      // hit next point without finding brain matter
      currentRetractionIndex = currentRetractionIndex + retractionStepIndexSize;
      if( ( currentRetractionIndex < 1 ) || ( currentRetractionIndex > ( singleTract->Size() - 2 ) ) )
      {
        keepRetracting = false;
      }
    }
  }
}