// Copyright (c) 2018, The Remix Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
//    conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
//    of conditions and the following disclaimer in the documentation and/or other
//    materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
//    used to endorse or promote products derived from this software without specific
//    prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers

#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <vector>

#include "common/int-util.h"
#include "crypto/hash.h"
#include "cryptonote_config.h"
#include "difficulty.h"
#include <boost/math/special_functions/round.hpp>

#undef REMIX_DEFAULT_LOG_CATEGORY
#define REMIX_DEFAULT_LOG_CATEGORY "difficulty"

namespace cryptonote {

  using std::size_t;
  using std::uint64_t;
  using std::vector;

#if defined(__x86_64__)
  static inline void mul(uint64_t a, uint64_t b, uint64_t &low, uint64_t &high) {
    low = mul128(a, b, &high);
  }

#else

  static inline void mul(uint64_t a, uint64_t b, uint64_t &low, uint64_t &high) {
    // __int128 isn't part of the standard, so the previous function wasn't portable. mul128() in Windows is fine,
    // but this portable function should be used elsewhere. Credit for this function goes to latexi95.

    uint64_t aLow = a & 0xFFFFFFFF;
    uint64_t aHigh = a >> 32;
    uint64_t bLow = b & 0xFFFFFFFF;
    uint64_t bHigh = b >> 32;

    uint64_t res = aLow * bLow;
    uint64_t lowRes1 = res & 0xFFFFFFFF;
    uint64_t carry = res >> 32;

    res = aHigh * bLow + carry;
    uint64_t highResHigh1 = res >> 32;
    uint64_t highResLow1 = res & 0xFFFFFFFF;

    res = aLow * bHigh;
    uint64_t lowRes2 = res & 0xFFFFFFFF;
    carry = res >> 32;

    res = aHigh * bHigh + carry;
    uint64_t highResHigh2 = res >> 32;
    uint64_t highResLow2 = res & 0xFFFFFFFF;

    //Addition

    uint64_t r = highResLow1 + lowRes2;
    carry = r >> 32;
    low = (r << 32) | lowRes1;
    r = highResHigh1 + highResLow2 + carry;
    uint64_t d3 = r & 0xFFFFFFFF;
    carry = r >> 32;
    r = highResHigh2 + carry;
    high = d3 | (r << 32);
  }

#endif

  static inline bool cadd(uint64_t a, uint64_t b) {
    return a + b < a;
  }

  static inline bool cadc(uint64_t a, uint64_t b, bool c) {
    return a + b < a || (c && a + b == (uint64_t) -1);
  }

  bool check_hash(const crypto::hash &hash, difficulty_type difficulty) {
    uint64_t low, high, top, cur;
    // First check the highest word, this will most likely fail for a random hash.
    mul(swap64le(((const uint64_t *) &hash)[3]), difficulty, top, high);
    if (high != 0) {
      return false;
    }
    mul(swap64le(((const uint64_t *) &hash)[0]), difficulty, low, cur);
    mul(swap64le(((const uint64_t *) &hash)[1]), difficulty, low, high);
    bool carry = cadd(cur, low);
    cur = high;
    mul(swap64le(((const uint64_t *) &hash)[2]), difficulty, low, high);
    carry = cadc(cur, low, carry);
    carry = cadc(high, top, carry);
    return !carry;
  }

  difficulty_type next_difficulty(std::vector<std::uint64_t> timestamps, std::vector<difficulty_type> cumulative_difficulties, size_t target_seconds) {

    const int64_t T = static_cast<int64_t>(target_seconds);
    size_t N = DIFFICULTY_WINDOW;
    int64_t FTL = static_cast<int64_t>(CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT);

    // Return a difficulty of 1 for first 3 blocks if it's the start of the chain.
    if (timestamps.size() < 4) {
      return 1;
    }
    // Otherwise, use a smaller N if the start of the chain is less than N+1.
    else if ( timestamps.size() < N+1 ) {
      N = timestamps.size() - 1;
    }
    // Otherwise make sure timestamps and cumulative_difficulties are correct size.
    else {
      timestamps.resize(N+1);
      cumulative_difficulties.resize(N+1);
    }
    // To get an average solvetime to within +/- ~0.1%, use an adjustment factor.
    // adjust=0.998 for N = 60
    const double adjust = 0.998;
    // The divisor k normalizes the LWMA sum to a standard LWMA.
    const double k = N * (N + 1) / 2;

    double LWMA(0), sum_inverse_D(0), harmonic_mean_D(0), nextDifficulty(0);
    int64_t solveTime(0);
    uint64_t difficulty(0), next_difficulty(0);

    // Loop through N most recent blocks. N is most recently solved block.
    for (size_t i = 1; i <= N; i++) {
      solveTime = static_cast<int64_t>(timestamps[i]) - static_cast<int64_t>(timestamps[i - 1]);
      solveTime = std::min<int64_t>((T * 10), std::max<int64_t>(solveTime, -FTL));
      difficulty = cumulative_difficulties[i] - cumulative_difficulties[i - 1];
      LWMA += (int64_t)(solveTime * i) / k;
      sum_inverse_D += 1 / static_cast<double>(difficulty);
    }

    harmonic_mean_D = N / sum_inverse_D;

    // Limit LWMA same as Bitcoin's 1/4 in case something unforeseen occurs.
    if (static_cast<int64_t>(boost::math::round(LWMA)) < T / 4)
      LWMA = static_cast<double>(T / 4);

    nextDifficulty = harmonic_mean_D * T / LWMA * adjust;

    // No limits should be employed, but this is correct way to employ a 20% symmetrical limit:
    // nextDifficulty=max(previous_Difficulty*0.8,min(previous_Difficulty/0.8, next_Difficulty));
    next_difficulty = static_cast<uint64_t>(nextDifficulty);
    return next_difficulty;
  }

  // LWMA-2 difficulty algorithm (commented version)
  // Copyright (c) 2017-2018 Zawy
  // https://github.com/zawy12/difficulty-algorithms/issues/3
  // Bitcoin clones must lower their FTL.
  // Cryptonote et al coins must make the following changes:
  // #define BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW    11
  // #define CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT        3 * DIFFICULTY_TARGET
  // #define DIFFICULTY_WINDOW                      60 + 1
  // Do not sort timestamps.  CN coins must deploy the Jagerman MTP Patch. See:
  // https://github.com/loki-project/loki/pull/26   or
  // https://github.com/wownero/wownero/commit/1f6760533fcec0d84a6bd68369e0ea26716b01e7

  // New coins:  "return 100;" should have the 100 changed based on expected hashrate.

  difficulty_type next_difficulty_v2(std::vector<std::uint64_t> timestamps, std::vector<difficulty_type> cumulative_difficulties, size_t target_seconds, size_t height) {

    double T = DIFFICULTY_TARGET; // target solvetime seconds
    double N = DIFFICULTY_WINDOW - 1; //  N=45, 60, and 90 for T=600, 120, 60.
    double FTL = CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT; // < 3xT
    double L(0), sum_6_ST(0), sum_9_ST(0), ST, next_D, prev_D, SMAn, SMAd;

    // If expecting a 10x decrease or 1000x increase in D after a fork, consider:
    // if ( height >= fork_height && height < fork_height+62 )  { return uint64_t difficulty_guess; }

    // TS and CD vectors should be size 61 after startup.
    if ( timestamps.size() > N  ) { timestamps.resize(N+1); cumulative_difficulties.resize(N+1);  }
    else if (timestamps.size() < 4)  {  return 100;  } // start up
    else  {  N = timestamps.size() - 1;  } // start up

    // N is most recently solved block. i must be signed
    for ( int64_t i = 1; i <= N; i++) {
        // +/- FTL limits are bad timestamp protection.  6xT limits drop in D to reduce oscillations.
        ST = std::max(-FTL, std::min(double(timestamps[i] - timestamps[i-1]), 6*T));
        L +=  ST * i ; // Give more weight to most recent blocks.
        // Do these inside loop to capture -FTL and +6*T limitations.
        if ( i > N-6 ) { sum_6_ST += ST; }
        if ( i > N-9 ) { sum_9_ST += ST; }
    }
    if (L < T*N) { L= T*N*6; } // sanity limit. Accidentally limits D rise at startup for ~60 blocks.

    // Calculate next_D = avgD * T / LWMA(STs)
    next_D = (cumulative_difficulties[N] - cumulative_difficulties[0]) * T*(N+1)*0.991 / (L*2);

    // LWMA-2 change from LWMA
    // Trigger sudden increase in D if hash attack is detected. Also limit rate of fall in D.
    // ====  begin LWMA-2 trigger and fall limitations  ====

    prev_D = cumulative_difficulties[N] - cumulative_difficulties[N-1];

    // Use Digishield-type tempered SMA to get long-term (~4*N) avg D to limit how high
    // consecutive triggers can send D.
    SMAn = (cumulative_difficulties[N] - cumulative_difficulties[0]) * 4 *T;
    SMAd = 3*N + double( timestamps[N] - timestamps[0] );

    // If a trigger would send D>1.7*avgD, then don't do it.
    // 1.70 allows 30% increase for 2 consecutive blocks and 14% for 4 blocks.
    // Tempered SMA = SMAn / SMAd, but do not divide for round off protection

    if  ( 1.14*next_D*SMAd > 1.70*SMAn ) {
        if ( next_D < 0.7*prev_D ) { next_D = 0.7*prev_D; }
    }
    else if  ( 1.3*next_D*SMAd < 1.70*SMAn && sum_6_ST < 1.2*T )   {
        next_D = 1.3*prev_D;
    }
    else if (sum_9_ST < 3.4*T )   {  next_D = 1.14*prev_D;  }
    // Prevent D falling too much after triggers, as long as D is not > 1.7*avgD
    else if  ( next_D < 0.9*prev_D )  { next_D = 0.9*prev_D;  }

    // ==== end LWMA-2's trigger and fall limitations ====

    // Prevent round off difference between systems to prevent chain split.
    // Theoretically not needed by C++ standard.  Requires D > 1. Needs 1E12 > D > 100.

    if  ( ceil(next_D + 0.01) > ceil(next_D) ) { next_D = ceil(next_D + 0.03);  }

    // next_Target = sumTargets*L*2/0.998/T/(N+1)/N/N; // To show the difference.

    return static_cast<uint64_t>(next_D);

  }
}


