contract Heaven3D is modularLong {
    using SafeMath for *;
    using NameFilter for string;
    using H3DKeysCalcLong for uint256;
	
	TeamDreamHubInterface public TeamDreamHub_;
	PlayerBookInterface public PlayerBook;
//==============================================================================
//     _ _  _  |`. _     _ _ |_ | _  _  .
//    (_(_)| |~|~|(_||_|| (_||_)|(/__\  .  (game settings)
//=================_|===========================================================
    string constant public name = "Heaven3D Official";
    string constant public symbol = "H3D";
	address private owner;
	uint256 constant private rndExtra_ = 0 hours;     // length of the very first ICO 
    uint256 constant private rndGap_ = 0 hours;         // length of ICO phase, set to 1 year for EOS.
    uint256 constant private rndInit_ = 1 hours;                // round timer starts at this
    uint256 constant private rndInc_ = 30 seconds;              // every full key purchased adds this much to the timer
	uint256 constant private rndDeciExt_ = 360 seconds;              // round extension time decide by random decision
    uint256 constant private rndMax_ = 24 hours;                // max length a round timer can be
	
	uint256 constant private rule_limit_latestPlayersCnt = 10; 	// should smaller than latestPlayers.length
	uint256 constant private rule_limit_heavyPlayersCnt = 10; 	// should smaller than heavyPlayers.length
//==============================================================================
//     _| _ _|_ _    _ _ _|_    _   .
//    (_|(_| | (_|  _\(/_ | |_||_)  .  (data used to store game info that changes)
//=============================|================================================
	uint256 public airDropPot_;             // person who gets the airdrop wins part of this pot
	uint256 public airDropTracker_ = 0;     // incremented each time a "qualified" tx occurs.  used to determine winning air drop
    uint256 public rID_;    // round id number / total rounds that have happened
//****************
// FLOW CONTROL
//****************	
	bool public noMoreNextRound_ = false; 	// if this flag enabled, in the end of the round the developers are going to update the smart contract of the game, in order to perfect players' gaming experience.
	uint256 public randomDecisionPhase_ = 100;
	bool private endRoundDecisionResult_ = false;
	address private address_of_last_rand_gen_source_ = address(0);
	mapping (uint256 => bool) pPAIDxID_;          // (pID => paid eth) returns paid eth by player id
//****************
// PLAYER DATA 
//****************
    mapping (address => uint256) public pIDxAddr_;          // (addr => pID) returns player id by address
    mapping (bytes32 => uint256) public pIDxName_;          // (name => pID) returns player id by name
    mapping (uint256 => H3Ddatasets.Player) public plyr_;   // (pID => data) player data
    mapping (uint256 => mapping (uint256 => H3Ddatasets.PlayerRounds)) public plyrRnds_;    // (pID => rID => data) player round data by player id & round id
    mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns.  (used so you can change your display name amongst any name you own)	
//****************
// ROUND DATA 
//****************
    mapping (uint256 => H3Ddatasets.Round) public round_;   // (rID => data) round data
    mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_;      // (rID => tID => data) eth in per team, by round id and team id
//==============================================================================
//     _ _  _  __|_ _    __|_ _  _  .
//    (_(_)| |_\ | | |_|(_ | (_)|   .  (initial data setup upon contract deploy)
//==============================================================================
    constructor(address _TeamDreamHubSCaddress, address _PlayerBookSCaddress)
        public
    {
		owner = msg.sender;
		
		TeamDreamHub_ = TeamDreamHubInterface(_TeamDreamHubSCaddress);
		PlayerBook = PlayerBookInterface(_PlayerBookSCaddress);
	}
//==============================================================================
//     _ _  _  _|. |`. _  _ _  .
//    | | |(_)(_||~|~|(/_| _\  .  (these are safety checks)
//==============================================================================
    /**
     * @dev used to make sure no one can interact with contract until it has 
     * been activated. 
     */
    modifier isActivated() {
        require(activated_ == true, "its not ready yet.  check ?eta in discord"); 
        _;
    }
    
    /**
     * @dev prevents contracts from interacting with Heaven3D 
     */
    modifier isHuman() {
        address _addr = msg.sender;
		require (_addr == tx.origin);
		
        uint256 _codeLength;
        
        assembly {_codeLength := extcodesize(_addr)}
        require(_codeLength == 0, "sorry humans only");
        _;
    }
	
	modifier onlyOwner() {
		require (msg.sender == owner);
		_;
	}	

    /**
     * @dev sets boundaries for incoming tx 
     */
    modifier isWithinLimits(uint256 _eth) {
        require(_eth >= 1000000000, "pocket lint: not a valid currency");
        require(_eth <= 100000000000000000000000, "no vitalik, no");
        _;    
    }
    
//==============================================================================
//     _    |_ |. _   |`    _  __|_. _  _  _  .
//    |_)|_||_)||(_  ~|~|_|| |(_ | |(_)| |_\  .  (use these to interact with contract)
//====|=========================================================================
    /**
     * @dev fallback function
	 * emergency buy uses last stored affiliate ID and team snek
     */
    function()
        isActivated()
        isHuman()
        isWithinLimits(msg.value)
        public
        payable
    {
        // set up our tx event data and determine if player is new or not
        H3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
            
        // fetch player id
        uint256 _pID = pIDxAddr_[msg.sender];
        
        // buy core 
        buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
    }
    
    /**
     * @dev converts all incoming ethereum to keys.
     * -functionhash- 0x8f38f309 (using ID for affiliate)
     * -functionhash- 0x98a0871d (using address for affiliate)
     * -functionhash- 0xa65b37a1 (using name for affiliate)
     * @param _affCode the ID/address/name of the player who gets the affiliate fee
     * @param _team what team is the player playing for?
     */
    function buyXid(uint256 _affCode, uint256 _team)
        isActivated()
        isHuman()
        isWithinLimits(msg.value)
        public
        payable
    {
        // set up our tx event data and determine if player is new or not
        H3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
        
        // fetch player id
        uint256 _pID = pIDxAddr_[msg.sender];
        
        // manage affiliate residuals
        // if no affiliate code was given or player tried to use their own, lolz
        if (_affCode == 0 || _affCode == _pID)
        {
            // use last stored affiliate code 
            _affCode = plyr_[_pID].laff;
            
        // if affiliate code was given & its not the same as previously stored 
        } else if (_affCode != plyr_[_pID].laff) {
            // update last affiliate 
            plyr_[_pID].laff = _affCode;
        }
        
        // verify a valid team was selected
        _team = verifyTeam(_team);
        
        // buy core 
        buyCore(_pID, _affCode, _team, _eventData_);
    }
    
    function buyXaddr(address _affCode, uint256 _team)
        isActivated()
        isHuman()
        isWithinLimits(msg.value)
        public
        payable
    {
        // set up our tx event data and determine if player is new or not
        H3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
        
        // fetch player id
        uint256 _pID = pIDxAddr_[msg.sender];
        
        // manage affiliate residuals
        uint256 _affID;
        // if no affiliate code was given or player tried to use their own, lolz
        if (_affCode == address(0) || _affCode == msg.sender)
        {
            // use last stored affiliate code
            _affID = plyr_[_pID].laff;
        
        // if affiliate code was given    
        } else {
            // get affiliate ID from aff Code 
            _affID = pIDxAddr_[_affCode];
            
            // if affID is not the same as previously stored 
            if (_affID != plyr_[_pID].laff)
            {
                // update last affiliate
                plyr_[_pID].laff = _affID;
            }
        }
        
        // verify a valid team was selected
        _team = verifyTeam(_team);
        
        // buy core 
        buyCore(_pID, _affID, _team, _eventData_);
    }
    
    function buyXname(bytes32 _affCode, uint256 _team)
        isActivated()
        isHuman()
        isWithinLimits(msg.value)
        public
        payable
    {
        // set up our tx event data and determine if player is new or not
        H3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
        
        // fetch player id
        uint256 _pID = pIDxAddr_[msg.sender];
        
        // manage affiliate residuals
        uint256 _affID;
        // if no affiliate code was given or player tried to use their own, lolz
        if (_affCode == '' || _affCode == plyr_[_pID].name)
        {
            // use last stored affiliate code
            _affID = plyr_[_pID].laff;
        
        // if affiliate code was given
        } else {
            // get affiliate ID from aff Code
            _affID = pIDxName_[_affCode];
            
            // if affID is not the same as previously stored
            if (_affID != plyr_[_pID].laff)
            {
                // update last affiliate
                plyr_[_pID].laff = _affID;
            }
        }
        
        // verify a valid team was selected
        _team = verifyTeam(_team);
        
        // buy core 
        buyCore(_pID, _affID, _team, _eventData_);
    }
    
    /**
     * @dev essentially the same as buy, but instead of you sending ether 
     * from your wallet, it uses your unwithdrawn earnings.
     * -functionhash- 0x349cdcac (using ID for affiliate)
     * -functionhash- 0x82bfc739 (using address for affiliate)
     * -functionhash- 0x079ce327 (using name for affiliate)
     * @param _affCode the ID/address/name of the player who gets the affiliate fee
     * @param _team what team is the player playing for?
     * @param _eth amount of earnings to use (remainder returned to gen vault)
     */
    function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
        isActivated()
        isHuman()
        isWithinLimits(_eth)
        public
    {
        // set up our tx event data
        H3Ddatasets.EventReturns memory _eventData_;
        
        // fetch player ID
        uint256 _pID = pIDxAddr_[msg.sender];
        
        // manage affiliate residuals
        // if no affiliate code was given or player tried to use their own, lolz
        if (_affCode == 0 || _affCode == _pID)
        {
            // use last stored affiliate code 
            _affCode = plyr_[_pID].laff;
            
        // if affiliate code was given & its not the same as previously stored 
        } else if (_affCode != plyr_[_pID].laff) {
            // update last affiliate 
            plyr_[_pID].laff = _affCode;
        }

        // verify a valid team was selected
        _team = verifyTeam(_team);

        // reload core
        reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
    }
    
    function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
        isActivated()
        isHuman()
        isWithinLimits(_eth)
        public
    {
        // set up our tx event data
        H3Ddatasets.EventReturns memory _eventData_;
        
        // fetch player ID
        uint256 _pID = pIDxAddr_[msg.sender];
        
        // manage affiliate residuals
        uint256 _affID;
        // if no affiliate code was given or player tried to use their own, lolz
        if (_affCode == address(0) || _affCode == msg.sender)
        {
            // use last stored affiliate code
            _affID = plyr_[_pID].laff;
        
        // if affiliate code was given    
        } else {
            // get affiliate ID from aff Code 
            _affID = pIDxAddr_[_affCode];
            
            // if affID is not the same as previously stored 
            if (_affID != plyr_[_pID].laff)
            {
                // update last affiliate
                plyr_[_pID].laff = _affID;
            }
        }
        
        // verify a valid team was selected
        _team = verifyTeam(_team);
        
        // reload core
        reLoadCore(_pID, _affID, _team, _eth, _eventData_);
    }
    
    function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
        isActivated()
        isHuman()
        isWithinLimits(_eth)
        public
    {
        // set up our tx event data
        H3Ddatasets.EventReturns memory _eventData_;
        
        // fetch player ID
        uint256 _pID = pIDxAddr_[msg.sender];
        
        // manage affiliate residuals
        uint256 _affID;
        // if no affiliate code was given or player tried to use their own, lolz
        if (_affCode == '' || _affCode == plyr_[_pID].name)
        {
            // use last stored affiliate code
            _affID = plyr_[_pID].laff;
        
        // if affiliate code was given
        } else {
            // get affiliate ID from aff Code
            _affID = pIDxName_[_affCode];
            
            // if affID is not the same as previously stored
            if (_affID != plyr_[_pID].laff)
            {
                // update last affiliate
                plyr_[_pID].laff = _affID;
            }
        }
        
        // verify a valid team was selected
        _team = verifyTeam(_team);
        
        // reload core
        reLoadCore(_pID, _affID, _team, _eth, _eventData_);
    }

	/**
     * @dev (use it for contract switching) set the flag noMoreNextRound_
     */
    function noMoreNextRoundSetting(bool _noMoreNextRound)
        isActivated()
		onlyOwner()
        public
	{	
		noMoreNextRound_ = _noMoreNextRound;
	}		
	
	/**
     * @dev (use it for contract switching) developers manually put last contract's pot-fund-for-next-round to the current round's pot
     */
    function insertToPot()
        isActivated()
		onlyOwner()
        public
		payable
	{		
        round_[rID_].pot = round_[rID_].pot.add(msg.value);
        emit H3Devents.onPotSwapDeposit(rID_, msg.value);
	}
			
    /**
     * @dev withdraws all of your earnings.
     * -functionhash- 0x3ccfd60b
     */
    function withdraw()
        isActivated()
        isHuman()
        public
    {
        // setup local rID 
        uint256 _rID = rID_;
        
        // grab time
        uint256 _now = now;
        
        // fetch player ID
        uint256 _pID = pIDxAddr_[msg.sender];
        
        // setup temp var for player eth
        uint256 _eth;
        
        // check to see if round has ended and no one has run round end yet
        if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
        {
            // set up our tx event data
            H3Ddatasets.EventReturns memory _eventData_;
            endRoundControl(_eventData_);            
			
			// get their earnings
            _eth = withdrawEarnings(_pID);
            
            // gib moni
            if (_eth > 0)
                plyr_[_pID].addr.transfer(_eth);    
            
			if(round_[_rID].ended == true)
			{
	            // build event data
	            _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
	            _eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
            
	            // fire withdraw and distribute event
	            emit H3Devents.onWithdrawAndDistribute
	            (
	                msg.sender, 
	                plyr_[_pID].name, 
	                _eth, 
	                _eventData_.compressedData, 
	                _eventData_.compressedIDs, 
	                _eventData_.winnerAddr, 
	                _eventData_.winnerName, 
	                _eventData_.amountWon, 
	                _eventData_.newPot, 
	                _eventData_.P3DAmount, 
	                _eventData_.genAmount
	            );
			}
			else
			{
				// fire withdraw event
            	emit H3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
			}            
            
        // in any other situation
        } else {
            // get their earnings
            _eth = withdrawEarnings(_pID);
            
            // gib moni
            if (_eth > 0)
                plyr_[_pID].addr.transfer(_eth);
            
            // fire withdraw event
            emit H3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
        }
    }
    
    /**
     * @dev use these to register names.  they are just wrappers that will send the
     * registration requests to the PlayerBook contract.  So registering here is the 
     * same as registering there.  UI will always display the last name you registered.
     * but you will still own all previously registered names to use as affiliate 
     * links.
     * - must pay a registration fee.
     * - name must be unique
     * - names will be converted to lowercase
     * - name cannot start or end with a space 
     * - cannot have more than 1 space in a row
     * - cannot be only numbers
     * - cannot start with 0x 
     * - name must be at least 1 char
     * - max length of 32 characters long
     * - allowed characters: a-z, 0-9, and space
     * -functionhash- 0x921dec21 (using ID for affiliate)
     * -functionhash- 0x3ddd4698 (using address for affiliate)
     * -functionhash- 0x685ffd83 (using name for affiliate)
     * @param _nameString players desired name
     * @param _affCode affiliate ID, address, or name of who referred you
     * @param _all set to true if you want this to push your info to all games 
     * (this might cost a lot of gas)
     */
    function registerNameXID(string _nameString, uint256 _affCode, bool _all)
        isHuman()
        public
        payable
    {
        bytes32 _name = _nameString.nameFilter();
        address _addr = msg.sender;
        uint256 _paid = msg.value;
        (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
        
        uint256 _pID = pIDxAddr_[_addr];
        
        // fire event
        emit H3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
    }
    
    function registerNameXaddr(string _nameString, address _affCode, bool _all)
        isHuman()
        public
        payable
    {
        bytes32 _name = _nameString.nameFilter();
        address _addr = msg.sender;
        uint256 _paid = msg.value;
        (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
        
        uint256 _pID = pIDxAddr_[_addr];
        
        // fire event
        emit H3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
    }
    
    function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
        isHuman()
        public
        payable
    {
        bytes32 _name = _nameString.nameFilter();
        address _addr = msg.sender;
        uint256 _paid = msg.value;
        (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
        
        uint256 _pID = pIDxAddr_[_addr];
        
        // fire event
        emit H3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
    }
//==============================================================================
//     _  _ _|__|_ _  _ _  .
//    (_|(/_ |  | (/_| _\  . (for UI & viewing things on etherscan)
//=====_|=======================================================================
    /**
     * @dev return the price buyer will pay for next 1 individual key.
     * -functionhash- 0x018a25e8
     * @return price for next key bought (in wei format)
     */
    function getBuyPrice()
        public 
        view 
        returns(uint256)
    {  
        // setup local rID
        uint256 _rID = rID_;
        
        // grab time
        uint256 _now = now;
        
        // are we in a round?
        if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
            return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
        else // rounds over.  need price for new round
            return ( 75000000000000 ); // init
    }
    
    /**
     * @dev returns time left.  dont spam this, you'll ddos yourself from your node 
     * provider
     * -functionhash- 0xc7e284b8
     * @return time left in seconds
     */
    function getTimeLeft()
        public
        view
        returns(uint256)
    {
        // setup local rID
        uint256 _rID = rID_;
        
        // grab time
        uint256 _now = now;
        
        if (_now < round_[_rID].end)
            if (_now > round_[_rID].strt + rndGap_)
                return( (round_[_rID].end).sub(_now) );
            else
                return( (round_[_rID].strt + rndGap_).sub(_now) );
        else
            return(0);
    }
    
    /**
     * @dev returns player earnings per vaults 
     * -functionhash- 0x63066434
     * @return winnings vault
     * @return general vault
     * @return affiliate vault
     */
    function getPlayerVaults(uint256 _pID)
        public
        view
        returns(uint256 ,uint256, uint256)
    {
        // setup local rID
        uint256 _rID = rID_;
        
		uint256 limitedDividends = (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd));
		if(limitedDividends > plyrRnds_[_pID][_rID].eth.mul(3))
			limitedDividends = plyrRnds_[_pID][_rID].eth.mul(3);
		
		return
		(
			plyr_[_pID].win,
			limitedDividends,
			plyr_[_pID].aff
		);        
    }
        
    /**
     * @dev returns all current round info needed for front end
     * -functionhash- 0x747dff42
     * @return eth invested during ICO phase
     * @return round id 
     * @return total keys for round 
     * @return time round ends
     * @return time round started
     * @return current pot 
     * @return current team ID & player ID in lead 
     * @return current player in leads address 
     * @return current player in leads name
     * @return whales eth in for round
     * @return bears eth in for round
     * @return sneks eth in for round
     * @return bulls eth in for round
     * @return airdrop tracker # & airdrop pot
     */
    function getCurrentRoundInfo()
        public
        view
        returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
    {
        // setup local rID
        uint256 _rID = rID_;
        
        return
        (
            round_[_rID].ico,               //0
            _rID,                           //1
            round_[_rID].keys,              //2
            round_[_rID].end,               //3
            round_[_rID].strt,              //4
            round_[_rID].pot,               //5
            (round_[_rID].team + (round_[_rID].plyr * 10)),     //6
            plyr_[round_[_rID].plyr].addr,  //7
            plyr_[round_[_rID].plyr].name,  //8
            rndTmEth_[_rID][0],             //9
            rndTmEth_[_rID][1],             //10
            rndTmEth_[_rID][2],             //11
            rndTmEth_[_rID][3],             //12
            randomDecisionPhase_            //13
        );
    }

    /**
     * @dev returns player info based on address.  if no address is given, it will 
     * use msg.sender 
     * -functionhash- 0xee0b5d8b
     * @param _addr address of the player you want to lookup 
     * @return player ID 
     * @return player name
     * @return keys owned (current round)
     * @return winnings vault
     * @return general vault 
     * @return affiliate vault 
	 * @return player round eth
     */
    function getPlayerInfoByAddress(address _addr)
        public 
        view 
        returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
    {
        // setup local rID
        uint256 _rID = rID_;
        
        if (_addr == address(0))
        {
            _addr == msg.sender;
        }
        uint256 _pID = pIDxAddr_[_addr];
		
		uint256 limitedDividends = (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd));
		if(limitedDividends > plyrRnds_[_pID][_rID].eth.mul(3))
			limitedDividends = plyrRnds_[_pID][_rID].eth.mul(3);
        
        return
        (
            _pID,                               //0
            plyr_[_pID].name,                   //1
            plyrRnds_[_pID][_rID].keys,         //2
            plyr_[_pID].win,                    //3
            limitedDividends,       //4
            plyr_[_pID].aff,                    //5
            plyrRnds_[_pID][_rID].eth           //6
        );
    }

//==============================================================================
//     _ _  _ _   | _  _ . _  .
//    (_(_)| (/_  |(_)(_||(_  . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================

    function endRoundControl(H3Ddatasets.EventReturns memory _eventData_)
        private
	{
	    // setup local rID 
        uint256 _rID = rID_;
		// set true for randomDecisionPhase_ we're in!
		randomDecisionPhase_ = 101;        
        // setup local _address_gen_src 
        address _address_gen_src = address_of_last_rand_gen_source_;
        
		bool goMakeDecision = true;
        // case1: 1st time to make decision OR sender is also the validator
        if((_address_gen_src == address(0)) || (_address_gen_src == msg.sender)) {
            goMakeDecision = true;
        }
		else {
			// case2: last sender is human
			if(checkNotSmartContract(_address_gen_src)) {                			
                // case2a: prior check PASS: returned by endRoundDecision()
                if(endRoundDecisionResult_ == true) {		
					// end the round (distributes pot) & start new round
					round_[_rID].ended = true;
					_eventData_ = endRound(_eventData_);																
					randomDecisionPhase_ = 100;
				}
				// case2b: prior check FAILED: returned by endRoundDecision()
                else {
					// grab time
					uint256 _now = now;					
					// set new end time by adding rndDeciExt_ to NOW; normally add 6 minutes
					round_[_rID].end = rndDeciExt_.add(_now);
				}
				
                // reset all flags
                // because we're leaving endGamePrcoess and not going to come back within a period of time
				endRoundDecisionResult_ = false;
				address_of_last_rand_gen_source_ = address(0);
				goMakeDecision = false;
			}
			// case3: last player is not human, so let the current player throw the dice again.
			else {
				goMakeDecision = true; 
			}
		}

        if(goMakeDecision == true) {
			//throw the dice and wait for next player to validate the result.
			address_of_last_rand_gen_source_ = msg.sender;
			endRoundDecisionResult_ = endRoundDecision();	
		}				
	}

    /**
     * @dev logic runs whenever a buy order is executed.  determines how to handle 
     * incoming eth depending on if we are in an active round or not
     */
    function buyCore(uint256 _pID, uint256 _affID, uint256 _team, H3Ddatasets.EventReturns memory _eventData_)
        private
    {
        // setup local rID
        uint256 _rID = rID_;
        
        // grab time
        uint256 _now = now;
        
        // if round is active
        if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) 
        {
            // call core 
            core(_rID, _pID, msg.value, _affID, _team, _eventData_);
        
        // if round is not active     
        } else {
            // check to see if end round needs to be ran
            if (_now > round_[_rID].end && round_[_rID].ended == false) 
            {
                endRoundControl(_eventData_); 
				
				if(round_[_rID].ended == true)
				{
	                // build event data
	                _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
	                _eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
                
	                // fire buy and distribute event 
	                emit H3Devents.onBuyAndDistribute
	                (
	                    msg.sender, 
	                    plyr_[_pID].name, 
	                    msg.value, 
	                    _eventData_.compressedData, 
	                    _eventData_.compressedIDs, 
	                    _eventData_.winnerAddr, 
	                    _eventData_.winnerName, 
	                    _eventData_.amountWon, 
	                    _eventData_.newPot, 
	                    _eventData_.P3DAmount, 
	                    _eventData_.genAmount
	                );
				}
            }
            
            // put eth in players vault 
            plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
        }
    }
    
    /**
     * @dev logic runs whenever a reload order is executed.  determines how to handle 
     * incoming eth depending on if we are in an active round or not 
     */
    function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, H3Ddatasets.EventReturns memory _eventData_)
        private
    {
        // setup local rID
        uint256 _rID = rID_;
        
        // grab time
        uint256 _now = now;
        
        // if round is active
        if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) 
        {
            // get earnings from all vaults and return unused to gen vault
            // because we use a custom safemath library.  this will throw if player 
            // tried to spend more eth than they have.
            plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
            
            // call core 
            core(_rID, _pID, _eth, _affID, _team, _eventData_);
        
        // if round is not active and end round needs to be ran   
        } else if (_now > round_[_rID].end && round_[_rID].ended == false) {
			
			endRoundControl(_eventData_); 
			
			if(round_[_rID].ended == true)
			{	            // build event data
	            _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
	            _eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
                
	            // fire buy and distribute event 
	            emit H3Devents.onReLoadAndDistribute
	            (
	                msg.sender, 
	                plyr_[_pID].name, 
	                _eventData_.compressedData, 
	                _eventData_.compressedIDs, 
	                _eventData_.winnerAddr, 
	                _eventData_.winnerName, 
	                _eventData_.amountWon, 
	                _eventData_.newPot, 
	                _eventData_.P3DAmount, 
	                _eventData_.genAmount
	            );
			}
        }
    }
    
    /**
     * @dev this is the core logic for any buy/reload that happens while a round 
     * is live.
     */
    function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, H3Ddatasets.EventReturns memory _eventData_)
        private
    {
        // if player is new to round
        if (plyrRnds_[_pID][_rID].keys == 0)
            _eventData_ = managePlayer(_pID, _eventData_); // don't have to do updateGenVault again because we have it in managePlayer()
		else // if not, can use _rID directly, but we decided to still go with plyr_[_pID].lrnd
			updateGenVault(_pID, plyr_[_pID].lrnd);	
        
        // early round eth limiter 
        if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000)
        {
            uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
            uint256 _refund = _eth.sub(_availableLimit);
            plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
            _eth = _availableLimit;
        }
        
        // if eth left is greater than min eth allowed (sorry no pocket lint)
        if (_eth > 1000000000) 
        {            
            // mint the new keys
            uint256 _keys = (round_[_rID].eth).keysRec(_eth);
            
            // if they bought at least 1 whole key
            if (_keys >= 1000000000000000000)
            {
				updateTimer(_keys, _rID);

				// set new leaders
				if (round_[_rID].plyr != _pID)
					round_[_rID].plyr = _pID;  
				if (round_[_rID].team != _team)
					round_[_rID].team = _team; 
				
				// set the new leader bool to true
				_eventData_.compressedData = _eventData_.compressedData + 100;
			}            
    
            // store the air drop tracker number (number of buys since last airdrop)
            _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
            
            // update player 
            plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
            plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
            
            // update round
            round_[_rID].keys = _keys.add(round_[_rID].keys);
            round_[_rID].eth = _eth.add(round_[_rID].eth);
            rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
    
            // distribute eth
            _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _eventData_);
            _eventData_ = distributeInternal(_rID, _pID, _eth, _keys, _eventData_);
			
			internalNoter(_rID, _pID);
			
            // call end tx function to fire end tx event.
		    endTx(_pID, _team, _eth, _keys, _eventData_);
        }
    }
