#include <btcnew/core_test/testutil.hpp>
#include <btcnew/node/common.hpp>
#include <btcnew/node/node.hpp>

#include <gtest/gtest.h>

#include <boost/property_tree/json_parser.hpp>

#include <fstream>

#include <crypto/ed25519-donna/ed25519.h>

TEST (ed25519, signing)
{
	btcnew::private_key prv (0);
	auto pub (btcnew::pub_key (prv));
	btcnew::uint256_union message (0);
	btcnew::signature signature;
	ed25519_sign (message.bytes.data (), sizeof (message.bytes), prv.bytes.data (), pub.bytes.data (), signature.bytes.data ());
	auto valid1 (ed25519_sign_open (message.bytes.data (), sizeof (message.bytes), pub.bytes.data (), signature.bytes.data ()));
	ASSERT_EQ (0, valid1);
	signature.bytes[32] ^= 0x1;
	auto valid2 (ed25519_sign_open (message.bytes.data (), sizeof (message.bytes), pub.bytes.data (), signature.bytes.data ()));
	ASSERT_NE (0, valid2);
}

TEST (transaction_block, empty)
{
	btcnew::keypair key1;
	btcnew::send_block block (0, 1, 13, key1.prv, key1.pub, 2);
	auto hash (block.hash ());
	ASSERT_FALSE (btcnew::validate_message (key1.pub, hash, block.signature));
	block.signature.bytes[32] ^= 0x1;
	ASSERT_TRUE (btcnew::validate_message (key1.pub, hash, block.signature));
}

TEST (block, send_serialize)
{
	btcnew::send_block block1 (0, 1, 2, btcnew::keypair ().prv, 4, 5);
	std::vector<uint8_t> bytes;
	{
		btcnew::vectorstream stream1 (bytes);
		block1.serialize (stream1);
	}
	auto data (bytes.data ());
	auto size (bytes.size ());
	ASSERT_NE (nullptr, data);
	ASSERT_NE (0, size);
	btcnew::bufferstream stream2 (data, size);
	bool error (false);
	btcnew::send_block block2 (error, stream2);
	ASSERT_FALSE (error);
	ASSERT_EQ (block1, block2);
}

TEST (block, send_serialize_json)
{
	btcnew::send_block block1 (0, 1, 2, btcnew::keypair ().prv, 4, 5);
	std::string string1;
	block1.serialize_json (string1);
	ASSERT_NE (0, string1.size ());
	boost::property_tree::ptree tree1;
	std::stringstream istream (string1);
	boost::property_tree::read_json (istream, tree1);
	bool error (false);
	btcnew::send_block block2 (error, tree1);
	ASSERT_FALSE (error);
	ASSERT_EQ (block1, block2);
}

TEST (block, receive_serialize)
{
	btcnew::receive_block block1 (0, 1, btcnew::keypair ().prv, 3, 4);
	btcnew::keypair key1;
	std::vector<uint8_t> bytes;
	{
		btcnew::vectorstream stream1 (bytes);
		block1.serialize (stream1);
	}
	btcnew::bufferstream stream2 (bytes.data (), bytes.size ());
	bool error (false);
	btcnew::receive_block block2 (error, stream2);
	ASSERT_FALSE (error);
	ASSERT_EQ (block1, block2);
}

TEST (block, receive_serialize_json)
{
	btcnew::receive_block block1 (0, 1, btcnew::keypair ().prv, 3, 4);
	std::string string1;
	block1.serialize_json (string1);
	ASSERT_NE (0, string1.size ());
	boost::property_tree::ptree tree1;
	std::stringstream istream (string1);
	boost::property_tree::read_json (istream, tree1);
	bool error (false);
	btcnew::receive_block block2 (error, tree1);
	ASSERT_FALSE (error);
	ASSERT_EQ (block1, block2);
}

TEST (block, open_serialize_json)
{
	btcnew::open_block block1 (0, 1, 0, btcnew::keypair ().prv, 0, 0);
	std::string string1;
	block1.serialize_json (string1);
	ASSERT_NE (0, string1.size ());
	boost::property_tree::ptree tree1;
	std::stringstream istream (string1);
	boost::property_tree::read_json (istream, tree1);
	bool error (false);
	btcnew::open_block block2 (error, tree1);
	ASSERT_FALSE (error);
	ASSERT_EQ (block1, block2);
}

TEST (block, change_serialize_json)
{
	btcnew::change_block block1 (0, 1, btcnew::keypair ().prv, 3, 4);
	std::string string1;
	block1.serialize_json (string1);
	ASSERT_NE (0, string1.size ());
	boost::property_tree::ptree tree1;
	std::stringstream istream (string1);
	boost::property_tree::read_json (istream, tree1);
	bool error (false);
	btcnew::change_block block2 (error, tree1);
	ASSERT_FALSE (error);
	ASSERT_EQ (block1, block2);
}

TEST (uint512_union, parse_zero)
{
	btcnew::uint512_union input (btcnew::uint512_t (0));
	std::string text;
	input.encode_hex (text);
	btcnew::uint512_union output;
	auto error (output.decode_hex (text));
	ASSERT_FALSE (error);
	ASSERT_EQ (input, output);
	ASSERT_TRUE (output.number ().is_zero ());
}

TEST (uint512_union, parse_zero_short)
{
	std::string text ("0");
	btcnew::uint512_union output;
	auto error (output.decode_hex (text));
	ASSERT_FALSE (error);
	ASSERT_TRUE (output.number ().is_zero ());
}

TEST (uint512_union, parse_one)
{
	btcnew::uint512_union input (btcnew::uint512_t (1));
	std::string text;
	input.encode_hex (text);
	btcnew::uint512_union output;
	auto error (output.decode_hex (text));
	ASSERT_FALSE (error);
	ASSERT_EQ (input, output);
	ASSERT_EQ (1, output.number ());
}

TEST (uint512_union, parse_error_symbol)
{
	btcnew::uint512_union input (btcnew::uint512_t (1000));
	std::string text;
	input.encode_hex (text);
	text[5] = '!';
	btcnew::uint512_union output;
	auto error (output.decode_hex (text));
	ASSERT_TRUE (error);
}