/*

Copyright (c) 2005-2015, University of Oxford.
All rights reserved.

University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.

This file is part of Chaste.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
 * Neither the name of the University of Oxford nor the names of its
   contributors may be used to endorse or promote products derived from this
   software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#include "PottsMeshGenerator.hpp"

#include <boost/scoped_array.hpp>

template<unsigned DIM>
PottsMeshGenerator<DIM>::PottsMeshGenerator(unsigned numNodesAcross, unsigned numElementsAcross, unsigned elementWidth,
                                            unsigned numNodesUp, unsigned numElementsUp, unsigned elementHeight,
                                            unsigned numNodesDeep, unsigned numElementsDeep, unsigned elementDepth,
                                            bool startAtBottomLeft, bool isPeriodicInX, bool isPeriodicInY ,bool isPeriodicInZ)
{
    assert(numNodesAcross > 0);
    assert(numNodesUp > 0);
    assert(numNodesDeep > 0);

    assert(numElementsAcross*elementWidth <= numNodesAcross);
    assert(numElementsUp*elementHeight <= numNodesUp);
    assert(numElementsDeep*elementDepth <= numNodesDeep);

    std::vector<Node<DIM>*> nodes;
    std::vector<PottsElement<DIM>*>  elements;
    std::vector<std::set<unsigned> > moore_neighbours;
    std::vector<std::set<unsigned> > von_neumann_neighbours;

    unsigned num_nodes = numNodesAcross*numNodesUp*numNodesDeep;

    unsigned next_node_index = 0;
    boost::scoped_array<unsigned> node_indices(new unsigned[elementWidth*elementHeight*elementDepth]);
    unsigned element_index;

    unsigned index_offset = 0;

    if (!startAtBottomLeft) // Elements in centre of mesh
    {
        // Calculate the width of the medium on the edge and offset the node index so that the elements are in the centre of the mesh.
        unsigned across_gap = (numNodesAcross -  numElementsAcross*elementWidth)/2;
        unsigned up_gap = (numNodesUp -  numElementsUp*elementHeight)/2;
        unsigned deep_gap = (numNodesDeep -  numElementsDeep*elementDepth)/2;

        index_offset = deep_gap*numNodesAcross*numNodesUp + up_gap*numNodesAcross + across_gap;
    }

    /*
     * Create the nodes, row by row, from the bottom up
     * On the first and last row we have numNodesAcross nodes, all of which are boundary
     * nodes. On each interior row we have numNodesAcross nodes, the first and last nodes
     * are boundary nodes.
     */
    for (unsigned k=0; k<numNodesDeep; k++)
    {
        for (unsigned j=0; j<numNodesUp; j++)
        {
            for (unsigned i=0; i<numNodesAcross; i++)
            {
                bool is_boundary_node=false;
                if (DIM==2)
                {
                    is_boundary_node = (j==0 || j==numNodesUp-1 || (i==0 && !isPeriodicInX) || (i==numNodesAcross-1 && !isPeriodicInX) ) ? true : false;
                }
                if (DIM==3)
                {
                    is_boundary_node = (j==0 || j==numNodesUp-1 || (i==0 && !isPeriodicInX) || (i==numNodesAcross-1 && !isPeriodicInX) || k==0 || k==numNodesDeep-1) ? true : false;
                }
                Node<DIM>* p_node = new Node<DIM>(next_node_index, is_boundary_node, i, j, k);
                nodes.push_back(p_node);
                next_node_index++;
            }
        }
    }
    assert(nodes.size()==num_nodes);

    /*
     * Create the elements. The array node_indices contains the
     * global node indices, in increasing order.
     */
    for (unsigned n=0; n<numElementsDeep; n++)
    {
        for (unsigned j=0; j<numElementsUp; j++)
        {
            for (unsigned i=0; i<numElementsAcross; i++)
            {
                for (unsigned m=0; m<elementDepth; m++)
                {
                    for (unsigned l=0; l<elementHeight; l++)
                    {
                        for (unsigned k=0; k<elementWidth; k++)
                        {
                            node_indices[m*elementHeight*elementWidth + l*elementWidth + k] = n*elementDepth*numNodesUp*numNodesAcross +
                                                                                j*elementHeight*numNodesAcross +
                                                                                i*elementWidth +
                                                                                m*numNodesAcross*numNodesUp +
                                                                                l*numNodesAcross +
                                                                                k + index_offset;
                        }
                    }
                }
                std::vector<Node<DIM>*> element_nodes;
                for (unsigned k=0; k<elementDepth*elementHeight*elementWidth; k++)
                {
                   element_nodes.push_back(nodes[node_indices[k]]);
                }

                element_index = n*numElementsAcross*numElementsUp + j*numElementsAcross + i;
                PottsElement<DIM>* p_element = new PottsElement<DIM>(element_index, element_nodes);
                elements.push_back(p_element);
            }
        }
    }

    /*
     * Create the neighborhoods of each node
     */

    moore_neighbours.resize(num_nodes);
    von_neumann_neighbours.resize(num_nodes);

    for (unsigned node_index=0; node_index<num_nodes; node_index++)
    {
        // Clear the set of neighbouring node indices

        moore_neighbours[node_index].clear();

        switch (DIM)
        {
            case 2:
            {
                assert(DIM == 2);
                /*
                 * This stores the available neighbours using the following numbering:
                 *
                 *  1-----0-----7
                 *  |     |     |
                 *  |     |     |
                 *  2-----x-----6
                 *  |     |     |
                 *  |     |     |
                 *  3-----4-----5
                 */

                // Create a vector of possible neighbouring node indices
                std::vector<unsigned> moore_neighbour_indices_vector(8, node_index);
                moore_neighbour_indices_vector[0] += numNodesAcross;
                moore_neighbour_indices_vector[1] += numNodesAcross - 1;
                moore_neighbour_indices_vector[2] -= 1;
                moore_neighbour_indices_vector[3] -= numNodesAcross + 1;
                moore_neighbour_indices_vector[4] -= numNodesAcross;
                moore_neighbour_indices_vector[5] -= numNodesAcross - 1;
                moore_neighbour_indices_vector[6] += 1;
                moore_neighbour_indices_vector[7] += numNodesAcross + 1;

                // Work out whether this node lies on any edge of the mesh
                bool on_south_edge = (node_index < numNodesAcross);
                bool on_north_edge = ((int) node_index > (int)numNodesAcross*((int)numNodesUp - 1) - 1);
                bool on_west_edge = (node_index%numNodesAcross == 0);
                bool on_east_edge = (node_index%numNodesAcross == numNodesAcross - 1);

                if (isPeriodicInX)
                {
                    if (on_west_edge)
                    {
                        moore_neighbour_indices_vector[1] = node_index + 2*numNodesAcross - 1;
                        moore_neighbour_indices_vector[2] = node_index + numNodesAcross - 1;
                        moore_neighbour_indices_vector[3] = node_index - 1;
                    }

                    if (on_east_edge)
                    {
                        moore_neighbour_indices_vector[5] = node_index - 2*numNodesAcross + 1;
                        moore_neighbour_indices_vector[6] = node_index - numNodesAcross + 1;
                        moore_neighbour_indices_vector[7] = node_index + 1;
                    }
                }

                if (isPeriodicInY)
                {
                    if (on_north_edge)
                    {
                        moore_neighbour_indices_vector[0] = node_index - numNodesAcross*(numNodesUp-1);
                        moore_neighbour_indices_vector[1] = moore_neighbour_indices_vector[0] - 1;
                        moore_neighbour_indices_vector[7] = moore_neighbour_indices_vector[0] + 1;

                        if (on_west_edge)
                        {
                            moore_neighbour_indices_vector[1] = moore_neighbour_indices_vector[1] + numNodesAcross;
                        }
                        if (on_east_edge)
                        {
                            moore_neighbour_indices_vector[7] = moore_neighbour_indices_vector[7] - numNodesAcross;
                        }
                    }

                    if (on_south_edge)
                    {
                        moore_neighbour_indices_vector[4] = node_index + numNodesAcross*(numNodesUp-1);
                        moore_neighbour_indices_vector[3] = moore_neighbour_indices_vector[4] - 1;
                        moore_neighbour_indices_vector[5] = moore_neighbour_indices_vector[4] + 1;

                        if (on_west_edge)
                        {
                            moore_neighbour_indices_vector[3] = moore_neighbour_indices_vector[3] + numNodesAcross;
                        }
                        if (on_east_edge)
                        {
                            moore_neighbour_indices_vector[5] = moore_neighbour_indices_vector[5] - numNodesAcross;
                        }
                    }
                }

                if (isPeriodicInX)
                {
                    on_east_edge = false;
                    on_west_edge = false;
                }
                if (isPeriodicInY)
                {
                    on_south_edge = false;
                    on_north_edge = false;
                }

                // Create a vector of booleans for which neighbours are available
                // Use the order N, NW, W, SW, S, SE, E, NE
                std::vector<bool> available_neighbours = std::vector<bool>(8, true);
                available_neighbours[0] = !on_north_edge;
                available_neighbours[1] = !(on_north_edge || on_west_edge);
                available_neighbours[2] = !on_west_edge;
                available_neighbours[3] = !(on_south_edge || on_west_edge);
                available_neighbours[4] = !on_south_edge;
                available_neighbours[5] = !(on_south_edge || on_east_edge);
                available_neighbours[6] = !on_east_edge;
                available_neighbours[7] = !(on_north_edge || on_east_edge);

                // Using neighbour_indices_vector and available_neighbours, store the indices of all available neighbours to the set all_neighbours
                for (unsigned i=0; i<8; i++)
                {
                    if (available_neighbours[i])
                    {
                        assert(moore_neighbour_indices_vector[i] < nodes.size());
                        moore_neighbours[node_index].insert(moore_neighbour_indices_vector[i]);
                    }
                }
                break;
            }
            case 3:
            {
                assert(DIM ==3);
                /*
                 * This stores the available neighbours using the following numbering:
                 *                      FRONT           BACK
                 *  1-----0-----7   10-----9---16   19----18---25
                 *  |     |     |   |     |     |   |     |     |
                 *  |     |     |   |     |     |   |     |     |
                 *  2-----x-----6   11----8-----15  20----17---24
                 *  |     |     |   |     |     |   |     |     |
                 *  |     |     |   |     |     |   |     |     |
                 *  3-----4-----5   12----13----14  21---22----23
                 */

                // Create a vector of possible neighbouring node indices
                std::vector<unsigned> moore_neighbour_indices_vector(26, node_index);
                moore_neighbour_indices_vector[0] += numNodesAcross;
                moore_neighbour_indices_vector[1] += numNodesAcross - 1;
                moore_neighbour_indices_vector[2] -= 1;
                moore_neighbour_indices_vector[3] -= numNodesAcross + 1;
                moore_neighbour_indices_vector[4] -= numNodesAcross;
                moore_neighbour_indices_vector[5] -= numNodesAcross - 1;
                moore_neighbour_indices_vector[6] += 1;
                moore_neighbour_indices_vector[7] += numNodesAcross + 1;
                moore_neighbour_indices_vector[8] -= numNodesAcross*numNodesUp;
                for (unsigned i=9; i<17; i++)
                {
                    moore_neighbour_indices_vector[i] = moore_neighbour_indices_vector[i-9]-numNodesAcross*numNodesUp;
                }
                moore_neighbour_indices_vector[17] += numNodesAcross*numNodesUp;
                for (unsigned i=18; i<26; i++)
                {
                    moore_neighbour_indices_vector[i]=moore_neighbour_indices_vector[i-18]+numNodesAcross*numNodesUp;
                }

                // Work out whether this node lies on any edge of the mesh
                bool on_south_edge = (node_index%(numNodesAcross*numNodesUp)<numNodesAcross);
                bool on_north_edge = (node_index%(numNodesAcross*numNodesUp)>(numNodesAcross*numNodesUp-numNodesAcross-1));
                bool on_west_edge = (node_index%numNodesAcross == 0);
                bool on_east_edge = (node_index%numNodesAcross == numNodesAcross - 1);
                bool on_front_edge = (node_index < numNodesAcross*numNodesUp);
                bool on_back_edge = (node_index > numNodesAcross*numNodesUp*(numNodesDeep-1)-1);

                if (isPeriodicInX)
                {
                    if (on_west_edge)
                    {
                        moore_neighbour_indices_vector[1] = node_index + 2*numNodesAcross - 1;
                        moore_neighbour_indices_vector[2] = node_index + numNodesAcross - 1;
                        moore_neighbour_indices_vector[3] = node_index - 1;

                        moore_neighbour_indices_vector[10] = moore_neighbour_indices_vector[1] - numNodesAcross*numNodesUp;
                        moore_neighbour_indices_vector[11] = moore_neighbour_indices_vector[2] - numNodesAcross*numNodesUp;
                        moore_neighbour_indices_vector[12] = moore_neighbour_indices_vector[3] - numNodesAcross*numNodesUp;

                        moore_neighbour_indices_vector[19] = moore_neighbour_indices_vector[1] + numNodesAcross*numNodesUp;
                        moore_neighbour_indices_vector[20] = moore_neighbour_indices_vector[2] + numNodesAcross*numNodesUp;
                        moore_neighbour_indices_vector[21] = moore_neighbour_indices_vector[3] + numNodesAcross*numNodesUp;
                    }

                    if (on_east_edge)
                    {
                        moore_neighbour_indices_vector[5] = node_index - 2*numNodesAcross + 1;
                        moore_neighbour_indices_vector[6] = node_index - numNodesAcross + 1;
                        moore_neighbour_indices_vector[7] = node_index + 1;

                        moore_neighbour_indices_vector[14] = moore_neighbour_indices_vector[5] - numNodesAcross*numNodesUp;
                        moore_neighbour_indices_vector[15] = moore_neighbour_indices_vector[6] - numNodesAcross*numNodesUp;
                        moore_neighbour_indices_vector[16] = moore_neighbour_indices_vector[7] - numNodesAcross*numNodesUp;

                        moore_neighbour_indices_vector[23] = moore_neighbour_indices_vector[5] + numNodesAcross*numNodesUp;
                        moore_neighbour_indices_vector[24] = moore_neighbour_indices_vector[6] + numNodesAcross*numNodesUp;
                        moore_neighbour_indices_vector[25] = moore_neighbour_indices_vector[7] + numNodesAcross*numNodesUp;
                    }
                }

                if (isPeriodicInY)
                {
                    if (on_north_edge)
                    {
                        moore_neighbour_indices_vector[0] = node_index - numNodesAcross*(numNodesUp-1);
                        moore_neighbour_indices_vector[1] = moore_neighbour_indices_vector[0] - 1;
                        moore_neighbour_indices_vector[7] = moore_neighbour_indices_vector[0] + 1;

                        moore_neighbour_indices_vector[10] = moore_neighbour_indices_vector[1] - numNodesAcross*numNodesUp;
                        moore_neighbour_indices_vector[9] = moore_neighbour_indices_vector[0] - numNodesAcross*numNodesUp;
                        moore_neighbour_indices_vector[16] = moore_neighbour_indices_vector[7] - numNodesAcross*numNodesUp;

                        moore_neighbour_indices_vector[19] = moore_neighbour_indices_vector[1] + numNodesAcross*numNodesUp;
                        moore_neighbour_indices_vector[18] = moore_neighbour_indices_vector[0] + numNodesAcross*numNodesUp;
                        moore_neighbour_indices_vector[25] = moore_neighbour_indices_vector[7] + numNodesAcross*numNodesUp;

                        if (on_west_edge)
                        {
                            moore_neighbour_indices_vector[1] = moore_neighbour_indices_vector[1] + numNodesAcross;
                            moore_neighbour_indices_vector[10] = moore_neighbour_indices_vector[10] + numNodesAcross;
                            moore_neighbour_indices_vector[19] = moore_neighbour_indices_vector[19] + numNodesAcross;
                        }
                        if (on_east_edge)
                        {
                            moore_neighbour_indices_vector[7] = moore_neighbour_indices_vector[7] - numNodesAcross;
                            moore_neighbour_indices_vector[16] = moore_neighbour_indices_vector[16] - numNodesAcross;
                            moore_neighbour_indices_vector[25] = moore_neighbour_indices_vector[25] - numNodesAcross;
                        }
                    }

                    if (on_south_edge)
                    {
                        moore_neighbour_indices_vector[4] = node_index + numNodesAcross*(numNodesUp-1);
                        moore_neighbour_indices_vector[3] = moore_neighbour_indices_vector[4] - 1;
                        moore_neighbour_indices_vector[5] = moore_neighbour_indices_vector[4] + 1;

                        moore_neighbour_indices_vector[12] = moore_neighbour_indices_vector[3] - numNodesAcross*numNodesUp;
                        moore_neighbour_indices_vector[13] = moore_neighbour_indices_vector[4] - numNodesAcross*numNodesUp;
                        moore_neighbour_indices_vector[14] = moore_neighbour_indices_vector[5] - numNodesAcross*numNodesUp;

                        moore_neighbour_indices_vector[21] = moore_neighbour_indices_vector[3] + numNodesAcross*numNodesUp;
                        moore_neighbour_indices_vector[22] = moore_neighbour_indices_vector[4] + numNodesAcross*numNodesUp;
                        moore_neighbour_indices_vector[23] = moore_neighbour_indices_vector[5] + numNodesAcross*numNodesUp;

                        if (on_west_edge)
                        {
                            moore_neighbour_indices_vector[3] = moore_neighbour_indices_vector[3] + numNodesAcross;
                            moore_neighbour_indices_vector[12] = moore_neighbour_indices_vector[12] + numNodesAcross;
                            moore_neighbour_indices_vector[21] = moore_neighbour_indices_vector[21] + numNodesAcross;
                        }
                        if (on_east_edge)
                        {
                            moore_neighbour_indices_vector[5] = moore_neighbour_indices_vector[5] - numNodesAcross;
                            moore_neighbour_indices_vector[14] = moore_neighbour_indices_vector[14] - numNodesAcross;
                            moore_neighbour_indices_vector[23] = moore_neighbour_indices_vector[23] - numNodesAcross;
                        }
                    }
                }

                if (isPeriodicInZ)
                {
                    if (on_back_edge)
                    {
                        moore_neighbour_indices_vector[17] = node_index - numNodesAcross*numNodesUp*(numNodesDeep-1);
                        moore_neighbour_indices_vector[20] = moore_neighbour_indices_vector[17] - 1;
                        moore_neighbour_indices_vector[24] = moore_neighbour_indices_vector[17] + 1;

                        moore_neighbour_indices_vector[21] = moore_neighbour_indices_vector[20] - numNodesAcross;
                        moore_neighbour_indices_vector[22] = moore_neighbour_indices_vector[17] - numNodesAcross;
                        moore_neighbour_indices_vector[23] = moore_neighbour_indices_vector[24] - numNodesAcross;

                        moore_neighbour_indices_vector[19] = moore_neighbour_indices_vector[20] + numNodesAcross;
                        moore_neighbour_indices_vector[18] = moore_neighbour_indices_vector[17] + numNodesAcross;
                        moore_neighbour_indices_vector[25] = moore_neighbour_indices_vector[24] + numNodesAcross;

                        if (on_west_edge)
                        {
                            moore_neighbour_indices_vector[19] = moore_neighbour_indices_vector[19] + numNodesAcross;
                            moore_neighbour_indices_vector[20] = moore_neighbour_indices_vector[20] + numNodesAcross;
                            moore_neighbour_indices_vector[21] = moore_neighbour_indices_vector[21] + numNodesAcross;
                        }
                        if (on_east_edge)
                        {
                            moore_neighbour_indices_vector[23] = moore_neighbour_indices_vector[23] - numNodesAcross;
                            moore_neighbour_indices_vector[24] = moore_neighbour_indices_vector[24] - numNodesAcross;
                            moore_neighbour_indices_vector[25] = moore_neighbour_indices_vector[25] - numNodesAcross;
                        }

                        if (on_south_edge)
                        {
                            moore_neighbour_indices_vector[21] = moore_neighbour_indices_vector[21] + numNodesAcross*numNodesUp;
                            moore_neighbour_indices_vector[22] = moore_neighbour_indices_vector[22] + numNodesAcross*numNodesUp;
                            moore_neighbour_indices_vector[23] = moore_neighbour_indices_vector[23] + numNodesAcross*numNodesUp;
                        }

                        if (on_north_edge)
                        {
                            moore_neighbour_indices_vector[18] = moore_neighbour_indices_vector[18] - numNodesAcross*numNodesUp;
                            moore_neighbour_indices_vector[19] = moore_neighbour_indices_vector[19] - numNodesAcross*numNodesUp;
                            moore_neighbour_indices_vector[25] = moore_neighbour_indices_vector[25] - numNodesAcross*numNodesUp;
                        }
                    }

                    if (on_front_edge)
                    {
                        moore_neighbour_indices_vector[8] = node_index + numNodesAcross*numNodesUp*(numNodesDeep-1);
                        moore_neighbour_indices_vector[11] = moore_neighbour_indices_vector[8] - 1;
                        moore_neighbour_indices_vector[15] = moore_neighbour_indices_vector[8] + 1;

                        moore_neighbour_indices_vector[12] = moore_neighbour_indices_vector[11] - numNodesAcross;
                        moore_neighbour_indices_vector[13] = moore_neighbour_indices_vector[8] - numNodesAcross;
                        moore_neighbour_indices_vector[14] = moore_neighbour_indices_vector[15] - numNodesAcross;

                        moore_neighbour_indices_vector[10] = moore_neighbour_indices_vector[11] + numNodesAcross;
                        moore_neighbour_indices_vector[9] = moore_neighbour_indices_vector[8] + numNodesAcross;
                        moore_neighbour_indices_vector[16] = moore_neighbour_indices_vector[15] + numNodesAcross;

                        if (on_west_edge)
                        {
                            moore_neighbour_indices_vector[10] = moore_neighbour_indices_vector[10] + numNodesAcross;
                            moore_neighbour_indices_vector[11] = moore_neighbour_indices_vector[11] + numNodesAcross;
                            moore_neighbour_indices_vector[12] = moore_neighbour_indices_vector[12] + numNodesAcross;
                        }
                        if (on_east_edge)
                        {
                            moore_neighbour_indices_vector[14] = moore_neighbour_indices_vector[14] - numNodesAcross;
                            moore_neighbour_indices_vector[15] = moore_neighbour_indices_vector[15] - numNodesAcross;
                            moore_neighbour_indices_vector[16] = moore_neighbour_indices_vector[16] - numNodesAcross;
                        }

                        if (on_south_edge)
                        {
                            moore_neighbour_indices_vector[12] = moore_neighbour_indices_vector[12] + numNodesAcross*numNodesUp;
                            moore_neighbour_indices_vector[13] = moore_neighbour_indices_vector[13] + numNodesAcross*numNodesUp;
                            moore_neighbour_indices_vector[14] = moore_neighbour_indices_vector[14] + numNodesAcross*numNodesUp;
                        }

                        if (on_north_edge)
                        {
                            moore_neighbour_indices_vector[9] = moore_neighbour_indices_vector[9] - numNodesAcross*numNodesUp;
                            moore_neighbour_indices_vector[10] = moore_neighbour_indices_vector[10] - numNodesAcross*numNodesUp;
                            moore_neighbour_indices_vector[16] = moore_neighbour_indices_vector[16] - numNodesAcross*numNodesUp;
                        }
                    }
                }

                if (isPeriodicInX)
                {
                    on_east_edge = false;
                    on_west_edge = false;
                }
                if (isPeriodicInY)
                {
                    on_south_edge = false;
                    on_north_edge = false;
                }
                if (isPeriodicInZ)
                {
                    on_front_edge = false;
                    on_back_edge = false;
                }

                // Create a vector of booleans for which neighbours are available
                // Use the order N, NW, W, SW, S, SE, E, NE
                std::vector<bool> available_neighbours = std::vector<bool>(26, true);
                available_neighbours[0] = !on_north_edge;
                available_neighbours[1] = !(on_north_edge || on_west_edge);
                available_neighbours[2] = !on_west_edge;
                available_neighbours[3] = !(on_south_edge || on_west_edge);
                available_neighbours[4] = !on_south_edge;
                available_neighbours[5] = !(on_south_edge || on_east_edge);
                available_neighbours[6] = !on_east_edge;
                available_neighbours[7] = !(on_north_edge || on_east_edge);
                available_neighbours[8] = !(on_front_edge);
                for (unsigned i=9; i<17; i++)
                {
                    available_neighbours[i] = (available_neighbours[i-9] && !(on_front_edge));
                }
                available_neighbours[17] = !(on_back_edge);
                for (unsigned i=18; i<26; i++)
                {
                    available_neighbours[i] = (available_neighbours[i-18] && !(on_back_edge));
                }

                // Using neighbour_indices_vector and available_neighbours, store the indices of all available neighbours to the set all_neighbours
                for (unsigned i=0; i<26; i++)
                {
                    if (available_neighbours[i] && moore_neighbour_indices_vector[i] < numNodesAcross*numNodesUp*numNodesDeep)
                    {
                        assert(moore_neighbour_indices_vector[i] < nodes.size());
                        moore_neighbours[node_index].insert(moore_neighbour_indices_vector[i]);
                    }
                }
                break;
            }
            default:
                NEVER_REACHED;
        }

        // Clear the set of neighbouring node indices
        von_neumann_neighbours[node_index].clear();

        switch (DIM)
        {
            case 2:
            {
                assert(DIM == 2);
                /*
                 * This stores the available neighbours using the following numbering:
                 *
                 *        0
                 *        |
                 *        |
                 *  1-----x-----3
                 *        |
                 *        |
                 *        2
                 */
                // Create a vector of possible neighbouring node indices
                std::vector<unsigned> von_neumann_neighbour_indices_vector(4, node_index);
                von_neumann_neighbour_indices_vector[0] += numNodesAcross;
                von_neumann_neighbour_indices_vector[1] -= 1;
                von_neumann_neighbour_indices_vector[2] -= numNodesAcross;
                von_neumann_neighbour_indices_vector[3] += 1;

                // Work out whether this node lies on any edge of the mesh
                bool on_south_edge = (node_index < numNodesAcross);
                bool on_north_edge = ((int)node_index > (int)numNodesAcross*((int)numNodesUp - 1) - 1);
                bool on_west_edge = (node_index%numNodesAcross == 0);
                bool on_east_edge = (node_index%numNodesAcross == numNodesAcross - 1);

                if (isPeriodicInX)
                {
                    if (on_west_edge)
                    {
                        von_neumann_neighbour_indices_vector[1] = node_index + numNodesAcross - 1;
                        on_west_edge = false;
                    }

                    if (on_east_edge)
                    {
                        von_neumann_neighbour_indices_vector[3] = node_index - numNodesAcross + 1;
                        on_east_edge = false;
                    }
                }

                if (isPeriodicInY)
                {
                    if (on_north_edge)
                    {
                        von_neumann_neighbour_indices_vector[0] = node_index - numNodesAcross*(numNodesUp-1);
                        on_north_edge = false;
                    }

                    if (on_south_edge)
                    {
                        von_neumann_neighbour_indices_vector[2] = node_index + numNodesAcross*(numNodesUp-1);
                        on_south_edge = false;
                    }
                }

                // Create a vector of booleans for which neighbours are available
                // Use the order N, W, S, E
                std::vector<bool> available_neighbours = std::vector<bool>(2*DIM, true);
                available_neighbours[0] = !on_north_edge;
                available_neighbours[1] = !on_west_edge;
                available_neighbours[2] = !on_south_edge;
                available_neighbours[3] = !on_east_edge;

                // Using von_neumann_neighbour_indices_vector and available_neighbours, store the indices of all available neighbours to the set all_neighbours
                for (unsigned i=0; i<4; i++)
                {
                    if (available_neighbours[i])
                    {
                        assert(von_neumann_neighbour_indices_vector[i] < nodes.size());
                        von_neumann_neighbours[node_index].insert(von_neumann_neighbour_indices_vector[i]);
                    }
                }
                break;
            }
            case 3:
            {
                assert(DIM == 3);

                /*
                 * This stores the available neighbours using the following numbering:
                 *
                 *        0  5
                 *        | /
                 *        |/
                 *  1-----x-----3
                 *      / |
                 *     /  |
                 *    4   2
                 */
                // Create a vector of possible neighbouring node indices
                std::vector<unsigned> von_neumann_neighbour_indices_vector(6, node_index);
                von_neumann_neighbour_indices_vector[0] += numNodesAcross;
                von_neumann_neighbour_indices_vector[1] -= 1;
                von_neumann_neighbour_indices_vector[2] -= numNodesAcross;
                von_neumann_neighbour_indices_vector[3] += 1;
                von_neumann_neighbour_indices_vector[4] -= numNodesAcross*numNodesUp;
                von_neumann_neighbour_indices_vector[5] += numNodesAcross*numNodesUp;

                // Work out whether this node lies on any edge of the mesh
                bool on_south_edge = (node_index%(numNodesAcross*numNodesUp)<numNodesAcross);
                bool on_north_edge = (node_index%(numNodesAcross*numNodesUp)>(numNodesAcross*numNodesUp-numNodesAcross-1));
                bool on_west_edge = (node_index%numNodesAcross== 0);
                bool on_east_edge = (node_index%numNodesAcross == numNodesAcross - 1);
                bool on_front_edge = (node_index < numNodesAcross*numNodesUp);
                bool on_back_edge = (node_index > numNodesAcross*numNodesUp*(numNodesDeep-1)-1);

                if (isPeriodicInX)
                {
                    if (on_west_edge)
                    {
                        von_neumann_neighbour_indices_vector[1] = node_index + numNodesAcross - 1;
                        on_west_edge = false;
                    }

                    if (on_east_edge)
                    {
                        von_neumann_neighbour_indices_vector[3] = node_index - numNodesAcross + 1;
                        on_east_edge = false;
                    }
                }

                if (isPeriodicInY)
                {
                    if (on_north_edge)
                    {
                        von_neumann_neighbour_indices_vector[0] = node_index - numNodesAcross*(numNodesUp-1);
                        on_north_edge = false;
                    }

                    if (on_south_edge)
                    {
                        von_neumann_neighbour_indices_vector[2] = node_index + numNodesAcross*(numNodesUp-1);
                        on_south_edge = false;
                    }
                }

                if (isPeriodicInZ)
                {
                    if (on_front_edge)
                    {
                        von_neumann_neighbour_indices_vector[4] = node_index + numNodesAcross*numNodesUp*(numNodesDeep-1);
                        on_front_edge = false;
                    }

                    if (on_back_edge)
                    {
                        von_neumann_neighbour_indices_vector[5] = node_index - numNodesAcross*numNodesUp*(numNodesDeep-1);
                        on_back_edge = false;
                    }
                }

                // Create a vector of booleans for which neighbours are available
                // Use the order N, W, S, E, F, B
                std::vector<bool> available_neighbours = std::vector<bool>(2*DIM, true);
                available_neighbours[0] = !on_north_edge;
                available_neighbours[1] = !on_west_edge;
                available_neighbours[2] = !on_south_edge;
                available_neighbours[3] = !on_east_edge;
                available_neighbours[4] = !on_front_edge;
                available_neighbours[5] = !on_back_edge;

                // Using von_neumann_neighbour_indices_vector and available_neighbours, store the indices of all available neighbours to the set all_neighbours
                for (unsigned i=0; i<6; i++)
                {
                    if (available_neighbours[i] && von_neumann_neighbour_indices_vector[i]<numNodesAcross*numNodesUp*numNodesDeep)
                    {
                        assert(von_neumann_neighbour_indices_vector[i] < nodes.size());
                        von_neumann_neighbours[node_index].insert(von_neumann_neighbour_indices_vector[i]);
                    }
                }
                break;
            }
            default:
                NEVER_REACHED;
        }
    }

    mpMesh = new PottsMesh<DIM>(nodes, elements, von_neumann_neighbours, moore_neighbours);
}