//==============================================================================
//     _ _ | _   | _ _|_ _  _ _  .
//    (_(_||(_|_||(_| | (_)| _\  .
//==============================================================================
    /**
     * @dev calculates unmasked earnings (just calculates, does not update mask)
     * @return earnings in wei format
     */
    function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
        private
        view
        returns(uint256)
    {
        return(  (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask)  );
    }
    
    /** 
     * @dev returns the amount of keys you would get given an amount of eth. 
     * -functionhash- 0xce89c80c
     * @param _rID round ID you want price for
     * @param _eth amount of eth sent in 
     * @return keys received 
     */
    function calcKeysReceived(uint256 _rID, uint256 _eth)
        public
        view
        returns(uint256)
    {
        // grab time
        uint256 _now = now;
        
        // are we in a round?
        if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
            return ( (round_[_rID].eth).keysRec(_eth) );
        else // rounds over.  need keys for new round
            return ( (_eth).keys() );
    }
    
    /** 
     * @dev returns current eth price for X keys.  
     * -functionhash- 0xcf808000
     * @param _keys number of keys desired (in 18 decimal format)
     * @return amount of eth needed to send
     */
    function iWantXKeys(uint256 _keys)
        public
        view
        returns(uint256)
    {
        // setup local rID
        uint256 _rID = rID_;
        
        // grab time
        uint256 _now = now;
        
        // are we in a round?
        if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
            return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
        else // rounds over.  need price for new round
            return ( (_keys).eth() );
    }