TEST (uint512_union, max)
{
	btcnew::uint512_union input (std::numeric_limits<btcnew::uint512_t>::max ());
	std::string text;
	input.encode_hex (text);
	btcnew::uint512_union output;
	auto error (output.decode_hex (text));
	ASSERT_FALSE (error);
	ASSERT_EQ (input, output);
	ASSERT_EQ (btcnew::uint512_t ("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), output.number ());
}

TEST (uint512_union, parse_error_overflow)
{
	btcnew::uint512_union input (std::numeric_limits<btcnew::uint512_t>::max ());
	std::string text;
	input.encode_hex (text);
	text.push_back (0);
	btcnew::uint512_union output;
	auto error (output.decode_hex (text));
	ASSERT_TRUE (error);
}

TEST (send_block, deserialize)
{
	btcnew::send_block block1 (0, 1, 2, btcnew::keypair ().prv, 4, 5);
	ASSERT_EQ (block1.hash (), block1.hash ());
	std::vector<uint8_t> bytes;
	{
		btcnew::vectorstream stream1 (bytes);
		block1.serialize (stream1);
	}
	ASSERT_EQ (btcnew::send_block::size, bytes.size ());
	btcnew::bufferstream stream2 (bytes.data (), bytes.size ());
	bool error (false);
	btcnew::send_block block2 (error, stream2);
	ASSERT_FALSE (error);
	ASSERT_EQ (block1, block2);
}

TEST (receive_block, deserialize)
{
	btcnew::receive_block block1 (0, 1, btcnew::keypair ().prv, 3, 4);
	ASSERT_EQ (block1.hash (), block1.hash ());
	block1.hashables.previous = 2;
	block1.hashables.source = 4;
	std::vector<uint8_t> bytes;
	{
		btcnew::vectorstream stream1 (bytes);
		block1.serialize (stream1);
	}
	ASSERT_EQ (btcnew::receive_block::size, bytes.size ());
	btcnew::bufferstream stream2 (bytes.data (), bytes.size ());
	bool error (false);
	btcnew::receive_block block2 (error, stream2);
	ASSERT_FALSE (error);
	ASSERT_EQ (block1, block2);
}

TEST (open_block, deserialize)
{
	btcnew::open_block block1 (0, 1, 0, btcnew::keypair ().prv, 0, 0);
	ASSERT_EQ (block1.hash (), block1.hash ());
	std::vector<uint8_t> bytes;
	{
		btcnew::vectorstream stream (bytes);
		block1.serialize (stream);
	}
	ASSERT_EQ (btcnew::open_block::size, bytes.size ());
	btcnew::bufferstream stream (bytes.data (), bytes.size ());
	bool error (false);
	btcnew::open_block block2 (error, stream);
	ASSERT_FALSE (error);
	ASSERT_EQ (block1, block2);
}

TEST (change_block, deserialize)
{
	btcnew::change_block block1 (1, 2, btcnew::keypair ().prv, 4, 5);
	ASSERT_EQ (block1.hash (), block1.hash ());
	std::vector<uint8_t> bytes;
	{
		btcnew::vectorstream stream1 (bytes);
		block1.serialize (stream1);
	}
	ASSERT_EQ (btcnew::change_block::size, bytes.size ());
	auto data (bytes.data ());
	auto size (bytes.size ());
	ASSERT_NE (nullptr, data);
	ASSERT_NE (0, size);
	btcnew::bufferstream stream2 (data, size);
	bool error (false);
	btcnew::change_block block2 (error, stream2);
	ASSERT_FALSE (error);
	ASSERT_EQ (block1, block2);
}

TEST (frontier_req, serialization)
{
	btcnew::frontier_req request1;
	request1.start = 1;
	request1.age = 2;
	request1.count = 3;
	std::vector<uint8_t> bytes;
	{
		btcnew::vectorstream stream (bytes);
		request1.serialize (stream);
	}
	auto error (false);
	btcnew::bufferstream stream (bytes.data (), bytes.size ());
	btcnew::message_header header (error, stream);
	ASSERT_FALSE (error);
	btcnew::frontier_req request2 (error, stream, header);
	ASSERT_FALSE (error);
	ASSERT_EQ (request1, request2);
}

TEST (block, publish_req_serialization)
{
	btcnew::keypair key1;
	btcnew::keypair key2;
	auto block (std::make_shared<btcnew::send_block> (0, key2.pub, 200, btcnew::keypair ().prv, 2, 3));
	btcnew::publish req (block);
	std::vector<uint8_t> bytes;
	{
		btcnew::vectorstream stream (bytes);
		req.serialize (stream);
	}
	auto error (false);
	btcnew::bufferstream stream2 (bytes.data (), bytes.size ());
	btcnew::message_header header (error, stream2);
	ASSERT_FALSE (error);
	btcnew::publish req2 (error, stream2, header);
	ASSERT_FALSE (error);
	ASSERT_EQ (req, req2);
	ASSERT_EQ (*req.block, *req2.block);
}

TEST (state_block, serialization)
{
	btcnew::keypair key1;
	btcnew::keypair key2;
	btcnew::state_block block1 (key1.pub, 1, key2.pub, 2, 4, key1.prv, key1.pub, 5);
	ASSERT_EQ (key1.pub, block1.hashables.account);
	ASSERT_EQ (btcnew::block_hash (1), block1.previous ());
	ASSERT_EQ (key2.pub, block1.hashables.representative);
	ASSERT_EQ (btcnew::amount (2), block1.hashables.balance);
	ASSERT_EQ (btcnew::uint256_union (4), block1.hashables.link);
	std::vector<uint8_t> bytes;
	{
		btcnew::vectorstream stream (bytes);
		block1.serialize (stream);
	}
	ASSERT_EQ (0x5, bytes[215]); // Ensure work is serialized big-endian
	ASSERT_EQ (btcnew::state_block::size, bytes.size ());
	bool error1 (false);
	btcnew::bufferstream stream (bytes.data (), bytes.size ());
	btcnew::state_block block2 (error1, stream);
	ASSERT_FALSE (error1);
	ASSERT_EQ (block1, block2);
	block2.hashables.account.clear ();
	block2.hashables.previous.clear ();
	block2.hashables.representative.clear ();
	block2.hashables.balance.clear ();
	block2.hashables.link.clear ();
	block2.signature.clear ();
	block2.work = 0;
	btcnew::bufferstream stream2 (bytes.data (), bytes.size ());
	ASSERT_FALSE (block2.deserialize (stream2));
	ASSERT_EQ (block1, block2);
	std::string json;
	block1.serialize_json (json);
	std::stringstream body (json);
	boost::property_tree::ptree tree;
	boost::property_tree::read_json (body, tree);
	bool error2 (false);
	btcnew::state_block block3 (error2, tree);
	ASSERT_FALSE (error2);
	ASSERT_EQ (block1, block3);
	block3.hashables.account.clear ();
	block3.hashables.previous.clear ();
	block3.hashables.representative.clear ();
	block3.hashables.balance.clear ();
	block3.hashables.link.clear ();
	block3.signature.clear ();
	block3.work = 0;
	ASSERT_FALSE (block3.deserialize_json (tree));
	ASSERT_EQ (block1, block3);
}

TEST (state_block, hashing)
{
	btcnew::keypair key;
	btcnew::state_block block (key.pub, 0, key.pub, 0, 0, key.prv, key.pub, 0);
	auto hash (block.hash ());
	block.hashables.account.bytes[0] ^= 0x1;
	ASSERT_NE (hash, block.hash ());
	block.hashables.account.bytes[0] ^= 0x1;
	ASSERT_EQ (hash, block.hash ());
	block.hashables.previous.bytes[0] ^= 0x1;
	ASSERT_NE (hash, block.hash ());
	block.hashables.previous.bytes[0] ^= 0x1;
	ASSERT_EQ (hash, block.hash ());
	block.hashables.representative.bytes[0] ^= 0x1;
	ASSERT_NE (hash, block.hash ());
	block.hashables.representative.bytes[0] ^= 0x1;
	ASSERT_EQ (hash, block.hash ());
	block.hashables.balance.bytes[0] ^= 0x1;
	ASSERT_NE (hash, block.hash ());
	block.hashables.balance.bytes[0] ^= 0x1;
	ASSERT_EQ (hash, block.hash ());
	block.hashables.link.bytes[0] ^= 0x1;
	ASSERT_NE (hash, block.hash ());
	block.hashables.link.bytes[0] ^= 0x1;
	ASSERT_EQ (hash, block.hash ());
}

TEST (block_uniquer, null)
{
	btcnew::block_uniquer uniquer;
	ASSERT_EQ (nullptr, uniquer.unique (nullptr));
}

TEST (block_uniquer, single)
{
	btcnew::keypair key;
	auto block1 (std::make_shared<btcnew::state_block> (0, 0, 0, 0, 0, key.prv, key.pub, 0));
	auto block2 (std::make_shared<btcnew::state_block> (*block1));
	ASSERT_NE (block1, block2);
	ASSERT_EQ (*block1, *block2);
	std::weak_ptr<btcnew::state_block> block3 (block2);
	ASSERT_NE (nullptr, block3.lock ());
	btcnew::block_uniquer uniquer;
	auto block4 (uniquer.unique (block1));
	ASSERT_EQ (block1, block4);
	auto block5 (uniquer.unique (block2));
	ASSERT_EQ (block1, block5);
	block2.reset ();
	ASSERT_EQ (nullptr, block3.lock ());
}

TEST (block_uniquer, cleanup)
{
	btcnew::keypair key;
	auto block1 (std::make_shared<btcnew::state_block> (0, 0, 0, 0, 0, key.prv, key.pub, 0));
	auto block2 (std::make_shared<btcnew::state_block> (0, 0, 0, 0, 0, key.prv, key.pub, 1));
	btcnew::block_uniquer uniquer;
	auto block3 (uniquer.unique (block1));
	auto block4 (uniquer.unique (block2));
	block2.reset ();
	block4.reset ();
	ASSERT_EQ (2, uniquer.size ());
	auto iterations (0);
	while (uniquer.size () == 2)
	{
		auto block5 (uniquer.unique (block1));
		ASSERT_LT (iterations++, 200);
	}
}

TEST (block_builder, from)
{
	std::error_code ec;
	btcnew::block_builder builder;
	auto block = builder
	             .state ()
	             .account_address ("btcnew_15nhh1kzw3x8ohez6s75wy3jr6dqgq65oaede1fzk5hqxk4j8ehz7iqtb3to")
	             .previous_hex ("FEFBCE274E75148AB31FF63EFB3082EF1126BF72BF3FA9C76A97FD5A9F0EBEC5")
	             .balance_dec ("2251569974100400000000000000000000")
	             .representative_address ("btcnew_1stofnrxuz3cai7ze75o174bpm7scwj9jn3nxsn8ntzg784jf1gzn1jjdkou")
	             .link_hex ("E16DD58C1EFA8B521545B0A74375AA994D9FC43828A4266D75ECF57F07A7EE86")
	             .build (ec);
	ASSERT_EQ (block->hash ().to_string (), "2D243F8F92CDD0AD94A1D456A6B15F3BE7A6FCBD98D4C5831D06D15C818CD81F");

	auto block2 = builder.state ().from (*block).build (ec);
	ASSERT_EQ (block2->hash ().to_string (), "2D243F8F92CDD0AD94A1D456A6B15F3BE7A6FCBD98D4C5831D06D15C818CD81F");

	auto block3 = builder.state ().from (*block).sign_zero ().work (0).build (ec);
	ASSERT_EQ (block3->hash ().to_string (), "2D243F8F92CDD0AD94A1D456A6B15F3BE7A6FCBD98D4C5831D06D15C818CD81F");
}

TEST (block_builder, zeroed_state_block)
{
	btcnew::block_builder builder;
	btcnew::keypair key;
	// Make sure manually- and builder constructed all-zero blocks have equal hashes, and check signature.
	auto zero_block_manual (std::make_shared<btcnew::state_block> (0, 0, 0, 0, 0, key.prv, key.pub, 0));
	auto zero_block_build = builder.state ().zero ().sign (key.prv, key.pub).build ();
	ASSERT_TRUE (zero_block_manual->hash () == zero_block_build->hash ());
	ASSERT_FALSE (btcnew::validate_message (key.pub, zero_block_build->hash (), zero_block_build->signature));
}

TEST (block_builder, state)
{
	// Test against a random hash from the live network
	std::error_code ec;
	btcnew::block_builder builder;
	auto block = builder
	             .state ()
	             .account_address ("btcnew_15nhh1kzw3x8ohez6s75wy3jr6dqgq65oaede1fzk5hqxk4j8ehz7iqtb3to")
	             .previous_hex ("FEFBCE274E75148AB31FF63EFB3082EF1126BF72BF3FA9C76A97FD5A9F0EBEC5")
	             .balance_dec ("2251569974100400000000000000000000")
	             .representative_address ("btcnew_1stofnrxuz3cai7ze75o174bpm7scwj9jn3nxsn8ntzg784jf1gzn1jjdkou")
	             .link_hex ("E16DD58C1EFA8B521545B0A74375AA994D9FC43828A4266D75ECF57F07A7EE86")
	             .build (ec);
	ASSERT_EQ (block->hash ().to_string (), "2D243F8F92CDD0AD94A1D456A6B15F3BE7A6FCBD98D4C5831D06D15C818CD81F");
}

TEST (block_builder, state_missing_rep)
{
	// Test against a random hash from the live network
	std::error_code ec;
	btcnew::block_builder builder;
	auto block = builder
	             .state ()
	             .account_address ("btcnew_15nhh1kzw3x8ohez6s75wy3jr6dqgq65oaede1fzk5hqxk4j8ehz7iqtb3to")
	             .previous_hex ("FEFBCE274E75148AB31FF63EFB3082EF1126BF72BF3FA9C76A97FD5A9F0EBEC5")
	             .balance_dec ("2251569974100400000000000000000000")
	             .link_hex ("E16DD58C1EFA8B521545B0A74375AA994D9FC43828A4266D75ECF57F07A7EE86")
	             .sign_zero ()
	             .work (0)
	             .build (ec);
	ASSERT_EQ (ec, btcnew::error_common::missing_representative);
}

TEST (block_builder, state_equality)
{
	std::error_code ec;
	btcnew::block_builder builder;

	// With constructor
	btcnew::keypair key1, key2;
	btcnew::state_block block1 (key1.pub, 1, key2.pub, 2, 4, key1.prv, key1.pub, 5);

	// With builder
	auto block2 = builder
	              .state ()
	              .account (key1.pub)
	              .previous (1)
	              .representative (key2.pub)
	              .balance (2)
	              .link (4)
	              .sign (key1.prv, key1.pub)
	              .work (5)
	              .build (ec);

	ASSERT_NO_ERROR (ec);
	ASSERT_EQ (block1.hash (), block2->hash ());
	ASSERT_EQ (block1.work, block2->work);
}

TEST (block_builder, state_errors)
{
	std::error_code ec;
	btcnew::block_builder builder;

	// Ensure the proper error is generated
	builder.state ().account_hex ("btcnew_bad").build (ec);
	ASSERT_EQ (ec, btcnew::error_common::bad_account_number);

	builder.state ().zero ().account_address ("btcnew_1111111111111111111111111111111111111111111111111111hifc8npp").build (ec);
	ASSERT_NO_ERROR (ec);
}

TEST (block_builder, open)
{
	// Test built block's hash against the Genesis open block from the live network
	std::error_code ec;
	btcnew::block_builder builder;
	auto block = builder
	             .open ()
	             .account_address ("btcnew_3t6k35gi95xu6tergt6p69ck76ogmitsa8mnijtpxm9fkcm736xtoncuohr3")
	             .representative_address ("btcnew_3t6k35gi95xu6tergt6p69ck76ogmitsa8mnijtpxm9fkcm736xtoncuohr3")
	             .source_hex ("E89208DD038FBB269987689621D52292AE9C35941A7484756ECCED92A65093BA")
	             .build (ec);
	ASSERT_EQ (block->hash ().to_string (), "991CF190094C00F0B68E2E5F75F6BEE95A2E0BD93CEAA4A6734DB9F19B728948");
}

TEST (block_builder, open_equality)
{
	std::error_code ec;
	btcnew::block_builder builder;

	// With constructor
	btcnew::keypair key1, key2;
	btcnew::open_block block1 (1, key1.pub, key2.pub, key1.prv, key1.pub, 5);

	// With builder
	auto block2 = builder
	              .open ()
	              .source (1)
	              .account (key2.pub)
	              .representative (key1.pub)
	              .sign (key1.prv, key1.pub)
	              .work (5)
	              .build (ec);

	ASSERT_NO_ERROR (ec);
	ASSERT_EQ (block1.hash (), block2->hash ());
	ASSERT_EQ (block1.work, block2->work);
}

TEST (block_builder, change)
{
	std::error_code ec;
	btcnew::block_builder builder;
	auto block = builder
	             .change ()
	             .representative_address ("btcnew_3rropjiqfxpmrrkooej4qtmm1pueu36f9ghinpho4esfdor8785a455d16nf")
	             .previous_hex ("088EE46429CA936F76C4EAA20B97F6D33E5D872971433EE0C1311BCB98764456")
	             .build (ec);
	ASSERT_EQ (block->hash ().to_string (), "13552AC3928E93B5C6C215F61879358E248D4A5246B8B3D1EEC5A566EDCEE077");
}

TEST (block_builder, change_equality)
{
	std::error_code ec;
	btcnew::block_builder builder;

	// With constructor
	btcnew::keypair key1, key2;
	btcnew::change_block block1 (1, key1.pub, key1.prv, key1.pub, 5);

	// With builder
	auto block2 = builder
	              .change ()
	              .previous (1)
	              .representative (key1.pub)
	              .sign (key1.prv, key1.pub)
	              .work (5)
	              .build (ec);

	ASSERT_NO_ERROR (ec);
	ASSERT_EQ (block1.hash (), block2->hash ());
	ASSERT_EQ (block1.work, block2->work);
}

TEST (block_builder, send)
{
	std::error_code ec;
	btcnew::block_builder builder;
	auto block = builder
	             .send ()
	             .destination_address ("btcnew_1gys8r4crpxhp94n4uho5cshaho81na6454qni5gu9n53gksoyy1wcd4udyb")
	             .previous_hex ("F685856D73A488894F7F3A62BC3A88E17E985F9969629FF3FDD4A0D4FD823F24")
	             .balance_hex ("00F035A9C7D818E7C34148C524FFFFEE")
	             .build (ec);
	ASSERT_EQ (block->hash ().to_string (), "4560E7B1F3735D082700CFC2852F5D1F378F7418FD24CEF1AD45AB69316F15CD");
}

TEST (block_builder, send_equality)
{
	std::error_code ec;
	btcnew::block_builder builder;

	// With constructor
	btcnew::keypair key1, key2;
	btcnew::send_block block1 (1, key1.pub, 2, key1.prv, key1.pub, 5);

	// With builder
	auto block2 = builder
	              .send ()
	              .previous (1)
	              .destination (key1.pub)
	              .balance (2)
	              .sign (key1.prv, key1.pub)
	              .work (5)
	              .build (ec);

	ASSERT_NO_ERROR (ec);
	ASSERT_EQ (block1.hash (), block2->hash ());
	ASSERT_EQ (block1.work, block2->work);
}

TEST (block_builder, receive_equality)
{
	std::error_code ec;
	btcnew::block_builder builder;

	// With constructor
	btcnew::keypair key1;
	btcnew::receive_block block1 (1, 2, key1.prv, key1.pub, 5);

	// With builder
	auto block2 = builder
	              .receive ()
	              .previous (1)
	              .source (2)
	              .sign (key1.prv, key1.pub)
	              .work (5)
	              .build (ec);

	ASSERT_NO_ERROR (ec);
	ASSERT_EQ (block1.hash (), block2->hash ());
	ASSERT_EQ (block1.work, block2->work);
}

TEST (block_builder, receive)
{
	std::error_code ec;
	btcnew::block_builder builder;
	auto block = builder
	             .receive ()
	             .previous_hex ("59660153194CAC5DAC08509D87970BF86F6AEA943025E2A7ED7460930594950E")
	             .source_hex ("7B2B0A29C1B235FDF9B4DEF2984BB3573BD1A52D28246396FBB3E4C5FE662135")
	             .build (ec);
	ASSERT_EQ (block->hash ().to_string (), "6C004BF911D9CF2ED75CF6EC45E795122AD5D093FF5A83EDFBA43EC4A3EDC722");
}


/*
 * Copyright 2013-present Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <folly/hash/Checksum.h>

#include <boost/crc.hpp>

#include <folly/Benchmark.h>
#include <folly/Random.h>
#include <folly/hash/Hash.h>
#include <folly/hash/detail/ChecksumDetail.h>
#include <folly/portability/GFlags.h>
#include <folly/portability/GTest.h>

namespace {
const unsigned int BUFFER_SIZE = 512 * 1024 * sizeof(uint64_t);
uint8_t buffer[BUFFER_SIZE];

struct ExpectedResult {
  size_t offset;
  size_t length;
  uint32_t crc32c;
};

ExpectedResult expectedResults[] = {
    // Zero-byte input
    {0, 0, ~0U},
    // Small aligned inputs to test special cases in SIMD implementations
    {8, 1, 1543413366},
    {8, 2, 523493126},
    {8, 3, 1560427360},
    {8, 4, 3422504776},
    {8, 5, 447841138},
    {8, 6, 3910050499},
    {8, 7, 3346241981},
    // Small unaligned inputs
    {9, 1, 3855826643},
    {10, 2, 560880875},
    {11, 3, 1479707779},
    {12, 4, 2237687071},
    {13, 5, 4063855784},
    {14, 6, 2553454047},
    {15, 7, 1349220140},
    // Larger inputs to test leftover chunks at the end of aligned blocks
    {8, 8, 627613930},
    {8, 9, 2105929409},
    {8, 10, 2447068514},
    {8, 11, 863807079},
    {8, 12, 292050879},
    {8, 13, 1411837737},
    {8, 14, 2614515001},
    {8, 15, 3579076296},
    {8, 16, 2897079161},
    {8, 17, 675168386},
    // Much larger inputs
    {0, BUFFER_SIZE, 2096790750},
    {1, BUFFER_SIZE / 2, 3854797577},
};

void testCRC32C(
    std::function<uint32_t(const uint8_t*, size_t, uint32_t)> impl) {
  for (auto expected : expectedResults) {
    uint32_t result = impl(buffer + expected.offset, expected.length, ~0U);
    EXPECT_EQ(expected.crc32c, result);
  }
}

void testCRC32CContinuation(
    std::function<uint32_t(const uint8_t*, size_t, uint32_t)> impl) {
  for (auto expected : expectedResults) {
    size_t partialLength = expected.length / 2;
    uint32_t partialChecksum =
        impl(buffer + expected.offset, partialLength, ~0U);
    uint32_t result = impl(
        buffer + expected.offset + partialLength,
        expected.length - partialLength,
        partialChecksum);
    EXPECT_EQ(expected.crc32c, result);
  }
}

void testMatchesBoost32Type() {
  for (auto expected : expectedResults) {
    boost::crc_32_type result;
    result.process_bytes(buffer + expected.offset, expected.length);
    const uint32_t boostResult = result.checksum();
    const uint32_t follyResult =
        folly::crc32_type(buffer + expected.offset, expected.length);
    EXPECT_EQ(follyResult, boostResult);
  }
}

} // namespace

TEST(Checksum, crc32c_software) {
  testCRC32C(folly::detail::crc32c_sw);
}

TEST(Checksum, crc32c_continuation_software) {
  testCRC32CContinuation(folly::detail::crc32c_sw);
}

TEST(Checksum, crc32c_hardware) {
  if (folly::detail::crc32c_hw_supported()) {
    testCRC32C(folly::detail::crc32c_hw);
  } else {
    LOG(WARNING) << "skipping hardware-accelerated CRC-32C tests"
                 << " (not supported on this CPU)";
  }
}

TEST(Checksum, crc32c_hardware_eq) {
  if (folly::detail::crc32c_hw_supported()) {
    for (int i = 0; i < 1000; i++) {
      auto sw = folly::detail::crc32c_sw(buffer, i, 0);
      auto hw = folly::detail::crc32c_hw(buffer, i, 0);
      EXPECT_EQ(sw, hw);
    }
  } else {
    LOG(WARNING) << "skipping hardware-accelerated CRC-32C tests"
                 << " (not supported on this CPU)";
  }
}

TEST(Checksum, crc32c_continuation_hardware) {
  if (folly::detail::crc32c_hw_supported()) {
    testCRC32CContinuation(folly::detail::crc32c_hw);
  } else {
    LOG(WARNING) << "skipping hardware-accelerated CRC-32C tests"
                 << " (not supported on this CPU)";
  }
}

TEST(Checksum, crc32c_autodetect) {
  testCRC32C(folly::crc32c);
}

TEST(Checksum, crc32c_continuation_autodetect) {
  testCRC32CContinuation(folly::crc32c);
}

TEST(Checksum, crc32) {
  if (folly::detail::crc32c_hw_supported()) {
    // Just check that sw and hw match
    for (auto expected : expectedResults) {
      uint32_t sw_res =
          folly::detail::crc32_sw(buffer + expected.offset, expected.length, 0);
      uint32_t hw_res =
          folly::detail::crc32_hw(buffer + expected.offset, expected.length, 0);
      EXPECT_EQ(sw_res, hw_res);
    }
  } else {
    LOG(WARNING) << "skipping hardware-accelerated CRC-32 tests"
                 << " (not supported on this CPU)";
  }
}

TEST(Checksum, crc32_continuation) {
  if (folly::detail::crc32c_hw_supported()) {
    // Just check that sw and hw match
    for (auto expected : expectedResults) {
      auto halflen = expected.length / 2;
      uint32_t sw_res =
          folly::detail::crc32_sw(buffer + expected.offset, halflen, 0);
      sw_res = folly::detail::crc32_sw(
          buffer + expected.offset + halflen, halflen, sw_res);
      uint32_t hw_res =
          folly::detail::crc32_hw(buffer + expected.offset, halflen, 0);
      hw_res = folly::detail::crc32_hw(
          buffer + expected.offset + halflen, halflen, hw_res);
      EXPECT_EQ(sw_res, hw_res);
      uint32_t sw_res2 =
          folly::detail::crc32_sw(buffer + expected.offset, halflen * 2, 0);
      EXPECT_EQ(sw_res, sw_res2);
      uint32_t hw_res2 =
          folly::detail::crc32_hw(buffer + expected.offset, halflen * 2, 0);
      EXPECT_EQ(hw_res, hw_res2);
    }
  } else {
    LOG(WARNING) << "skipping hardware-accelerated CRC-32 tests"
                 << " (not supported on this CPU)";
  }
}

TEST(Checksum, crc32_type) {
  // Test that crc32_type matches boost::crc_32_type
  testMatchesBoost32Type();
}

TEST(Checksum, crc32_combine) {
  for (size_t totlen = 1024; totlen < BUFFER_SIZE; totlen += BUFFER_SIZE / 8) {
    auto mid = folly::Random::rand64(0, totlen);
    auto crc1 = folly::crc32(&buffer[0], mid, 0);
    auto crc2 = folly::crc32(&buffer[mid], totlen - mid, 0);
    auto crcfull = folly::crc32(&buffer[0], totlen, 0);
    auto combined = folly::crc32_combine(crc1, crc2, totlen - mid);
    EXPECT_EQ(combined, crcfull);
  }
}

TEST(Checksum, crc32c_combine) {
  for (size_t totlen = 1024; totlen < BUFFER_SIZE; totlen += BUFFER_SIZE / 8) {
    auto mid = folly::Random::rand64(0, totlen);
    auto crc1 = folly::crc32c(&buffer[0], mid, 0);
    auto crc2 = folly::crc32c(&buffer[mid], totlen - mid, 0);
    auto crcfull = folly::crc32c(&buffer[0], totlen, 0);
    auto combined = folly::crc32c_combine(crc1, crc2, totlen - mid);
    EXPECT_EQ(combined, crcfull);
  }
}

void benchmarkHardwareCRC32C(unsigned long iters, size_t blockSize) {
  if (folly::detail::crc32c_hw_supported()) {
    uint32_t checksum;
    for (unsigned long i = 0; i < iters; i++) {
      checksum = folly::detail::crc32c_hw(buffer, blockSize);
      folly::doNotOptimizeAway(checksum);
    }
  } else {
    LOG(WARNING) << "skipping hardware-accelerated CRC-32C benchmarks"
                 << " (not supported on this CPU)";
  }
}

void benchmarkSoftwareCRC32C(unsigned long iters, size_t blockSize) {
  uint32_t checksum;
  for (unsigned long i = 0; i < iters; i++) {
    checksum = folly::detail::crc32c_sw(buffer, blockSize);
    folly::doNotOptimizeAway(checksum);
  }
}

void benchmarkHardwareCRC32(unsigned long iters, size_t blockSize) {
  if (folly::detail::crc32_hw_supported()) {
    uint32_t checksum;
    for (unsigned long i = 0; i < iters; i++) {
      checksum = folly::detail::crc32_hw(buffer, blockSize);
      folly::doNotOptimizeAway(checksum);
    }
  } else {
    LOG(WARNING) << "skipping hardware-accelerated CRC-32 benchmarks"
                 << " (not supported on this CPU)";
  }
}

void benchmarkSoftwareCRC32(unsigned long iters, size_t blockSize) {
  uint32_t checksum;
  for (unsigned long i = 0; i < iters; i++) {
    checksum = folly::detail::crc32_sw(buffer, blockSize);
    folly::doNotOptimizeAway(checksum);
  }
}

void benchmarkCombineHardwareCrc32(unsigned long iters, size_t blockSize) {
  // Arbitrarily chosen checksums
  uint32_t checksum1 = 0xEDB88320;
  uint32_t checksum2 = 0x82F63B78;
  uint32_t result;
  for (unsigned long i = 0; i < iters; i++) {
    result = folly::crc32_combine(checksum1, checksum2, blockSize);
    folly::doNotOptimizeAway(result);
  }
}

void benchmarkCombineSoftwareLinear(unsigned long iters, size_t blockSize) {
  // Arbitrarily chosen checksums
  std::vector<uint8_t> zbuffer;
  zbuffer.reserve(blockSize);
  memset(zbuffer.data(), 0, blockSize);
  uint32_t checksum1 = 0xEDB88320;
  uint32_t checksum2 = 0x82F63B78;
  uint32_t result;
  for (unsigned long i = 0; i < iters; i++) {
    result = folly::crc32c(zbuffer.data(), blockSize, checksum1);
    result ^= checksum2;
    folly::doNotOptimizeAway(result);
  }
}

void benchmarkCombineHardwareCrc32c(unsigned long iters, size_t blockSize) {
  // Arbitrarily chosen checksums
  uint32_t checksum1 = 0xEDB88320;
  uint32_t checksum2 = 0x82F63B78;
  uint32_t result;
  for (unsigned long i = 0; i < iters; i++) {
    result = folly::crc32c_combine(checksum1, checksum2, blockSize);
    folly::doNotOptimizeAway(result);
  }
}

// This test fits easily in the L1 cache on modern server processors,
// and thus it mainly measures the speed of the checksum computation.
BENCHMARK(crc32c_hardware_1KB_block, iters) {
  benchmarkHardwareCRC32C(iters, 1024);
}

BENCHMARK(crc32c_software_1KB_block, iters) {
  benchmarkSoftwareCRC32C(iters, 1024);
}

BENCHMARK(crc32_hardware_1KB_block, iters) {
  benchmarkHardwareCRC32(iters, 1024);
}

BENCHMARK(crc32_software_1KB_block, iters) {
  benchmarkSoftwareCRC32(iters, 1024);
}

BENCHMARK_DRAW_LINE();

// This test is too big for the L1 cache but fits in L2
BENCHMARK(crc32c_hardware_64KB_block, iters) {
  benchmarkHardwareCRC32C(iters, 64 * 1024);
}

BENCHMARK(crc32c_software_64KB_block, iters) {
  benchmarkSoftwareCRC32C(iters, 64 * 1024);
}

BENCHMARK(crc32_hardware_64KB_block, iters) {
  benchmarkHardwareCRC32(iters, 64 * 1024);
}

BENCHMARK(crc32_software_64KB_block, iters) {
  benchmarkSoftwareCRC32(iters, 64 * 1024);
}

BENCHMARK_DRAW_LINE();

// This test is too big for the L2 cache but fits in L3
BENCHMARK(crc32c_hardware_512KB_block, iters) {
  benchmarkHardwareCRC32C(iters, 512 * 1024);
}

BENCHMARK(crc32c_software_512KB_block, iters) {
  benchmarkSoftwareCRC32C(iters, 512 * 1024);
}

BENCHMARK(crc32_hardware_512KB_block, iters) {
  benchmarkHardwareCRC32(iters, 512 * 1024);
}

BENCHMARK(crc32_software_512KB_block, iters) {
  benchmarkSoftwareCRC32(iters, 512 * 1024);
}

BENCHMARK_DRAW_LINE();

BENCHMARK(crc32_combine_linear_512KB_block, iters) {
  benchmarkCombineSoftwareLinear(iters, 512 * 1024);
}

BENCHMARK(crc32_combine_512KB_block, iters) {
  benchmarkCombineHardwareCrc32(iters, 512 * 1024);
}

BENCHMARK(crc32c_combine_512KB_block, iters) {
  benchmarkCombineHardwareCrc32c(iters, 512 * 1024);
}

int main(int argc, char** argv) {
  testing::InitGoogleTest(&argc, argv);
  gflags::ParseCommandLineFlags(&argc, &argv, true);

  // Populate a buffer with a deterministic pattern
  // on which to compute checksums
  const uint8_t* src = buffer;
  uint64_t* dst = (uint64_t*)buffer;
  const uint64_t* end = (const uint64_t*)(buffer + BUFFER_SIZE);
  *dst++ = 0;
  while (dst < end) {
    *dst++ = folly::hash::fnv64_buf((const char*)src, sizeof(uint64_t));
    src += sizeof(uint64_t);
  }

  auto ret = RUN_ALL_TESTS();
  if (!ret && FLAGS_benchmark) {
    folly::runBenchmarks();
  }
  return ret;
}


/****************************************************************************
 * Copyright (c) 2012-2019 by the ArborX authors                            *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the ArborX library. ArborX is                       *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 *                                                                          *
 * SPDX-License-Identifier: BSD-3-Clause                                    *
 ****************************************************************************/

#include "ArborX_BoostRTreeHelpers.hpp"
#include "ArborX_EnableDeviceTypes.hpp" // ARBORX_DEVICE_TYPES
#include <ArborX_DistributedSearchTree.hpp>

#include <boost/test/unit_test.hpp>

#include <algorithm>
#include <iostream>
#include <random>
#include <tuple>

#include "Search_UnitTestHelpers.hpp"
#include <mpi.h>

#define BOOST_TEST_MODULE DistributedSearchTree

BOOST_AUTO_TEST_CASE_TEMPLATE(hello_world, DeviceType, ARBORX_DEVICE_TYPES)
{
  MPI_Comm comm = MPI_COMM_WORLD;
  int comm_rank;
  MPI_Comm_rank(comm, &comm_rank);
  int comm_size;
  MPI_Comm_size(comm, &comm_size);

  int const n = 4;
  Kokkos::View<ArborX::Point *, DeviceType> points("points", n);
  // [  rank 0       [  rank 1       [  rank 2       [  rank 3       [
  // x---x---x---x---x---x---x---x---x---x---x---x---x---x---x---x---
  // ^   ^   ^   ^
  // 0   1   2   3   ^   ^   ^   ^
  //                 0   1   2   3   ^   ^   ^   ^
  //                                 0   1   2   3   ^   ^   ^   ^
  //                                                 0   1   2   3
  using ExecutionSpace = typename DeviceType::execution_space;
  Kokkos::parallel_for(Kokkos::RangePolicy<ExecutionSpace>(0, n),
                       KOKKOS_LAMBDA(int i) {
                         points(i) = {{(double)i / n + comm_rank, 0., 0.}};
                       });

  ArborX::DistributedSearchTree<DeviceType> tree(comm, points);

  // 0---0---0---0---1---1---1---1---2---2---2---2---3---3---3---3---
  // |               |               |               |               |
  // |               |               |               x   x   x   x   |
  // |               |               |               |<------0------>|
  // |               |               x   x   x   x   x               |
  // |               |               |<------1------>|               |
  // |               x   x   x   x   x               |               |
  // |               |<------2------>|               |               |
  // x   x   x   x   x               |               |               |
  // |<------3------>|               |               |               |
  // |               |               |               |               |
  Kokkos::View<ArborX::Within *, DeviceType> queries("queries", 1);
  auto queries_host = Kokkos::create_mirror_view(queries);
  queries_host(0) =
      ArborX::within({{0.5 + comm_size - 1 - comm_rank, 0., 0.}}, 0.5);
  deep_copy(queries, queries_host);

  // 0---0---0---0---1---1---1---1---2---2---2---2---3---3---3---3---
  // |               |               |               |               |
  // |               |               |           x   x   x           |
  // |               |           x   x   x        <--0-->            |
  // |           x   x   x        <--1-->            |               |
  // x   x        <--2-->            |               |               |
  // 3-->            |               |               |               |
  // |               |               |               |               |
  Kokkos::View<ArborX::Nearest<ArborX::Point> *, DeviceType> nearest_queries(
      "nearest_queries", 1);
  auto nearest_queries_host = Kokkos::create_mirror_view(nearest_queries);
  nearest_queries_host(0) = ArborX::nearest<ArborX::Point>(
      {{0.0 + comm_size - 1 - comm_rank, 0., 0.}},
      comm_rank < comm_size - 1 ? 3 : 2);
  deep_copy(nearest_queries, nearest_queries_host);

  std::vector<int> indices_ref;
  std::vector<int> ranks_ref;
  for (int i = 0; i < n; ++i)
  {
    indices_ref.push_back(n - 1 - i);
    ranks_ref.push_back(comm_size - 1 - comm_rank);
  }
  if (comm_rank > 0)
  {
    indices_ref.push_back(0);
    ranks_ref.push_back(comm_size - comm_rank);
    checkResults(tree, queries, indices_ref, {0, n + 1}, ranks_ref);
  }
  else
  {
    checkResults(tree, queries, indices_ref, {0, n}, ranks_ref);
  }

  BOOST_TEST(n > 2);
  if (comm_rank < comm_size - 1)
  {
    checkResults(tree, nearest_queries, {0, n - 1, 1}, {0, 3},
                 {comm_size - 1 - comm_rank, comm_size - 2 - comm_rank,
                  comm_size - 1 - comm_rank});
  }
  else
  {
    checkResults(tree, nearest_queries, {0, 1}, {0, 2},
                 {comm_size - 1 - comm_rank, comm_size - 1 - comm_rank});
  }
}

BOOST_AUTO_TEST_CASE_TEMPLATE(empty_tree, DeviceType, ARBORX_DEVICE_TYPES)
{
  MPI_Comm comm = MPI_COMM_WORLD;
  int comm_rank;
  MPI_Comm_rank(comm, &comm_rank);
  int comm_size;
  MPI_Comm_size(comm, &comm_size);

  auto const emptry_dist_tree = makeDistributedSearchTree<DeviceType>(comm, {});

  BOOST_TEST(emptry_dist_tree.empty());
  BOOST_TEST(emptry_dist_tree.size() == 0);

  BOOST_TEST(ArborX::Details::equals(emptry_dist_tree.bounds(), {}));

  checkResults(emptry_dist_tree, makeOverlapQueries<DeviceType>({}), {}, {0},
               {});

  checkResults(emptry_dist_tree, makeWithinQueries<DeviceType>({}), {}, {0},
               {});

  checkResults(emptry_dist_tree, makeNearestQueries<DeviceType>({}), {}, {0},
               {});

  checkResults(emptry_dist_tree, makeNearestQueries<DeviceType>({}), {}, {0},
               {}, {});

  // Only rank 0 has a couple spatial queries with a spatial predicate
  if (comm_rank == 0)
    checkResults(emptry_dist_tree,
                 makeOverlapQueries<DeviceType>({
                     {},
                     {},
                 }),
                 {}, {0, 0, 0}, {});
  else
    checkResults(emptry_dist_tree, makeOverlapQueries<DeviceType>({}), {}, {0},
                 {});

  // All ranks but rank 0 have a single query with a spatial predicate
  if (comm_rank == 0)
    checkResults(emptry_dist_tree, makeWithinQueries<DeviceType>({}), {}, {0},
                 {});
  else
    checkResults(emptry_dist_tree,
                 makeWithinQueries<DeviceType>({
                     {{{(double)comm_rank, 0., 0.}}, (double)comm_size},
                 }),
                 {}, {0, 0}, {});

  // All ranks but rank 0 have a single query with a nearest predicate
  if (comm_rank == 0)
    checkResults(emptry_dist_tree, makeNearestQueries<DeviceType>({}), {}, {0},
                 {});
  else
    checkResults(emptry_dist_tree,
                 makeNearestQueries<DeviceType>({
                     {{{0., 0., 0.}}, comm_rank},
                 }),
                 {}, {0, 0}, {});

  // All ranks have a single query with a nearest predicate (this version
  // returns distances as well)
  checkResults(emptry_dist_tree,
               makeNearestQueries<DeviceType>({
                   {{{0., 0., 0.}}, comm_size},
               }),
               {}, {0, 0}, {}, {});
}

BOOST_AUTO_TEST_CASE_TEMPLATE(unique_leaf_on_rank_0, DeviceType,
                              ARBORX_DEVICE_TYPES)
{
  MPI_Comm comm = MPI_COMM_WORLD;
  int comm_rank;
  MPI_Comm_rank(comm, &comm_rank);
  int comm_size;
  MPI_Comm_size(comm, &comm_size);

  // tree has one unique leaf that lives on rank 0
  auto const tree =
      (comm_rank == 0 ? makeDistributedSearchTree<DeviceType>(
                            comm,
                            {
                                {{{0., 0., 0.}}, {{1., 1., 1.}}},
                            })
                      : makeDistributedSearchTree<DeviceType>(comm, {}));

  BOOST_TEST(!tree.empty());
  BOOST_TEST(tree.size() == 1);

  BOOST_TEST(
      ArborX::Details::equals(tree.bounds(), {{{0., 0., 0.}}, {{1., 1., 1.}}}));

  checkResults(tree, makeOverlapQueries<DeviceType>({}), {}, {0}, {});

  checkResults(tree, makeWithinQueries<DeviceType>({}), {}, {0}, {});

  checkResults(tree, makeNearestQueries<DeviceType>({}), {}, {0}, {});

  checkResults(tree, makeNearestQueries<DeviceType>({}), {}, {0}, {}, {});

  // Querying for more neighbors than there are leaves in the tree
  checkResults(tree,
               makeNearestQueries<DeviceType>({
                   {{{(double)comm_rank, (double)comm_rank, (double)comm_rank}},
                    comm_size},
               }),
               {0}, {0, 1}, {0});
}

BOOST_AUTO_TEST_CASE_TEMPLATE(one_leaf_per_rank, DeviceType,
                              ARBORX_DEVICE_TYPES)
{
  MPI_Comm comm = MPI_COMM_WORLD;
  int comm_rank;
  MPI_Comm_rank(comm, &comm_rank);
  int comm_size;
  MPI_Comm_size(comm, &comm_size);

  // tree has one leaf per rank
  auto const tree = makeDistributedSearchTree<DeviceType>(
      comm,
      {
          {{{(double)comm_rank, 0., 0.}}, {{(double)comm_rank + 1., 1., 1.}}},
      });

  BOOST_TEST(!tree.empty());
  BOOST_TEST((int)tree.size() == comm_size);

  BOOST_TEST(ArborX::Details::equals(
      tree.bounds(), {{{0., 0., 0.}}, {{(double)comm_size, 1., 1.}}}));

  checkResults(tree,
               makeOverlapQueries<DeviceType>({
                   {{{(double)comm_size - (double)comm_rank - .5, .5, .5}},
                    {{(double)comm_size - (double)comm_rank - .5, .5, .5}}},
                   {{{(double)comm_rank + .5, .5, .5}},
                    {{(double)comm_rank + .5, .5, .5}}},
               }),
               {0, 0}, {0, 1, 2}, {comm_size - 1 - comm_rank, comm_rank});

  checkResults(tree, makeNearestQueries<DeviceType>({}), {}, {0}, {});
  checkResults(tree, makeOverlapQueries<DeviceType>({}), {}, {0}, {});

  if (comm_rank > 0)
    checkResults(tree,
                 makeNearestQueries<DeviceType>({
                     {{{0., 0., 0.}}, comm_rank * comm_size},
                 }),
                 std::vector<int>(comm_size, 0), {0, comm_size}, [comm_size]() {
                   std::vector<int> r(comm_size);
                   std::iota(begin(r), end(r), 0);
                   return r;
                 }());
  else
    checkResults(tree,
                 makeNearestQueries<DeviceType>({
                     {{{0., 0., 0.}}, comm_rank * comm_size},
                 }),
                 {}, {0, 0}, {});
}

BOOST_AUTO_TEST_CASE_TEMPLATE(non_approximate_nearest_neighbors, DeviceType,
                              ARBORX_DEVICE_TYPES)
{
  MPI_Comm comm = MPI_COMM_WORLD;
  int comm_rank;
  MPI_Comm_rank(comm, &comm_rank);
  int comm_size;
  MPI_Comm_size(comm, &comm_size);

  //  +----------0----------1----------2----------3
  //  |          |          |          |          |
  //  |          |          |          |          |
  //  |          |          |          |          |
  //  |          |          |          |          |
  //  0----------1----------2----------3----------+
  //  [  rank 0  ]
  //             [  rank 1  ]
  //                        [  rank 2  ]
  //                                   [  rank 3  ]
  auto const tree = makeDistributedSearchTree<DeviceType>(
      comm, {
                {{{(double)comm_rank, 0., 0.}}, {{(double)comm_rank, 0., 0.}}},
                {{{(double)comm_rank + 1., 1., 1.}},
                 {{(double)comm_rank + 1., 1., 1.}}},
            });

  BOOST_TEST(!tree.empty());
  BOOST_TEST((int)tree.size() == 2 * comm_size);

  //  +----------0----------1----------2----------3
  //  |          |          |          |          |
  //  |          |          |          |          |
  //  |          |          |          |          |
  //  |          |          |          |          |
  //  0-------x--1-------X--2-------X--3-------X--+
  //          ^          ^          ^          ^
  //          3          2          1          0
  if (comm_rank > 0)
    checkResults(tree,
                 makeNearestQueries<DeviceType>({
                     {{{(double)(comm_size - 1 - comm_rank) + .75, 0., 0.}}, 1},
                 }),
                 {0}, {0, 1}, {comm_size - comm_rank});
  else
    checkResults(tree,
                 makeNearestQueries<DeviceType>({
                     {{{(double)(comm_size - 1 - comm_rank) + .75, 0., 0.}}, 1},
                 }),
                 {0}, {0, 1}, {comm_size - 1});
}

std::vector<std::array<double, 3>>
make_random_cloud(double const Lx, double const Ly, double const Lz,
                  int const n, double const seed)
{
  std::vector<std::array<double, 3>> cloud(n);
  std::default_random_engine generator(seed);
  std::uniform_real_distribution<double> distribution_x(0.0, Lx);
  std::uniform_real_distribution<double> distribution_y(0.0, Ly);
  std::uniform_real_distribution<double> distribution_z(0.0, Lz);
  for (int i = 0; i < n; ++i)
  {
    double x = distribution_x(generator);
    double y = distribution_y(generator);
    double z = distribution_z(generator);
    cloud[i] = {{x, y, z}};
  }
  return cloud;
}

BOOST_AUTO_TEST_CASE_TEMPLATE(boost_comparison, DeviceType, ARBORX_DEVICE_TYPES)
{
  MPI_Comm comm = MPI_COMM_WORLD;
  int comm_rank;
  MPI_Comm_rank(comm, &comm_rank);
  int comm_size;
  MPI_Comm_size(comm, &comm_size);

  // Construct a random cloud of point. We use the same seed on all the
  // processors.
  double const Lx = 10.0;
  double const Ly = 10.0;
  double const Lz = 10.0;
  int const n = 100;
  auto cloud = make_random_cloud(Lx, Ly, Lz, n, 0);
  auto queries = make_random_cloud(Lx, Ly, Lz, n, 1234);

  // The formula is a bit complicated but it does not require n be divisible
  // by comm_size
  int const local_n = (n + comm_size - 1 - comm_rank) / comm_size;
  Kokkos::View<ArborX::Box *, DeviceType> bounding_boxes("bounding_boxes",
                                                         local_n);
  auto bounding_boxes_host = Kokkos::create_mirror_view(bounding_boxes);
  for (int i = 0; i < n; ++i)
  {
    if (i % comm_size == comm_rank)
    {
      auto const &point = cloud[i];
      double const x = std::get<0>(point);
      double const y = std::get<1>(point);
      double const z = std::get<2>(point);
      bounding_boxes_host[i / comm_size] = {{{x, y, z}}, {{x, y, z}}};
    }
  }
  Kokkos::deep_copy(bounding_boxes, bounding_boxes_host);

  // Initialize the distributed search tree
  ArborX::DistributedSearchTree<DeviceType> distributed_tree(comm,
                                                             bounding_boxes);

  auto rtree = BoostRTreeHelpers::makeRTree(comm, bounding_boxes_host);

  // make queries
  using ExecutionSpace = typename DeviceType::execution_space;
  Kokkos::View<double * [3], ExecutionSpace> point_coords("point_coords",
                                                          local_n);
  auto point_coords_host = Kokkos::create_mirror_view(point_coords);
  Kokkos::View<double *, ExecutionSpace> radii("radii", local_n);
  auto radii_host = Kokkos::create_mirror_view(radii);
  Kokkos::View<int * [2], ExecutionSpace> within_n_pts("within_n_pts", local_n);
  std::default_random_engine generator(0);
  std::uniform_real_distribution<double> distribution_radius(
      0.0, std::sqrt(Lx * Lx + Ly * Ly + Lz * Lz));
  std::uniform_int_distribution<int> distribution_k(1, std::floor(sqrt(n * n)));
  for (int i = 0; i < n; ++i)
  {
    if (i % comm_size == comm_rank)
    {
      auto const &point = queries[i];
      int const j = i / comm_size;
      double const x = std::get<0>(point);
      double const y = std::get<1>(point);
      double const z = std::get<2>(point);
      radii_host(j) = distribution_radius(generator);

      point_coords_host(j, 0) = x;
      point_coords_host(j, 1) = y;
      point_coords_host(j, 2) = z;
    }
  }
  Kokkos::deep_copy(point_coords, point_coords_host);
  Kokkos::deep_copy(radii, radii_host);

  Kokkos::View<ArborX::Within *, DeviceType> within_queries("within_queries",
                                                            local_n);
  Kokkos::parallel_for(
      "register_within_queries",
      Kokkos::RangePolicy<ExecutionSpace>(0, local_n), KOKKOS_LAMBDA(int i) {
        within_queries(i) = ArborX::within(
            {{point_coords(i, 0), point_coords(i, 1), point_coords(i, 2)}},
            radii(i));
      });
  Kokkos::fence();

  // Perform the search
  Kokkos::View<int *, DeviceType> indices("indices", 0);
  Kokkos::View<int *, DeviceType> offset("offset", 0);
  Kokkos::View<int *, DeviceType> ranks("ranks", 0);
  distributed_tree.query(within_queries, indices, offset, ranks);
  auto indices_host = Kokkos::create_mirror_view(indices);
  Kokkos::deep_copy(indices_host, indices);
  auto offset_host = Kokkos::create_mirror_view(offset);
  Kokkos::deep_copy(offset_host, offset);
  auto ranks_host = Kokkos::create_mirror_view(ranks);
  Kokkos::deep_copy(ranks_host, ranks);
  auto bvh_results = std::make_tuple(offset_host, indices_host, ranks_host);

  auto within_queries_host = Kokkos::create_mirror_view(within_queries);
  Kokkos::deep_copy(within_queries_host, within_queries);
  auto rtree_results =
      BoostRTreeHelpers::performQueries(rtree, within_queries_host);

  validateResults(bvh_results, rtree_results);
}


//==================================================================================================
/*
  Copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
//! [transform-binary]
#include <boost/simd/algorithm/transform.hpp>
#include <iostream>
#include <vector>

struct f
{
  template<typename T> T operator()(T const& a, T const& b) const { return b/a; }
};

int main()
{
  std::vector<float> d{1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f};
  std::vector<float> e{0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f};
  std::vector<float> out(7);

  boost::simd::transform( d.data(), d.data()+7, e.data(), out.data(), f{});

  for(auto x : out )
    std::cout << x << " ";

  return 0;
}
//! [transform-binary]


//display kinect depth in real-time
//#define INFO
#define TIMER
#define _USE_MATH_DEFINES
#include <GL/glew.h>

#include <cuda_gl_interop.h>
#include <cuda_runtime_api.h>

#ifdef __gnu_linux__
#include <sys/types.h>
#include <sys/stat.h>
#elif _WIN32
#include <direct.h>
#else
#error "OS not supported!"
#endif
#include <iostream>
#include <string>
#include <vector>

#include <boost/scoped_ptr.hpp>
#include <boost/filesystem.hpp>

#include <opencv2/core.hpp>
#include <opencv2/cudaarithm.hpp>

#include <Eigen/Dense>
//camera calibration from a sequence of images
#include <opencv2/cudaarithm.hpp>
#include <OpenNI.h>
#include "Kinect.h"
#include "GLUtil.hpp"
#include <map>
#include "Camera.h"
#include "VideoSourceKinect.hpp"

//Qt
#include <QGLViewer/qglviewer.h>
#include "Data4Viewer.h"
#include "DataLive.h"

using namespace std;
using namespace cv;
using namespace Eigen;
using namespace qglviewer;
DataLive::DataLive()
:Data4Viewer(){
	_bRepeat = false;// repeatedly play the sequence
	_nStatus = 01;//1 restart; 2 //recording continue 3://pause 4://dump
	_nMethodIdx = 0;
}

void DataLive::loadFromYml(){
	_uResolution = 0;
	_Cw = Vector3d(1,1,1);
	_cam_param_path = string("..\\data\\Xtion");
}

void DataLive::reset(){
	//for testing different oni files
	_nStatus = 9;
	_pGL.reset();
	_pGL.reset( new btl::gl_util::CGLUtil(_uResolution,_uPyrHeight) );
	_pGL->init();
	_pGL->constructVBOsPBOs();
	_pKinect.reset();

	_pKinect.reset( new btl::kinect::VideoSourceKinect(_uResolution,_uPyrHeight,true,_Cw,_cam_param_path) );
	using namespace btl::kinect;
	_pKinect->initKinect();

	int nn = 0;
	bool bIsSuccessful = false;
	while (!bIsSuccessful&&nn < 20){
		bIsSuccessful = _pKinect->getNextFrame(&_nStatus);
		nn++;
	}

	return;
}

void DataLive::updatePF(){
	//int64 A = getTickCount();
	using btl::kinect::VideoSourceKinect;

	//load data from video source and model
	if( !_pKinect->getNextFrame(&_nStatus) ) return;
	return;
}


// Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2007-2008 Steven Watanabe
//
// 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)

#ifndef BOOST_UNITS_DIMENSION_HPP
#define BOOST_UNITS_DIMENSION_HPP

#include <boost/static_assert.hpp>

#include <boost/type_traits/is_same.hpp>

#include <boost/mpl/arithmetic.hpp>

#include <boost/units/static_rational.hpp>
#include <boost/units/detail/dimension_list.hpp>
#include <boost/units/detail/dimension_impl.hpp>

/// \file
/// \brief Core metaprogramming utilities for compile-time dimensional analysis.

namespace boost {

namespace units {

/// Reduce dimension list to cardinal form. This algorithm collapses duplicate
/// base dimension tags and sorts the resulting list by the tag ordinal value.
/// Dimension lists that resolve to the same dimension are guaranteed to be
/// represented by an identical type.
///
/// The argument should be an MPL forward sequence containing instances
/// of the @c dim template.
///
/// The result is also an MPL forward sequence.  It also supports the
/// following metafunctions to allow use as a dimension.
///
///    - @c mpl::plus is defined only on two equal dimensions and returns the argument unchanged.
///    - @c mpl::minus is defined only for two equal dimensions and returns the argument unchanged.
///    - @c mpl::negate will return its argument unchanged.
///    - @c mpl::times is defined for any dimensions and adds corresponding exponents.
///    - @c mpl::divides is defined for any dimensions and subtracts the exponents of the
///         right had argument from the corresponding exponents of the left had argument.
///         Missing base dimension tags are assumed to have an exponent of zero.
///    - @c static_power takes a dimension and a static_rational and multiplies all
///         the exponents of the dimension by the static_rational.
///    - @c static_root takes a dimension and a static_rational and divides all
///         the exponents of the dimension by the static_rational.
template<typename Seq>
struct make_dimension_list
{
    typedef typename detail::sort_dims<Seq>::type type;
};

/// Raise a dimension list to a scalar power.
template<typename DL,typename Ex>
struct static_power
{
    typedef typename detail::static_power_impl<DL::size::value>::template apply<
        DL,
        Ex
    >::type type;
};

/// Take a scalar root of a dimension list.
template<typename DL,typename Rt>
struct static_root
{
    typedef typename detail::static_root_impl<DL::size::value>::template apply<
        DL,
        Rt
    >::type type;
};

} // namespace units

#ifndef BOOST_UNITS_DOXYGEN

namespace mpl {

template<>
struct plus_impl<boost::units::detail::dimension_list_tag,boost::units::detail::dimension_list_tag>
{
    template<class T0, class T1>
    struct apply
    {
        BOOST_STATIC_ASSERT((boost::is_same<T0,T1>::value == true));
        typedef T0 type;
    };
};

template<>
struct minus_impl<boost::units::detail::dimension_list_tag,boost::units::detail::dimension_list_tag>
{
    template<class T0, class T1>
    struct apply
    {
        BOOST_STATIC_ASSERT((boost::is_same<T0,T1>::value == true));
        typedef T0 type;
    };
};

template<>
struct times_impl<boost::units::detail::dimension_list_tag,boost::units::detail::dimension_list_tag>
{
    template<class T0, class T1>
    struct apply
    {
        typedef typename boost::units::detail::merge_dimensions<T0,T1>::type type;
    };
};

template<>
struct divides_impl<boost::units::detail::dimension_list_tag,boost::units::detail::dimension_list_tag>
{
    template<class T0, class T1>
    struct apply
    {
        typedef typename boost::units::detail::merge_dimensions<
            T0,
            typename boost::units::detail::static_inverse_impl<
                T1::size::value
            >::template apply<
                T1
            >::type
        >::type type;
    };
};

template<>
struct negate_impl<boost::units::detail::dimension_list_tag>
{
    template<class T0>
    struct apply
    {
        typedef T0 type;
    };
};

} // namespace mpl

#endif

} // namespace boost

#endif // BOOST_UNITS_DIMENSION_HPP


/* (c) 2016, 2021 FFF Services. For details refers to LICENSE.txt */
/*
 * Copyright (c) 2015 Cryptonomex, Inc., and contributors.
 *
 * The MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#include <graphene/chain/protocol/asset.hpp>
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>

namespace graphene { namespace chain {
      typedef boost::multiprecision::uint128_t uint128_t;
      typedef boost::multiprecision::int128_t  int128_t;

      bool operator == ( const price& a, const price& b )
      {
         if( std::tie( a.base.asset_id, a.quote.asset_id ) != std::tie( b.base.asset_id, b.quote.asset_id ) )
             return false;

         const auto amult = uint128_t( b.quote.amount.value ) * a.base.amount.value;
         const auto bmult = uint128_t( a.quote.amount.value ) * b.base.amount.value;

         return amult == bmult;
      }

      bool operator < ( const price& a, const price& b )
      {
         if( a.base.asset_id < b.base.asset_id ) return true;
         if( a.base.asset_id > b.base.asset_id ) return false;
         if( a.quote.asset_id < b.quote.asset_id ) return true;
         if( a.quote.asset_id > b.quote.asset_id ) return false;

         const auto amult = uint128_t( b.quote.amount.value ) * a.base.amount.value;
         const auto bmult = uint128_t( a.quote.amount.value ) * b.base.amount.value;

         return amult < bmult;
      }

      bool operator <= ( const price& a, const price& b )
      {
         return (a == b) || (a < b);
      }

      bool operator != ( const price& a, const price& b )
      {
         return !(a == b);
      }

      bool operator > ( const price& a, const price& b )
      {
         return !(a <= b);
      }

      bool operator >= ( const price& a, const price& b )
      {
         return !(a < b);
      }

      asset operator * ( const asset& a, const price& b )
      {
         if( a.asset_id == b.base.asset_id )
         {
            FC_ASSERT( b.base.amount.value > 0 );
            uint128_t result = (uint128_t(a.amount.value) * b.quote.amount.value)/b.base.amount.value;
            FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY );
            return asset( result.convert_to<int64_t>(), b.quote.asset_id );
         }
         else if( a.asset_id == b.quote.asset_id )
         {
            FC_ASSERT( b.quote.amount.value > 0 );
            uint128_t result = (uint128_t(a.amount.value) * b.base.amount.value)/b.quote.amount.value;
            FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY );
            return asset( result.convert_to<int64_t>(), b.base.asset_id );
         }
         FC_THROW_EXCEPTION( fc::assert_exception, "invalid asset * price", ("asset",a)("price",b) );
      }

      price operator / ( const asset& base, const asset& quote )
      { try {
         FC_ASSERT( base.asset_id != quote.asset_id );
         return price{base,quote};
      } FC_CAPTURE_AND_RETHROW( (base)(quote) ) }

      price price::max( asset_id_type base, asset_id_type quote ) { return asset( share_type(GRAPHENE_MAX_SHARE_SUPPLY), base ) / asset( share_type(1), quote); }
      price price::min( asset_id_type base, asset_id_type quote ) { return asset( 1, base ) / asset( GRAPHENE_MAX_SHARE_SUPPLY, quote); }

      bool price::is_null() const { return *this == price(); }

      void price::validate() const
      { try {
         FC_ASSERT( base.amount > share_type(0) );
         FC_ASSERT( quote.amount > share_type(0) );
         FC_ASSERT( base.asset_id != quote.asset_id );
      } FC_CAPTURE_AND_RETHROW( (base)(quote) ) }

      bool price_feed::is_for( asset_id_type asset_id ) const
      {
         try
         {
            if( !core_exchange_rate.is_null() )
               return (core_exchange_rate.base.asset_id == asset_id);
            // (null, null) is valid for any feed
            return true;
         }
         FC_CAPTURE_AND_RETHROW( (*this) )
      }

// compile-time table of powers of 10 using template metaprogramming

template< int N >
struct p10
{
   static const int64_t v = 10 * p10<N-1>::v;
};

template<>
struct p10<0>
{
   static const int64_t v = 1;
};

const int64_t scaled_precision_lut[19] =
{
   p10<  0 >::v, p10<  1 >::v, p10<  2 >::v, p10<  3 >::v,
   p10<  4 >::v, p10<  5 >::v, p10<  6 >::v, p10<  7 >::v,
   p10<  8 >::v, p10<  9 >::v, p10< 10 >::v, p10< 11 >::v,
   p10< 12 >::v, p10< 13 >::v, p10< 14 >::v, p10< 15 >::v,
   p10< 16 >::v, p10< 17 >::v, p10< 18 >::v
};

} } // graphene::chain


// __BEGIN_LICENSE__
//  Copyright (c) 2006-2012, United States Government as represented by the
//  Administrator of the National Aeronautics and Space Administration. All
//  rights reserved.
//
//  The NASA Vision Workbench is licensed under the Apache License,
//  Version 2.0 (the "License"); you may not use this file except in
//  compliance with the License. You may obtain a copy of the License at
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// __END_LICENSE__

#ifdef _MSC_VER
#pragma warning(disable:4244)
#pragma warning(disable:4267)
#pragma warning(disable:4996)
#endif

#include <cstdlib>
#include <iostream>
#include <cmath>
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/foreach.hpp>
namespace fs = boost::filesystem;
namespace po = boost::program_options;

#include <vw/Core/Functors.h>
#include <vw/Image/Algorithms.h>
#include <vw/Image/ImageMath.h>
#include <vw/Image/ImageViewRef.h>
#include <vw/Image/PerPixelViews.h>
#include <vw/Image/PixelMask.h>
#include <vw/Image/MaskViews.h>
#include <vw/Image/PixelTypes.h>
#include <vw/Image/Statistics.h>
#include <vw/FileIO/DiskImageView.h>
#include <vw/Cartography/GeoReference.h>
#include <vw/tools/Common.h>
#include <vw/FileIO/DiskImageResourceGDAL.h>
#include <vw/Image/Interpolation.h>
#include <asp/Core/Macros.h>
#include <asp/Core/Common.h>

using namespace vw;
using namespace vw::cartography;
using namespace std;

struct Options : asp::BaseOptions {};

/// Find the mean and std dev DEM of the given input sets of DEMs.
/// Also output count.tif, showing for each pixel how many times
/// it was encountered in the stack of DEMs.

int main( int argc, char *argv[] ){

  try {
    ImageView<double> mean_dem, std_dev_dem, count_dem;
    GeoReference georef;
    double nodata_val = numeric_limits<double>::quiet_NaN();

    if (argc <= 1){
      vw_throw(ArgumentErr() << "Missing input files.\n"
               << "Usage: " << argv[0] << " <dems>\n");
    }

    int start = 1;
    for (int i = start; i < argc; i++){
      std::string curr_file = argv[i];
      std::cout << "Reading: " << curr_file << std::endl;

      DiskImageResourceGDAL in_rsrc(curr_file);
      double curr_nodata_val = numeric_limits<double>::quiet_NaN();
      if ( in_rsrc.has_nodata_read() ) {
        curr_nodata_val = in_rsrc.nodata_read();
        vw_out() << "\tFound input nodata value: " << curr_nodata_val << std::endl;
      }else{
        vw_out() << "Nodata value not found in: " << curr_file << std::endl;
      }

      GeoReference curr_georef;
      read_georeference(curr_georef, in_rsrc);

      DiskImageView<float> curr_dem(in_rsrc);
      ImageViewRef< PixelMask<float> > masked_dem = create_mask(curr_dem, curr_nodata_val);

      InterpolationView<EdgeExtensionView< ImageViewRef < PixelMask<float> >, ConstantEdgeExtension>, BilinearInterpolation> masked_dem_interp = interpolate(masked_dem);

      if (i == start){
        mean_dem.set_size    ( curr_dem.cols(), curr_dem.rows() );
        std_dev_dem.set_size ( curr_dem.cols(), curr_dem.rows() );
        count_dem.set_size   ( curr_dem.cols(), curr_dem.rows() );
        georef = curr_georef;
        nodata_val = curr_nodata_val;
      }

      for (int col = 0; col < mean_dem.cols(); col++){
        for (int row = 0; row < mean_dem.rows(); row++){
          Vector2 pix(col, row);

          if (i != start){
            pix = curr_georef.lonlat_to_pixel(georef.pixel_to_lonlat(pix));
          }

          double x = pix[0], y = pix[1];
          double interp_val;
          bool is_in_box = ( 0 <= x && x <= masked_dem_interp.cols() - 1 &&
                             0 <= y && y <= masked_dem_interp.rows() - 1 );
          if (!is_in_box) continue;

          // The "if" statement below is to work around a bug in
          // interpolation with PixelMask.
          PixelMask<float> val;
          if (x == col && y == row)
            val = masked_dem(col, row);
          else
            val = masked_dem_interp(x, y);
          if (!is_valid(val)) continue;
          interp_val = val.child();

          mean_dem    (col, row) += interp_val;
          std_dev_dem (col, row) += interp_val*interp_val;
          count_dem   (col, row) += 1;
        }

      }
    }

    for (int col = 0; col < mean_dem.cols(); col++){
      for (int row = 0; row < mean_dem.rows(); row++){

        if (count_dem (col, row) == 0){
          mean_dem    (col, row) = nodata_val;
          std_dev_dem (col, row) = nodata_val;
          count_dem   (col, row) = nodata_val;
          continue;
        }

        double mean    = mean_dem(col, row)/count_dem(col, row);
        double std_dev = sqrt( std_dev_dem(col, row)/count_dem(col, row) - mean*mean );

        mean_dem    (col, row) = mean;
        std_dev_dem (col, row) = std_dev;
      }
    }

    Options opt;
    std::string mean_file = "mean.tif";
    std::cout << "Writing: " << mean_file << std::endl;
    asp::block_write_gdal_image(mean_file, pixel_cast<float>(mean_dem),
                                georef, nodata_val, opt);

    std::string std_dev_file = "std_dev.tif";
    std::cout << "Writing: " << std_dev_file << std::endl;
    asp::block_write_gdal_image(std_dev_file, pixel_cast<float>(std_dev_dem),
                                georef, nodata_val, opt);

    std::string count_file = "count.tif";
    std::cout << "Writing: " << count_file << std::endl;
    asp::block_write_gdal_image(count_file, pixel_cast<float>(count_dem),
                                georef, nodata_val, opt);

  } ASP_STANDARD_CATCHES;

  return 0;
}