template<unsigned DIM>
PottsMeshGenerator<DIM>::~PottsMeshGenerator()
{
    delete mpMesh;
}

template<unsigned DIM>
PottsMesh<DIM>* PottsMeshGenerator<DIM>::GetMesh()
{
    return mpMesh;
}

// Explicit instantiation
template class PottsMeshGenerator<1>;
template class PottsMeshGenerator<2>;
template class PottsMeshGenerator<3>;


#include "tkdCmdParser.h"

#include <algorithm>
#include <iterator>
#include <functional>
#include <numeric>

#include <boost/random/uniform_int.hpp>
#include <boost/random/uniform_real.hpp>
#include <boost/random/variate_generator.hpp>
#include <boost/random.hpp>
#include <boost/random/normal_distribution.hpp>

#include "itkImage.h"
#include "itkImageLinearIteratorWithIndex.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkExtractImageFilter.h"

#include "graphCommon.h"
#include "annCommon.h"
#include "annRelabel.h"

/**
 * Circular bootstrap.
 *
 * Neuroimage (2010) Pierre Bellec et al,
 * "Multi-level bootstrap analysis of stable cluster in resting-state fMRI".
 *
 * wim@invivonmr.uu.nl, 06-04-2010.
 *
 */
namespace bootstrap
{
	typedef float PixelType;