//==============================================================================
//    _|_ _  _ | _  .
//     | (_)(_)|_\  .
//==============================================================================
    /**
	 * @dev receives name/player info from names contract 
     */
    function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
        external
    {
        require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
        if (pIDxAddr_[_addr] != _pID)
            pIDxAddr_[_addr] = _pID;
        if (pIDxName_[_name] != _pID)
            pIDxName_[_name] = _pID;
        if (plyr_[_pID].addr != _addr)
            plyr_[_pID].addr = _addr;
        if (plyr_[_pID].name != _name)
            plyr_[_pID].name = _name;
        if (plyr_[_pID].laff != _laff)
            plyr_[_pID].laff = _laff;
        if (plyrNames_[_pID][_name] == false)
            plyrNames_[_pID][_name] = true;
    }
    
    /**
     * @dev receives entire player name list 
     */
    function receivePlayerNameList(uint256 _pID, bytes32 _name)
        external
    {
        require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
        if(plyrNames_[_pID][_name] == false)
            plyrNames_[_pID][_name] = true;
    }   
        
    /**
     * @dev gets existing or registers new pID.  use this when a player may be new
     * @return pID 
     */
    function determinePID(H3Ddatasets.EventReturns memory _eventData_)
        private
        returns (H3Ddatasets.EventReturns)
    {
        uint256 _pID = pIDxAddr_[msg.sender];
        // if player is new to this version of Heaven3D
        if (_pID == 0)
        {
            // grab their player ID, name and last aff ID, from player names contract 
            _pID = PlayerBook.getPlayerID(msg.sender);
            bytes32 _name = PlayerBook.getPlayerName(_pID);
            uint256 _laff = PlayerBook.getPlayerLAff(_pID);
            
            // set up player account 
            pIDxAddr_[msg.sender] = _pID;
            plyr_[_pID].addr = msg.sender;
            
            if (_name != "")
            {
                pIDxName_[_name] = _pID;
                plyr_[_pID].name = _name;
                plyrNames_[_pID][_name] = true;
            }
            
            if (_laff != 0 && _laff != _pID)
                plyr_[_pID].laff = _laff;
            
            // set the new player bool to true
            _eventData_.compressedData = _eventData_.compressedData + 1;
        } 
        return (_eventData_);
    }
    
    /**
     * @dev checks to make sure user picked a valid team.  if not sets team 
     * to default (sneks)
     */
    function verifyTeam(uint256 _team)
        private
        pure
        returns (uint256)
    {
        if (_team < 0 || _team > 3)
            return(2);
        else
            return(_team);
    }
    
    /**
     * @dev decides if round end needs to be run & new round started.  and if 
     * player unmasked earnings from previously played rounds need to be moved.
     */
    function managePlayer(uint256 _pID, H3Ddatasets.EventReturns memory _eventData_)
        private
        returns (H3Ddatasets.EventReturns)
    {
        // if player has played a previous round, move their unmasked earnings
        // from that round to gen vault.
        if (plyr_[_pID].lrnd != 0)
            updateGenVault(_pID, plyr_[_pID].lrnd);
            
        // update player's last round played
        plyr_[_pID].lrnd = rID_;
            
        // set the joined round bool to true
        _eventData_.compressedData = _eventData_.compressedData + 10;
        
        return(_eventData_);
    }
    
    /**
     * @dev ends the round. manages paying out winner/splitting up pot
     */
    function endRound(H3Ddatasets.EventReturns memory _eventData_)
        private
        returns (H3Ddatasets.EventReturns)
    {
        // setup local rID
        uint256 _rID = rID_;
        
        // grab our winning player and team id's
        uint256 _winPID = round_[_rID].plyr;
        uint256 _winTID = round_[_rID].team;
        
        // grab our pot amount
        uint256 _pot = round_[_rID].pot;
        
        // calculate our winner share, community rewards, gen share, 
        // p3d share, and amount reserved for next pot 
        uint256 _win = (_pot.mul(68)) / 100; // for all winners
        uint256 _com = (_pot.mul(10)) / 100; // for community 
        uint256 _gen = 0; 
        uint256 _p3d = 0;
		
		// community rewards
		TeamDreamHub_.deposit.value(_com)();
		
		uint256 _res = ((_pot.sub(_com)).sub(_gen)).sub(_p3d); // _win should be handled later.        
		(_res,_eventData_) = winnersProfitDistributor(_rID, _win, _res, _eventData_); // distribute to all winners
		
		// if update in smart contract is neccessary, the developers will trigger this mechanism.
		// in this condition we're going into maintenance mode in order to update the smart contract on the blockchain
		// we developers will put _res into the next pot manually when H3D is going online again.
		// the down time is expected to be short.
		if(noMoreNextRound_ == true)
		{
			owner.transfer(_res);
			_res = 0;
		}
            
        // prepare event data
        _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
        _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
        _eventData_.winnerAddr = plyr_[_winPID].addr;
        _eventData_.winnerName = plyr_[_winPID].name;
        _eventData_.amountWon = _win;
        _eventData_.genAmount = _gen;
        _eventData_.P3DAmount = _p3d;
        _eventData_.newPot = _res;
        
        // start next round
        rID_++;
        _rID++;
        round_[_rID].strt = now;
        round_[_rID].end = now.add(rndInit_).add(rndGap_);
        round_[_rID].pot = _res; // the rest goes to next pot
        
        return(_eventData_);
    }
    
    /**
     * @dev moves any unmasked earnings to gen vault.  updates earnings mask
     */
    function updateGenVault(uint256 _pID, uint256 _rIDlast)
        private 
    {
        uint256 dividend_yet_distribute = calcUnMaskedEarnings(_pID, _rIDlast);
        if (dividend_yet_distribute > 0)
        {			
			uint256 _earnings;
			uint256 all_dividend_earned = dividend_yet_distribute.add(plyrRnds_[_pID][_rIDlast].eth_went_to_gen);
			//check 3x limit
			if (all_dividend_earned > (plyrRnds_[_pID][_rIDlast].eth).mul(3))
			{	
				//===adjustment done accordingly===
				
				//seperate exceeds_part from dividend_yet_distribute
				uint256 remain_quota = (plyrRnds_[_pID][_rIDlast].eth).mul(3).sub(plyrRnds_[_pID][_rIDlast].eth_went_to_gen); // can only provide the dividend withing 3x of inputed eth.
				uint256 exceeds_part = dividend_yet_distribute.sub(remain_quota);

				_earnings = remain_quota;
				
		        // add exceeds_part as new profit to the current round and adjust round.mask accordingly				
				uint256 _dust = updateMasks(rID_, _pID, exceeds_part, 0); // keys = 0 because didn't add new key.
				if (_dust > 0) // add dust to pot
					round_[rID_].pot = round_[rID_].pot.add(_dust);	
			}
			else
			{
				_earnings = dividend_yet_distribute;
			}
			
			// put in gen vault
			plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
			
			//note to eth_went_to_gen, in order to estimate all eth passed to geb vault in the current round.
			plyrRnds_[_pID][_rIDlast].eth_went_to_gen = _earnings.add(plyrRnds_[_pID][_rIDlast].eth_went_to_gen);			
			
			// zero out their earnings by updating mask
			plyrRnds_[_pID][_rIDlast].mask = dividend_yet_distribute.add(plyrRnds_[_pID][_rIDlast].mask);
        }
    }
    
    /**
     * @dev updates round timer based on number of whole keys bought.
     */
    function updateTimer(uint256 _keys, uint256 _rID)
        private
    {
        // grab time
        uint256 _now = now;
        
        // calculate time based on number of keys bought
        uint256 _newTime;
        if (_now > round_[_rID].end && round_[_rID].plyr == 0)
            _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
        else
            _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
        
        // compare to max and set new end time
        if (_newTime < (rndMax_).add(_now))
            round_[_rID].end = _newTime;
        else
            round_[_rID].end = rndMax_.add(_now);
    }
	
	/**
     * @dev generates a random number in order to make a decision
     * @return PASS or REJECT?
     */
    function endRoundDecision()
        private 
        returns(bool)
    {
		bool decision = false;
        uint256 seed = uint256(keccak256(abi.encodePacked(
            
            (block.timestamp).add
            (block.difficulty).add
            ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
            (block.gaslimit).add
            ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
            (block.number)
            
        )));
        
		uint256 randNum = (seed - ((seed / 1000) * 1000));
		if(randNum < 50) // 5% probability
            decision = true;
		
		// fire event
		emit H3Devents.onNewDecision(msg.sender,randNum,decision);
		
		return decision;
    }	
	
	/**
     * @dev check if an address is smart contract
     * @return true (Not smart contract) or false
     */
    function checkNotSmartContract(address targetAddr)
        private 
        returns(bool)
    {
		uint256 _codeLength;        
		assembly {
			_codeLength := extcodesize(targetAddr)
		}
		
		if(_codeLength == 0) // last sender is human
			return true;
		else
			return false;
    }	
    

    /**
     * @dev distributes eth based on fees to com, aff, and p3d
     */
    function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, H3Ddatasets.EventReturns memory _eventData_)
        private
        returns(H3Ddatasets.EventReturns)
    {
        // pay 10% out to community fund
        uint256 _com = (_eth.mul(10)) / 100;
        uint256 _p3d = 0;
                
        // distribute share to affiliate
        uint256 _aff = _eth / 10;
        
        // decide what to do with affiliate share of fees
        // affiliate must not be self, and must have a name registered
        if (_affID != _pID && plyr_[_affID].name != '') {
            plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
            emit H3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
        } else {
			_com = _com.add(_aff);
        }
		
		// payout community rewards
		TeamDreamHub_.deposit.value(_com)();
        
        return(_eventData_);
    }
    
    function potSwap()
        external
        payable
    {
        // setup local rID
        uint256 _rID = rID_ + 1;
        
        round_[_rID].pot = round_[_rID].pot.add(msg.value);
        emit H3Devents.onPotSwapDeposit(_rID, msg.value);
    }
    
    /**
     * @dev distributes eth based on fees to gen and pot
     */
    function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _keys, H3Ddatasets.EventReturns memory _eventData_)
        private
        returns(H3Ddatasets.EventReturns)
    {
        // calculate gen share
        uint256 _gen = (_eth.mul(60)) / 100; 
        
        // update eth balance (eth = eth - (com share + aff share + p3d share + airdrop pot share))
        _eth = _eth.sub((_eth.mul(20)) / 100);
        
        // calculate pot 
        uint256 _pot = _eth.sub(_gen);
        
        // distribute gen share (thats what updateMasks() does) and adjust
        // balances for dust.
        uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
        if (_dust > 0)
            _gen = _gen.sub(_dust);
        
        // add eth to pot
        round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
        
        // set up event data
        _eventData_.genAmount = _gen.add(_eventData_.genAmount);
        _eventData_.potAmount = _pot;
        
        return(_eventData_);
    }
	
	/**
     * @dev distribute profits (_win) to the pot winners)
     */
    function winnersProfitDistributor(uint256 _rID, uint256 _win, uint256 _res, H3Ddatasets.EventReturns memory _eventData_)
        private
		returns (uint256, H3Ddatasets.EventReturns)
    {		
		uint256 _pIDtmp; 
		uint256 _paidPlayerCount; // note how many players have been paid already.
		uint256 _bonus_portion; // compute portions

        _eventData_ = determinePID(_eventData_);

        // pay the rand number generator caller (rate = 1%)
        _bonus_portion = (_win.mul(10)) / 1000;
        _pIDtmp = pIDxAddr_[address_of_last_rand_gen_source_];
		plyr_[_pIDtmp].win = _bonus_portion.add(plyr_[_pIDtmp].win);
		_res = _res.sub(_bonus_portion);
        
        // pay our latestPlayers (rate = 49% / 10 players = 4.9%)
        _bonus_portion = (_win.mul(49)) / 1000;
		_paidPlayerCount = 0;

		// pay the latest 10 players
        for (uint i = 0; i < round_[_rID].latestPlayers.length; i++) {			
			if(round_[_rID].latestPlayers[i] == 0) break; // early-stop						
			if(_paidPlayerCount == rule_limit_latestPlayersCnt) break; // already paid enough players			
										
			_pIDtmp = round_[_rID].latestPlayers[i];
			// only pay out for human players
			if(checkNotSmartContract(plyr_[_pIDtmp].addr)) {
				plyr_[_pIDtmp].win = _bonus_portion.add(plyr_[_pIDtmp].win);
				_res = _res.sub(_bonus_portion);
				_paidPlayerCount++;
				// record the latestPlayers for later use
				pPAIDxID_[round_[_rID].latestPlayers[i]] = true;				
			}			
		}
		
        // pay our heavyPlayers (rate = 50% / 10 players = 5%)
        _bonus_portion = (_win.mul(50)) / 1000;
		_paidPlayerCount = 0;
		for (i = 0; i < round_[_rID].heavyPlayers.length; i++) {			
			if(round_[_rID].heavyPlayers[i] == 0) break; // early-stop
			if(_paidPlayerCount == rule_limit_heavyPlayersCnt) break; // already paid enough players
						
			_pIDtmp = round_[_rID].heavyPlayers[i];
			// only pay out for human players
			if(checkNotSmartContract(plyr_[_pIDtmp].addr)) {				
                // don't pay if _pIDtmp is one of the latestPlayers
                if(pPAIDxID_[_pIDtmp] == true) continue;
				plyr_[_pIDtmp].win = _bonus_portion.add(plyr_[_pIDtmp].win);
				_res = _res.sub(_bonus_portion);
				_paidPlayerCount++;
			}
		}		
		// clear pPAIDxID_ for the use in next round's endround process.
		for (i = 0; i < round_[_rID].latestPlayers.length; i++)
			pPAIDxID_[round_[_rID].latestPlayers[i]] = false;		
		
		return (_res,_eventData_);
	}
	
    /**
     * @dev note neccessary info.
     */
    function internalNoter(uint256 _rID, uint256 _pID)
        private
    {
		bool hasFoundIdx = false;
		
        // [update latestPlayers list]
		// round_[_rID].latestPlayers is a FIFO in which idx = 0 is the head and idx = length - 1 is the tail
		// the latest player will be the closest player (i.e., on the list) to the tail.		
        // initially idx_insert is mapping to the last slot
        // if idx_insert is not changed with the conditions below
        // idx_insert is located in the last slot
        uint idx_insert = round_[_rID].latestPlayers.length - 1;
		uint i;
		uint j;
		
		// shift the FIFO to find a slot to insert the current player		
		// case1: when the list is not full
		for (i=0; i<round_[_rID].latestPlayers.length-1; i++) {
            // case1a: if _pID exists in the ith slot
            if(round_[_rID].latestPlayers[i] == _pID) {
                // shift earlier players to fill the ith slot
                for (j=i; j<round_[_rID].latestPlayers.length-1; j++) {
                    round_[_rID].latestPlayers[j] = round_[_rID].latestPlayers[j+1];
                    if(round_[_rID].latestPlayers[j] == 0) {
                        idx_insert = j;  // new index = j
						hasFoundIdx = true;
						break; // early stop when there's no more non-empty cell left to check on.
					}
                }
            }
			// case1b: if _pID doesn't exist in the ith slot, and it's an empty slot
            else {
                // if not repeated, check whether the slot is empty (0)
                if(round_[_rID].latestPlayers[i] == 0) {
                    idx_insert = i;  // new index = i
					hasFoundIdx = true;
					break; // early stop when find an empty cell already.
				}				
			}				
		}					

		// case2: when the list is full
		// only do it when former loop hasn't found an idx to insert
        if (hasFoundIdx == false) {
			for (i=0; i<round_[_rID].latestPlayers.length-1; i++) {
				// replace the 1st one and leave the last slot empty.			
				round_[_rID].latestPlayers[i] = round_[_rID].latestPlayers[i+1]; 
			}			
        }
        
        // assign the _pID to the corresponding idx_insert for the latestPlayers list
        round_[_rID].latestPlayers[idx_insert] = _pID;
        
        // ----------------------------------------------------

        // [update heavyPlayers list]
		// round_[_rID].heavyPlayers is a list in which idx = 0 is the head and idx = length - 1 is the tail
		// the player who spent largest amount of ether will be the closest player (i.e., on the list) to the head.		
        // initially set idx_insert is mapping to the last slot
        // if idx_insert is not changed with the conditions below
        // idx_insert is located in the last slot
		hasFoundIdx = false;
        idx_insert = round_[_rID].heavyPlayers.length - 1;

        // check whether the _pID repeated in the heavyPlayers list
		// case: checking whether the current player is already on the list.
        for(i=0; i<round_[_rID].heavyPlayers.length; i++) {
            if(round_[_rID].heavyPlayers[i] == 0) break; // early-stop when no more non-empty cells to read.
            // if _pID exists in the ith slot
            if(round_[_rID].heavyPlayers[i] == _pID) {
                // shift the other players to fill the ith slot
                for(j=i; j<round_[_rID].heavyPlayers.length-1; j++) {
                    round_[_rID].heavyPlayers[j] = round_[_rID].heavyPlayers[j+1];
                    if(round_[_rID].heavyPlayers[j] == 0) break; 
                }
            }
        }      

        // after eliminating the repeated _pID, order the players by spent ethers
        for(i=0; i<round_[_rID].heavyPlayers.length; i++) {
			// case1: use this in the round beginning
			// case2: spent eth smaller than the others on the list
            if(round_[_rID].heavyPlayers[i] == 0) {
                idx_insert = i;  // new index = i
				hasFoundIdx = true;
				break; // early-stop when find a idx_insert to insert
			}			
            else {
                // case3: if spent eth larger than someone, insert the current player into the slot
                if(plyrRnds_[_pID][_rID].eth > plyrRnds_[round_[_rID].heavyPlayers[i]][_rID].eth) {
                    idx_insert = i;  // new index = i
					hasFoundIdx = true;
                    // shift players to vacate the ith slot
                    for (j=i; j<round_[_rID].heavyPlayers.length-1; j++) {
                        round_[_rID].heavyPlayers[j+1] = round_[_rID].heavyPlayers[j];
                        if(round_[_rID].heavyPlayers[j] == 0) break; // early-stop when find an empty cell
                    }
					break; // early-stop when already find an idx_insert to insert
                }            
            }                
        }

		// assign the _pID to the corresponding idx_insert for the heavyPlayers list, only when really find an appropriate position on the list that is for the player.
		if(hasFoundIdx == true)        
			round_[_rID].heavyPlayers[idx_insert] = _pID;
	}			

    /**
     * @dev updates masks for round and player when keys are bought
     * @return dust left over 
     */
    function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
        private
        returns(uint256)
    {
        /* MASKING NOTES
            earnings masks are a tricky thing for people to wrap their minds around.
            the basic thing to understand here.  is were going to have a global
            tracker based on profit per share for each round, that increases in
            relevant proportion to the increase in share supply.
            
            the player will have an additional mask that basically says "based
            on the rounds mask, my shares, and how much i've already withdrawn,
            how much is still owed to me?"
        */
        
		uint256 _ppt;
		if(round_[_rID].keys.sub(_keys) == 0) // only 1st key buyer can earn dividend based on the keys just purchased
		{
			// calc profit per key & round mask based on this buy:  (dust goes to pot)
			_ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
			round_[_rID].mask = _ppt.add(round_[_rID].mask);
				
			// calculate player earning from their own buy (only based on the keys
			// they just bought).  & update player earnings mask
			uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
			plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // sub(_pearn) because want to deliver it to the player.
			return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); // calculate & return dust
		}
		else
		{
			// calc profit per key & round mask based on this buy:  (dust goes to pot)
			_ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys.sub(_keys)); // sub. _keys because only distribute the profit to former keys.
			round_[_rID].mask = _ppt.add(round_[_rID].mask);
				
			// update player earnings mask so they cannot obtain profit generated based on their own input
			plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000))).add(plyrRnds_[_pID][_rID].mask); 
			return(_gen.sub((_ppt.mul(round_[_rID].keys.sub(_keys))) / (1000000000000000000))); // calculate & return dust; sub. _keys because only distribute the profit to former keys. 
		}		
        
    }
    
    /**
     * @dev adds up unmasked earnings, & vault earnings, sets them all to 0
     * @return earnings in wei format
     */
    function withdrawEarnings(uint256 _pID)
        private
        returns(uint256)
    {
        // update gen vault
        updateGenVault(_pID, plyr_[_pID].lrnd);
        
        // from vaults 
        uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
        if (_earnings > 0)
        {
            plyr_[_pID].win = 0;
            plyr_[_pID].gen = 0;
            plyr_[_pID].aff = 0;
        }

        return(_earnings);
    }
    
    /**
     * @dev prepares compression data and fires event for buy or reload tx's
     */
    function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, H3Ddatasets.EventReturns memory _eventData_)
        private
    {
        _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
        _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
        
        emit H3Devents.onEndTx
        (
            _eventData_.compressedData,
            _eventData_.compressedIDs,
            plyr_[_pID].name,
            msg.sender,
            _eth,
            _keys,
            _eventData_.winnerAddr,
            _eventData_.winnerName,
            _eventData_.amountWon,
            _eventData_.newPot,
            _eventData_.P3DAmount,
            _eventData_.genAmount,
            _eventData_.potAmount,
            airDropPot_
        );
    }