	typedef std::vector< unsigned int > VectorType;

	typedef itk::Image< PixelType, 3 > Image3DType;
	typedef itk::Image< PixelType, 4 > Image4DType;

	typedef itk::ImageRegionConstIteratorWithIndex< Image4DType > ConstIterator4DType;
	typedef itk::ImageRegionIteratorWithIndex< Image4DType > Iterator4DType;
	typedef itk::ExtractImageFilter< Image4DType, Image4DType > ExtractImageFilterType;
	typedef itk::ImageFileWriter< Image4DType > ImageFileWriterType;

	typedef boost::mt19937 random_number_type;
	typedef boost::uniform_int< int > int_distribution_type;
	typedef boost::variate_generator< random_number_type&, int_distribution_type > int_generator_type;

	// *******************************************************************************

	/**
	 * Option list.
	 */
	struct parameters
	{
		std::string inputFileName;
		std::string maskFileName;
		std::string outputFileName;
		int iterations;
    int clusters;
    int repeat;
  };

  // *******************************************************************************

  /**
   * Construct similarity matrix using circular block boostrapping.
   */
  class Bootstrap
  {

    private:

      Image4DType::Pointer m_Data;
      Image4DType::Pointer m_DoubleData;
      Image3DType::Pointer m_Mask;
      std::vector< Image4DType::Pointer > m_BootstrapContainer;