//==============================================================================
//    (~ _  _    _._|_    .
//    _)(/_(_|_|| | | \/  .
//====================/=========================================================
    /** upon contract deploy, it will be deactivated.  this is a one time
     * use function that will activate the contract.  we do this so devs 
     * have time to set things up on the web end                            **/
    bool public activated_ = false;
    function activate()
        public
    {
        // only Team Dream can activate 
        require(
            msg.sender == owner,
            "only Team Dream can activate"
        );
        
        // can only be ran once
        require(activated_ == false, "Heaven3D already activated");
        
        // activate the contract 
        activated_ = true;
        
        // lets start first round
		rID_ = 1;
        round_[1].strt = now + rndExtra_ - rndGap_;
        round_[1].end = now + rndInit_ + rndExtra_;
    }
	
}
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
        isActivated()
        isHuman()
        isWithinLimits(_eth)
        public
    {
        // set up our tx event data
        H3Ddatasets.EventReturns memory _eventData_;
        
        // fetch player ID
        uint256 _pID = pIDxAddr_[msg.sender];
        
        // manage affiliate residuals
        // if no affiliate code was given or player tried to use their own, lolz
        if (_affCode == 0 || _affCode == _pID)
        {
            // use last stored affiliate code 
            _affCode = plyr_[_pID].laff;
            
        // if affiliate code was given & its not the same as previously stored 
        } else if (_affCode != plyr_[_pID].laff) {
            // update last affiliate 
            plyr_[_pID].laff = _affCode;
        }

        // verify a valid team was selected
        _team = verifyTeam(_team);

        // reload core
        reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
    }
/**
 * @dev essentially the same as buy, but instead of you sending ether 
 * from your wallet, it uses your unwithdrawn earnings.
 * -functionhash- 0x349cdcac (using ID for affiliate)
 * -functionhash- 0x82bfc739 (using address for affiliate)
 * -functionhash- 0x079ce327 (using name for affiliate)
 * @param _affCode the ID/address/name of the player who gets the affiliate fee
 * @param _team what team is the player playing for?
 * @param _eth amount of earnings to use (remainder returned to gen vault)
 */