    public:

      /**
       * Run.
       */
      void Run( const parameters& list )
      {
        // [ 1 ] Read data ...
        Read4D( list.inputFileName );
        ReadMask( list.maskFileName );

        // [ 2 ] Get list of random blocksizes and random offsets ...
        random_number_type generator( time( 0 ) );

        // [ 3 ] Construct circular bootstrap 4D images ...
        FillBootstrapContainer( list.iterations, generator );

        // [ 4 ] DEBUG TODO Write all different 4D images to disk...
        typedef itk::ImageFileWriter< Image4DType > ImageFileWriterType;
        ImageFileWriterType::Pointer writer = ImageFileWriterType::New();

        for( unsigned int i = 0; i < m_BootstrapContainer.size(); i++ )
        {
          std::stringstream ss;
          ss << "test_" << i << ".nii.gz";

          writer->SetFileName( ss.str() );
          writer->SetInput( m_BootstrapContainer.at( i ) );
          writer->Update();
        }
      }

    private:

      /**
       * Fill bootstrap container.
       */
      void FillBootstrapContainer( unsigned int n, random_number_type& generator )
      {
        Image4DType::SizeType size = m_Data->GetLargestPossibleRegion().GetSize();
        unsigned int max = size[3];

        for ( unsigned int i = 0; i < n; i++ )
        {
          std::cout << "Bootstrap nr: " << i << std::endl;
          m_BootstrapContainer.push_back( GetBootstrapImage( generator, max ) );
        }
      }

      /**
       * Return bootstrapped 4D image.
       */
      Image4DType::Pointer GetBootstrapImage( random_number_type& generator, unsigned int max )
      {
        // get number of blocks, sufficient to occupy full 4D image ...
        VectorType blockSizes;
        VectorType offsets;

        while ( std::accumulate( blockSizes.begin(), blockSizes.end(), static_cast< unsigned int > ( 0 ) ) < max )
        {
          offsets.push_back( GetRandomNumber( generator, max ) );
          blockSizes.push_back( GetRandomNumber( generator, 3 * sqrt( max ) ) ); // TODO manual set?
        }

        std::vector< Image4DType::Pointer > blocks = GetBlocks( blockSizes, offsets );

        return MergeBlocks( blocks );
      }

      /**
       * Return circular blocks, taken from input images.
       */
      std::vector< Image4DType::Pointer > GetBlocks( const VectorType& blockSizes, const VectorType& offsets )
      {
        std::vector< Image4DType::Pointer > blocks;

        for ( unsigned int i = 0; i < blockSizes.size(); i++ )
        {
          unsigned int blockSize = blockSizes.at( i );
          unsigned int offset = offsets.at( i );

          ExtractImageFilterType::Pointer filter = ExtractImageFilterType::New();
          filter->SetInput( m_DoubleData );

          Image4DType::RegionType region = m_DoubleData->GetLargestPossibleRegion();
          Image4DType::SizeType size = region.GetSize();
          Image4DType::IndexType index = region.GetIndex();

          size[3] = blockSize;
          index[3] = offset;

          region.SetSize( size );
          region.SetIndex( index );

          filter->SetExtractionRegion( region );

          filter->Update();
          blocks.push_back( filter->GetOutput() );

          m_DoubleData->DisconnectPipeline();
        }
        return blocks;
      }

      /**
       * Merge blocks until size is equal to input 4D Image.
       */
      Image4DType::Pointer MergeBlocks( const std::vector< Image4DType::Pointer >& blocks )
      {
        Image4DType::Pointer image = Image4DType::New();

        image->SetRegions( m_DoubleData->GetLargestPossibleRegion() );
        image->SetOrigin( m_DoubleData->GetOrigin() );
        image->SetSpacing( m_DoubleData->GetSpacing() );

        image->Allocate();
        image->FillBuffer( 0 );

        typedef itk::ImageRegionConstIteratorWithIndex< Image4DType > ConstIterator4D;
        typedef itk::ImageRegionIteratorWithIndex< Image4DType > Iterator4D;

        Image4DType::IndexType index = m_DoubleData->GetLargestPossibleRegion().GetIndex();

        for ( unsigned int i = 0; i < blocks.size(); i++ )
        {
          Image4DType::RegionType region = blocks.at( i )->GetLargestPossibleRegion();
          Image4DType::SizeType size = region.GetSize();
          region.SetIndex( index );

          Iterator4D it4( image, region );
          it4.GoToBegin();

          ConstIterator4D it3( blocks.at( i ), blocks.at( i )->GetLargestPossibleRegion() );
          it3.GoToBegin();

          while ( !it3.IsAtEnd(), !it4.IsAtEnd() )
          {
            it4.Set( it3.Get() );
            ++it3;
            ++it4;
          }
          index[ 3 ] += size[ 3 ];
        }

        // Extract first block from image and return ...
        ExtractImageFilterType::Pointer filter = ExtractImageFilterType::New();
        filter->SetInput( image );

        Image4DType::RegionType cropRegion = image->GetLargestPossibleRegion();
        Image4DType::SizeType cropSize = cropRegion.GetSize();
        Image4DType::IndexType cropIndex = cropRegion.GetIndex();

        cropSize[3] = ( m_Data->GetLargestPossibleRegion().GetSize() )[ 3 ];
        cropIndex[3] = 0;

        cropRegion.SetSize( cropSize );
        cropRegion.SetIndex( cropIndex );

        filter->SetExtractionRegion( cropRegion );
        filter->Update();

        return filter->GetOutput();
      }

      /**
       * Return random number.
       */
      int GetRandomNumber( random_number_type& generator, unsigned int max )
      {
        // uniform distribution: 0 -> 4D image size ...
        int_distribution_type int_uni_dist( 0, max - 1 );
        int_generator_type int_distribution( generator, int_uni_dist );

        int value = int_distribution();
        while ( value < 2 )
          value = int_distribution();

        return value;
      }

      /**
       * Read 3D volume.
       */
      void ReadMask( const std::string& inputFileName )
      {
        if ( !inputFileName.empty() )
        {
          typedef itk::ImageFileReader< Image3DType > ReaderType;
          ReaderType::Pointer reader = ReaderType::New();
          reader->SetFileName( inputFileName );
          reader->Update();
          m_Mask = reader->GetOutput();
        } else
        {
          // use 4D input data as reference for full mask...
          Image4DType::SizeType size4D = m_Data->GetLargestPossibleRegion().GetSize();
          Image4DType::IndexType index4D = m_Data->GetLargestPossibleRegion().GetIndex();
          Image3DType::SizeType size3D;
          Image3DType::IndexType index3D;
          size3D[0] = size4D[0];
          size3D[1] = size4D[1];
          size3D[2] = size4D[2];
          index3D[0] = index4D[0];
          index3D[1] = index4D[1];
          index3D[2] = index4D[2];
          Image3DType::RegionType region3D;
          region3D.SetSize( size3D );
          region3D.SetIndex( index3D );
          m_Mask = Image3DType::New();
          m_Mask->SetRegions( region3D );
          m_Mask->Allocate();
          m_Mask->FillBuffer( 1 );
        }
      }

      /**
       * Read 4D data, and set double data object (for wrapping).
       */
      void Read4D( const std::string& inputFileName )
      {
        typedef itk::ImageFileReader< Image4DType > ReaderType;
        ReaderType::Pointer reader = ReaderType::New();
        reader->SetFileName( inputFileName );
        reader->Update();
        m_Data = reader->GetOutput();

        Image4DType::RegionType region = m_Data->GetLargestPossibleRegion();
        Image4DType::SizeType size = region.GetSize();
        size[3] *= 2;
        region.SetSize( size );

        m_DoubleData = Image4DType::New();
        m_DoubleData->SetRegions( region );
        m_DoubleData->SetSpacing( m_Data->GetSpacing() );
        m_DoubleData->SetOrigin( m_Data->GetOrigin() );
        m_DoubleData->Allocate();
        m_DoubleData->FillBuffer( 0 );

        ConstIterator4DType it( m_Data, m_Data->GetLargestPossibleRegion() );
        Iterator4DType nit( m_DoubleData, m_DoubleData->GetLargestPossibleRegion() );

        it.GoToBegin();
        nit.GoToBegin();

        // first round ...
        while( !nit.IsAtEnd(), !it.IsAtEnd() )
        {
          nit.Set( it.Get() );
          ++nit;
          ++it;
        }

        // second round ...
        it.GoToBegin();
        while( !nit.IsAtEnd(), !it.IsAtEnd() )
        {
          nit.Set( it.Get() );
          ++nit;
          ++it;
        }
      }
  };
} // end namespace bootstrap

/**
 * Main.
 */
int main( int argc, char ** argv )
{
  tkd::CmdParser p( argv[0], "Circular block boostrap." );

  bootstrap::parameters args;
  args.iterations = 10;

  p.AddArgument( args.inputFileName, "input" ) ->AddAlias( "i" )->SetDescription( "4D input image" )->SetMinMax( 1, 1 )->SetRequired(
      true );

  p.AddArgument( args.outputFileName, "output" ) ->AddAlias( "o" )->SetDescription( "Similarity matrix output file" )->SetMinMax( 1, 1 )->SetRequired(
      true );

  p.AddArgument( args.maskFileName, "mask" ) ->AddAlias( "m" )->SetDescription( "Mask 3D image" )->SetMinMax( 1, 1 );

  p.AddArgument( args.iterations, "iterations" )->AddAlias( "n" )->SetDescription( "Bootstrap iterations (default: 10)" )->SetMinMax( 1,
      1 );

  if ( !p.Parse( argc, argv ) )
  {
    p.PrintUsage( std::cout );
    return EXIT_FAILURE;
  }

  bootstrap::Bootstrap boostrapObj;

  boostrapObj.Run( args );

  return EXIT_SUCCESS;
}


// Copyright 2004 The Trustees of Indiana University.

// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

//  Authors: Douglas Gregor
//           Andrew Lumsdaine
#ifndef BOOST_GRAPH_BRANDES_BETWEENNESS_CENTRALITY_HPP
#define BOOST_GRAPH_BRANDES_BETWEENNESS_CENTRALITY_HPP

#include <stack>
#include <vector>
#include <boost/graph/overloading.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/graph/breadth_first_search.hpp>
#include <boost/graph/relax.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/type_traits/is_convertible.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/mpl/if.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/graph/named_function_params.hpp>
#include <algorithm>

namespace boost {

namespace detail { namespace graph {

  /**
   * Customized visitor passed to Dijkstra's algorithm by Brandes'
   * betweenness centrality algorithm. This visitor is responsible for
   * keeping track of the order in which vertices are discovered, the
   * predecessors on the shortest path(s) to a vertex, and the number
   * of shortest paths.
   */
  template<typename Graph, typename WeightMap, typename IncomingMap,
           typename DistanceMap, typename PathCountMap>
  struct brandes_dijkstra_visitor : public bfs_visitor<>
  {
    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;
    typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;

    brandes_dijkstra_visitor(std::stack<vertex_descriptor>& ordered_vertices,
                             WeightMap weight,
                             IncomingMap incoming,
                             DistanceMap distance,
                             PathCountMap path_count)
      : ordered_vertices(ordered_vertices), weight(weight),
        incoming(incoming), distance(distance),
        path_count(path_count)
    { }

    /**
     * Whenever an edge e = (v, w) is relaxed, the incoming edge list
     * for w is set to {(v, w)} and the shortest path count of w is set to
     * the number of paths that reach {v}.
     */
    void edge_relaxed(edge_descriptor e, const Graph& g)
    {
      vertex_descriptor v = source(e, g), w = target(e, g);
      incoming[w].clear();
      incoming[w].push_back(e);
      put(path_count, w, get(path_count, v));
    }

    /**
     * If an edge e = (v, w) was not relaxed, it may still be the case
     * that we've found more equally-short paths, so include {(v, w)} in the
     * incoming edges of w and add all of the shortest paths to v to the
     * shortest path count of w.
     */
    void edge_not_relaxed(edge_descriptor e, const Graph& g)
    {
      typedef typename property_traits<WeightMap>::value_type weight_type;
      typedef typename property_traits<DistanceMap>::value_type distance_type;
      vertex_descriptor v = source(e, g), w = target(e, g);
      distance_type d_v = get(distance, v), d_w = get(distance, w);
      weight_type w_e = get(weight, e);

      closed_plus<distance_type> combine;
      if (d_w == combine(d_v, w_e)) {
        put(path_count, w, get(path_count, w) + get(path_count, v));
        incoming[w].push_back(e);
      }
    }

    /// Keep track of vertices as they are reached
    void examine_vertex(vertex_descriptor w, const Graph&)
    {
      ordered_vertices.push(w);
    }

  private:
    std::stack<vertex_descriptor>& ordered_vertices;
    WeightMap weight;
    IncomingMap incoming;
    DistanceMap distance;
    PathCountMap path_count;
  };

  /**
   * Function object that calls Dijkstra's shortest paths algorithm
   * using the Dijkstra visitor for the Brandes betweenness centrality
   * algorithm.
   */
  template<typename WeightMap>
  struct brandes_dijkstra_shortest_paths
  {
    brandes_dijkstra_shortest_paths(WeightMap weight_map)
      : weight_map(weight_map) { }

    template<typename Graph, typename IncomingMap, typename DistanceMap,
             typename PathCountMap, typename VertexIndexMap>
    void
    operator()(Graph& g,
               typename graph_traits<Graph>::vertex_descriptor s,
               std::stack<typename graph_traits<Graph>::vertex_descriptor>& ov,
               IncomingMap incoming,
               DistanceMap distance,
               PathCountMap path_count,
               VertexIndexMap vertex_index)
    {
      typedef brandes_dijkstra_visitor<Graph, WeightMap, IncomingMap,
                                       DistanceMap, PathCountMap> visitor_type;
      visitor_type visitor(ov, weight_map, incoming, distance, path_count);

      dijkstra_shortest_paths(g, s,
                              boost::weight_map(weight_map)
                              .vertex_index_map(vertex_index)
                              .distance_map(distance)
                              .visitor(visitor));
    }

  private:
    WeightMap weight_map;
  };

  /**
   * Function object that invokes breadth-first search for the
   * unweighted form of the Brandes betweenness centrality algorithm.
   */
  struct brandes_unweighted_shortest_paths
  {
    /**
     * Customized visitor passed to breadth-first search, which
     * records predecessor and the number of shortest paths to each
     * vertex.
     */
    template<typename Graph, typename IncomingMap, typename DistanceMap,
             typename PathCountMap>
    struct visitor_type : public bfs_visitor<>
    {
      typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;
      typedef typename graph_traits<Graph>::vertex_descriptor
        vertex_descriptor;

      visitor_type(IncomingMap incoming, DistanceMap distance,
                   PathCountMap path_count,
                   std::stack<vertex_descriptor>& ordered_vertices)
        : incoming(incoming), distance(distance),
          path_count(path_count), ordered_vertices(ordered_vertices) { }

      /// Keep track of vertices as they are reached
      void examine_vertex(vertex_descriptor v, Graph&)
      {
        ordered_vertices.push(v);
      }

      /**
       * Whenever an edge e = (v, w) is labelled a tree edge, the
       * incoming edge list for w is set to {(v, w)} and the shortest
       * path count of w is set to the number of paths that reach {v}.
       */
      void tree_edge(edge_descriptor e, Graph& g)
      {
        vertex_descriptor v = source(e, g);
        vertex_descriptor w = target(e, g);
        put(distance, w, get(distance, v) + 1);

        put(path_count, w, get(path_count, v));
        incoming[w].push_back(e);
      }

      /**
       * If an edge e = (v, w) is not a tree edge, it may still be the
       * case that we've found more equally-short paths, so include (v, w)
       * in the incoming edge list of w and add all of the shortest
       * paths to v to the shortest path count of w.
       */
      void non_tree_edge(edge_descriptor e, Graph& g)
      {
        vertex_descriptor v = source(e, g);
        vertex_descriptor w = target(e, g);
        if (get(distance, w) == get(distance, v) + 1) {
          put(path_count, w, get(path_count, w) + get(path_count, v));
          incoming[w].push_back(e);
        }
      }

    private:
      IncomingMap incoming;
      DistanceMap distance;
      PathCountMap path_count;
      std::stack<vertex_descriptor>& ordered_vertices;
    };

    template<typename Graph, typename IncomingMap, typename DistanceMap,
             typename PathCountMap, typename VertexIndexMap>
    void
    operator()(Graph& g,
               typename graph_traits<Graph>::vertex_descriptor s,
               std::stack<typename graph_traits<Graph>::vertex_descriptor>& ov,
               IncomingMap incoming,
               DistanceMap distance,
               PathCountMap path_count,
               VertexIndexMap vertex_index)
    {
      typedef typename graph_traits<Graph>::vertex_descriptor
        vertex_descriptor;

      visitor_type<Graph, IncomingMap, DistanceMap, PathCountMap>
        visitor(incoming, distance, path_count, ov);

      std::vector<default_color_type>
        colors(num_vertices(g), color_traits<default_color_type>::white());
      boost::queue<vertex_descriptor> Q;
      breadth_first_visit(g, s, Q, visitor,
                          make_iterator_property_map(colors.begin(),
                                                     vertex_index));
    }
  };

  // When the edge centrality map is a dummy property map, no
  // initialization is needed.
  template<typename Iter>
  inline void
  init_centrality_map(std::pair<Iter, Iter>, dummy_property_map) { }

  // When we have a real edge centrality map, initialize all of the
  // centralities to zero.
  template<typename Iter, typename Centrality>
  void
  init_centrality_map(std::pair<Iter, Iter> keys, Centrality centrality_map)
  {
    typedef typename property_traits<Centrality>::value_type
      centrality_type;
    while (keys.first != keys.second) {
      put(centrality_map, *keys.first, centrality_type(0));
      ++keys.first;
    }
  }

  // When the edge centrality map is a dummy property map, no update
  // is performed.
  template<typename Key, typename T>
  inline void
  update_centrality(dummy_property_map, const Key&, const T&) { }

  // When we have a real edge centrality map, add the value to the map
  template<typename CentralityMap, typename Key, typename T>
  inline void
  update_centrality(CentralityMap centrality_map, Key k, const T& x)
  { put(centrality_map, k, get(centrality_map, k) + x); }

  template<typename Iter>
  inline void
  divide_centrality_by_two(std::pair<Iter, Iter>, dummy_property_map) {}

  template<typename Iter, typename CentralityMap>
  inline void
  divide_centrality_by_two(std::pair<Iter, Iter> keys,
                           CentralityMap centrality_map)
  {
    typename property_traits<CentralityMap>::value_type two(2);
    while (keys.first != keys.second) {
      put(centrality_map, *keys.first, get(centrality_map, *keys.first) / two);
      ++keys.first;
    }
  }

  template<typename Graph, typename CentralityMap, typename EdgeCentralityMap,
           typename IncomingMap, typename DistanceMap,
           typename DependencyMap, typename PathCountMap,
           typename VertexIndexMap, typename ShortestPaths>
  void
  brandes_betweenness_centrality_impl(const Graph& g,
                                      CentralityMap centrality,     // C_B
                                      EdgeCentralityMap edge_centrality_map,
                                      IncomingMap incoming, // P
                                      DistanceMap distance,         // d
                                      DependencyMap dependency,     // delta
                                      PathCountMap path_count,      // sigma
                                      VertexIndexMap vertex_index,
                                      ShortestPaths shortest_paths)
  {
    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;
    typedef typename graph_traits<Graph>::edge_iterator edge_iterator;
    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;

    // Initialize centrality
    init_centrality_map(vertices(g), centrality);
    init_centrality_map(edges(g), edge_centrality_map);

    std::stack<vertex_descriptor> ordered_vertices;
    vertex_iterator s, s_end;
    for (boost::tie(s, s_end) = vertices(g); s != s_end; ++s) {
      // Initialize for this iteration
      vertex_iterator w, w_end;
      for (boost::tie(w, w_end) = vertices(g); w != w_end; ++w) {
        incoming[*w].clear();
        put(path_count, *w, 0);
        put(dependency, *w, 0);
      }
      put(path_count, *s, 1);

      // Execute the shortest paths algorithm. This will be either
      // Dijkstra's algorithm or a customized breadth-first search,
      // depending on whether the graph is weighted or unweighted.
      shortest_paths(g, *s, ordered_vertices, incoming, distance,
                     path_count, vertex_index);

      while (!ordered_vertices.empty()) {
        vertex_descriptor w = ordered_vertices.top();
        ordered_vertices.pop();

        typedef typename property_traits<IncomingMap>::value_type
          incoming_type;
        typedef typename incoming_type::iterator incoming_iterator;
        typedef typename property_traits<DependencyMap>::value_type
          dependency_type;

        for (incoming_iterator vw = incoming[w].begin();
             vw != incoming[w].end(); ++vw) {
          vertex_descriptor v = source(*vw, g);
          dependency_type factor = dependency_type(get(path_count, v))
            / dependency_type(get(path_count, w));
          factor *= (dependency_type(1) + get(dependency, w));
          put(dependency, v, get(dependency, v) + factor);
          update_centrality(edge_centrality_map, *vw, factor);
        }

        if (w != *s) {
          update_centrality(centrality, w, get(dependency, w));
        }
      }
    }

    typedef typename graph_traits<Graph>::directed_category directed_category;
    const bool is_undirected =
      is_convertible<directed_category*, undirected_tag*>::value;
    if (is_undirected) {
      divide_centrality_by_two(vertices(g), centrality);
      divide_centrality_by_two(edges(g), edge_centrality_map);
    }
  }

} } // end namespace detail::graph

template<typename Graph, typename CentralityMap, typename EdgeCentralityMap,
         typename IncomingMap, typename DistanceMap,
         typename DependencyMap, typename PathCountMap,
         typename VertexIndexMap>
void
brandes_betweenness_centrality(const Graph& g,
                               CentralityMap centrality,     // C_B
                               EdgeCentralityMap edge_centrality_map,
                               IncomingMap incoming, // P
                               DistanceMap distance,         // d
                               DependencyMap dependency,     // delta
                               PathCountMap path_count,      // sigma
                               VertexIndexMap vertex_index
                               BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,vertex_list_graph_tag))
{
  detail::graph::brandes_unweighted_shortest_paths shortest_paths;

  detail::graph::brandes_betweenness_centrality_impl(g, centrality,
                                                     edge_centrality_map,
                                                     incoming, distance,
                                                     dependency, path_count,
                                                     vertex_index,
                                                     shortest_paths);
}

template<typename Graph, typename CentralityMap, typename EdgeCentralityMap,
         typename IncomingMap, typename DistanceMap,
         typename DependencyMap, typename PathCountMap,
         typename VertexIndexMap, typename WeightMap>
void
brandes_betweenness_centrality(const Graph& g,
                               CentralityMap centrality,     // C_B
                               EdgeCentralityMap edge_centrality_map,
                               IncomingMap incoming, // P
                               DistanceMap distance,         // d
                               DependencyMap dependency,     // delta
                               PathCountMap path_count,      // sigma
                               VertexIndexMap vertex_index,
                               WeightMap weight_map
                               BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,vertex_list_graph_tag))
{
  detail::graph::brandes_dijkstra_shortest_paths<WeightMap>
    shortest_paths(weight_map);

  detail::graph::brandes_betweenness_centrality_impl(g, centrality,
                                                     edge_centrality_map,
                                                     incoming, distance,
                                                     dependency, path_count,
                                                     vertex_index,
                                                     shortest_paths);
}

namespace detail { namespace graph {
  template<typename Graph, typename CentralityMap, typename EdgeCentralityMap,
           typename WeightMap, typename VertexIndexMap>
  void
  brandes_betweenness_centrality_dispatch2(const Graph& g,
                                           CentralityMap centrality,
                                           EdgeCentralityMap edge_centrality_map,
                                           WeightMap weight_map,
                                           VertexIndexMap vertex_index)
  {
    typedef typename graph_traits<Graph>::degree_size_type degree_size_type;
    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;
    typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;
    typedef typename mpl::if_c<(is_same<CentralityMap,
                                        dummy_property_map>::value),
                                         EdgeCentralityMap,
                               CentralityMap>::type a_centrality_map;
    typedef typename property_traits<a_centrality_map>::value_type
      centrality_type;

    typename graph_traits<Graph>::vertices_size_type V = num_vertices(g);

    std::vector<std::vector<edge_descriptor> > incoming(V);
    std::vector<centrality_type> distance(V);
    std::vector<centrality_type> dependency(V);
    std::vector<degree_size_type> path_count(V);

    brandes_betweenness_centrality(
      g, centrality, edge_centrality_map,
      make_iterator_property_map(incoming.begin(), vertex_index),
      make_iterator_property_map(distance.begin(), vertex_index),
      make_iterator_property_map(dependency.begin(), vertex_index),
      make_iterator_property_map(path_count.begin(), vertex_index),
      vertex_index,
      weight_map);
  }

  template<typename Graph, typename CentralityMap, typename EdgeCentralityMap,
           typename VertexIndexMap>
  void
  brandes_betweenness_centrality_dispatch2(const Graph& g,
                                           CentralityMap centrality,
                                           EdgeCentralityMap edge_centrality_map,
                                           VertexIndexMap vertex_index)
  {
    typedef typename graph_traits<Graph>::degree_size_type degree_size_type;
    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;
    typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;
    typedef typename mpl::if_c<(is_same<CentralityMap,
                                        dummy_property_map>::value),
                                         EdgeCentralityMap,
                               CentralityMap>::type a_centrality_map;
    typedef typename property_traits<a_centrality_map>::value_type
      centrality_type;

    typename graph_traits<Graph>::vertices_size_type V = num_vertices(g);

    std::vector<std::vector<edge_descriptor> > incoming(V);
    std::vector<centrality_type> distance(V);
    std::vector<centrality_type> dependency(V);
    std::vector<degree_size_type> path_count(V);

    brandes_betweenness_centrality(
      g, centrality, edge_centrality_map,
      make_iterator_property_map(incoming.begin(), vertex_index),
      make_iterator_property_map(distance.begin(), vertex_index),
      make_iterator_property_map(dependency.begin(), vertex_index),
      make_iterator_property_map(path_count.begin(), vertex_index),
      vertex_index);
  }

  template<typename WeightMap>
  struct brandes_betweenness_centrality_dispatch1
  {
    template<typename Graph, typename CentralityMap,
             typename EdgeCentralityMap, typename VertexIndexMap>
    static void
    run(const Graph& g, CentralityMap centrality,
        EdgeCentralityMap edge_centrality_map, VertexIndexMap vertex_index,
        WeightMap weight_map)
    {
      brandes_betweenness_centrality_dispatch2(g, centrality, edge_centrality_map,
                                               weight_map, vertex_index);
    }
  };

  template<>
  struct brandes_betweenness_centrality_dispatch1<error_property_not_found>
  {
    template<typename Graph, typename CentralityMap,
             typename EdgeCentralityMap, typename VertexIndexMap>
    static void
    run(const Graph& g, CentralityMap centrality,
        EdgeCentralityMap edge_centrality_map, VertexIndexMap vertex_index,
        error_property_not_found)
    {
      brandes_betweenness_centrality_dispatch2(g, centrality, edge_centrality_map,
                                               vertex_index);
    }
  };

  template <typename T>
  struct is_bgl_named_params {
    BOOST_STATIC_CONSTANT(bool, value = false);
  };

  template <typename Param, typename Tag, typename Rest>
  struct is_bgl_named_params<bgl_named_params<Param, Tag, Rest> > {
    BOOST_STATIC_CONSTANT(bool, value = true);
  };

} } // end namespace detail::graph

template<typename Graph, typename Param, typename Tag, typename Rest>
void
brandes_betweenness_centrality(const Graph& g,
                               const bgl_named_params<Param,Tag,Rest>& params
                               BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,vertex_list_graph_tag))
{
  typedef bgl_named_params<Param,Tag,Rest> named_params;

  typedef typename property_value<named_params, edge_weight_t>::type ew;
  detail::graph::brandes_betweenness_centrality_dispatch1<ew>::run(
    g,
    choose_param(get_param(params, vertex_centrality),
                 dummy_property_map()),
    choose_param(get_param(params, edge_centrality),
                 dummy_property_map()),
    choose_const_pmap(get_param(params, vertex_index), g, vertex_index),
    get_param(params, edge_weight));
}

// disable_if is required to work around problem with MSVC 7.1 (it seems to not
// get partial ordering getween this overload and the previous one correct)
template<typename Graph, typename CentralityMap>
typename disable_if<detail::graph::is_bgl_named_params<CentralityMap>,
                    void>::type
brandes_betweenness_centrality(const Graph& g, CentralityMap centrality
                               BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,vertex_list_graph_tag))
{
  detail::graph::brandes_betweenness_centrality_dispatch2(
    g, centrality, dummy_property_map(), get(vertex_index, g));
}

template<typename Graph, typename CentralityMap, typename EdgeCentralityMap>
void
brandes_betweenness_centrality(const Graph& g, CentralityMap centrality,
                               EdgeCentralityMap edge_centrality_map
                               BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,vertex_list_graph_tag))
{
  detail::graph::brandes_betweenness_centrality_dispatch2(
    g, centrality, edge_centrality_map, get(vertex_index, g));
}

/**
 * Converts "absolute" betweenness centrality (as computed by the
 * brandes_betweenness_centrality algorithm) in the centrality map
 * into "relative" centrality. The result is placed back into the
 * given centrality map.
 */
template<typename Graph, typename CentralityMap>
void
relative_betweenness_centrality(const Graph& g, CentralityMap centrality)
{
  typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;
  typedef typename property_traits<CentralityMap>::value_type centrality_type;

  typename graph_traits<Graph>::vertices_size_type n = num_vertices(g);
  centrality_type factor = centrality_type(2)/centrality_type(n*n - 3*n + 2);
  vertex_iterator v, v_end;
  for (boost::tie(v, v_end) = vertices(g); v != v_end; ++v) {
    put(centrality, *v, factor * get(centrality, *v));
  }
}

// Compute the central point dominance of a graph.
template<typename Graph, typename CentralityMap>
typename property_traits<CentralityMap>::value_type
central_point_dominance(const Graph& g, CentralityMap centrality
                        BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,vertex_list_graph_tag))
{
  using std::max;

  typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;
  typedef typename property_traits<CentralityMap>::value_type centrality_type;

  typename graph_traits<Graph>::vertices_size_type n = num_vertices(g);

  // Find max centrality
  centrality_type max_centrality(0);
  vertex_iterator v, v_end;
  for (boost::tie(v, v_end) = vertices(g); v != v_end; ++v) {
    max_centrality = (max)(max_centrality, get(centrality, *v));
  }

  // Compute central point dominance
  centrality_type sum(0);
  for (boost::tie(v, v_end) = vertices(g); v != v_end; ++v) {
    sum += (max_centrality - get(centrality, *v));
  }
  return sum/(n-1);
}

} // end namespace boost

#endif // BOOST_GRAPH_BRANDES_BETWEENNESS_CENTRALITY_HPP