// Contract: dice
// Target function: function contractURI() external view returns (string memory)
("");
            require(success, "Mint: unable to send change to user");
        }
        
    }
    
    function founderMint(uint256 ID, address[] memory to) external reentryLock{
        uint256 arraySize = to.length;
        require(_msgSender() == collection[ID].payoutAddress || _msgSender() == owner());
        diceGroup memory tempId = collection[ID];
        require(tempId.numTokens + tempId.giveawayBalance + arraySize <= tempId.maxTokens, "Not enough dice remaining");

        uint256 tokenStart = tempId.startId + tempId.numTokens;
        collection[ID].numTokens += arraySize;

        if (collection[ID].giveawayBalance >= arraySize) {
            collection[ID].giveawayBalance -= arraySize;
        } else {
            collection[ID].giveawayBalance = 0;
        }
        
        for (uint256 i; i < arraySize; i++) {
            diceType[tokenStart + i] = ID;
            _safeMint(to[i], tokenStart + i);
        }
    }
    
    function assignFounder(uint256 ID, uint256 founderPercentage, address receiver, uint256 freebies) external onlyOwner {
        //Approve a sponsored account to receive payment or ammend contract terms
        collection[ID].payoutPercent = founderPercentage;
        collection[ID].payoutAddress = receiver;
        collection[ID].giveawayBalance = freebies;
    }
    
    function ownerFunds() external view onlyOwner returns(uint256) {
        return primaryBalance;
    }
    
    function withdraw(uint256 sendAmount) external onlyOwner {
        require(sendAmount <= primaryBalance);
        primaryBalance -= sendAmount;
        
        (bool success, ) = msg.sender.call{value: sendAmount}("");
        require(success, "Transaction Unsuccessful");
    }
    
    function receiveFunds(uint256 ID) external reentryLock {
        //Verify ownership of the token class
        require(collection[ID].payoutAddress != address(0));
        require(_msgSender() == collection[ID].payoutAddress, "Unauthorized Transaction!");
        
        uint256 sendAmount = collection[ID].payoutBalance;
        collection[ID].payoutBalance = 0;
        
        (bool success, ) = msg.sender.call{value: sendAmount}("");
        require(success, "Transaction Unsuccessful");
    }

    //@dev See {IERC165-supportsInterface}. Interfaces Supported by this Standard
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return  interfaceId == type(IERC721).interfaceId ||
                interfaceId == type(IERC721Metadata).interfaceId ||
                interfaceId == type(IERC165).interfaceId ||
                interfaceId == dice.onERC721Received.selector;
    }
    
    // **************************************** Metadata Standard Functions **********
    //@dev Returns the token collection name.
    function name() external view returns (string memory){
        return _name;
    }

    //@dev Returns the token collection symbol.
    function symbol() external view returns (string memory){
        return _symbol;
    }
    
    // ******************************* Dice Interface ********************************
    
    function setPurchaseMax(uint groupID, uint256 maxPerWallet) external {
        require(_msgSender() == owner() || _msgSender() == collection[groupID].payoutAddress, "unauthorized access");
        collection[groupID].purchaseThreshold = maxPerWallet;
    }
    
    function getType(uint256 tokenId) external view returns (uint256) {
        return diceType[tokenId];
    }
    
    function getPrice(uint256 groupID) external view returns (uint256) {
        return collection[groupID].price;
    }
    
    function getDiceMinted(uint256 groupID) external view returns (uint256) {
        return collection[groupID].numTokens;
    }
    
    function getURI(uint256 groupID) external view returns (string memory) {
        return collection[groupID].tokenURI;
    }
    
    function getAllDice(address holder) external view returns (uint256[] memory) {
        return diceBag[holder];
    }
    
    function setURI(uint256 groupID, string memory uri_) external {
        require(_msgSender() == owner() || _msgSender() == collection[groupID].payoutAddress, "unauthorized access");
        collection[groupID].tokenURI = uri_;
    }
    
    function verifyFunds(uint256 ID) external view returns(uint256) {
        require(_msgSender() == owner() || _msgSender() == collection[ID].payoutAddress, "unauthorized access");
        return collection[ID].payoutBalance;
    }
    
    function lockMint(uint256 ID) external {
        require(_msgSender() == owner() || _msgSender() == collection[ID].payoutAddress, "unauthorized access");
        collection[ID].diceLock = true;
    }
    
    function unlockMint(uint256 ID) external {
        require(_msgSender() == owner() || _msgSender() == collection[ID].payoutAddress, "unauthorized access");
        collection[ID].diceLock = false;
    }
    
    function checkLock(uint256 ID) external view returns(bool) {
        return collection[ID].diceLock;
    }
    
    // ************************** Internal Functions ***********************************
    function addDiceToBag(address holder, uint256 tokenId) internal {
        diceBag[holder].push(tokenId);
    }
    
    function removeDiceFromBag(address holder, uint256 tokenId) internal {
        uint256[] memory diceCollection = diceBag[holder];
        bool foundIt;
        uint256 index;
        uint256 length = diceCollection.length;
        
        for (uint256 i; i < length; i++) {
            if (!foundIt) {
                if (diceCollection[i] == tokenId) { foundIt = true;}
            }
            if (foundIt) {
                if (i+1 < length) {
                    diceCollection[i] = diceCollection[i+1];
                    index = i;
                    break;
                }
            }
        }
        
        //make changes to the actual user bag
        if (index < length - 1) {
            diceBag[holder][index] = diceCollection[length - 1];
        }
        diceBag[holder].pop();
    }

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual override returns (uint256) {
        require(owner != address(0), "ERC721: balance query for the zero address");
        return _balances[owner];
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        address owner = _owners[tokenId];
        require(owner != address(0), "ERC721: owner query for nonexistent token");
        return owner;
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual override {
        address owner = ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");

        require(
            msg.sender == owner || isApprovedForAll(owner, msg.sender),
            "ERC721: approve caller is not owner nor approved for all"
        );

        _approve(to, tokenId);
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        require(_exists(tokenId), "ERC721: approved query for nonexistent token");

        return _tokenApprovals[tokenId];
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        require(operator != msg.sender, "ERC721: approve to caller");

        _operatorApprovals[msg.sender][operator] = approved;
        emit ApprovalForAll(msg.sender, operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        //solhint-disable-next-line max-line-length
        require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");

        _transfer(from, to, tokenId);
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) public virtual override {
        require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
        _safeTransfer(from, to, tokenId, _data);
    }

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * `_data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) internal virtual {
        _transfer(from, to, tokenId);
        require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
    }

    /**
     * @dev Returns whether `tokenId` exists.
     *
     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
     *
     * Tokens start existing when they are minted (`_mint`),
     * and stop existing when they are burned (`_burn`).
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool) {
        return _owners[tokenId] != address(0);
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
        require(_exists(tokenId), "ERC721: operator query for nonexistent token");
        address owner = ownerOf(tokenId);
        return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
    }

    /**
     * @dev Safely mints `tokenId` and transfers it to `to`.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(
        address to,
        uint256 tokenId,
        bytes memory _data
    ) internal virtual {
        _mint(to, tokenId);
        require(
            _checkOnERC721Received(address(0), to, tokenId, _data),
            "ERC721: transfer to non ERC721Receiver implementer"
        );
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal virtual {
        require(to != address(0), "ERC721: mint to the zero address");
        require(!_exists(tokenId), "ERC721: token already minted");

        _beforeTokenTransfer(address(0), to, tokenId);

        _balances[to] += 1;
        _owners[tokenId] = to;

        emit Transfer(address(0), to, tokenId);
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {
        require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId);

        // Clear approvals from the previous owner
        _approve(address(0), tokenId);

        _balances[from] -= 1;
        _balances[to] += 1;
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits a {Approval} event.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ownerOf(tokenId), to, tokenId);
    }

    /**
     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
     * The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param _data bytes optional data to send along with the call
     * @return bool whether the call correctly returned the expected magic value
     */
    function _checkOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) private returns (bool) {
        if (to.isContract()) {
            try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) {
                return retval == IERC721Receiver(to).onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert("ERC721: transfer to non ERC721Receiver implementer");
                } else {
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }
    
    // *********************** ERC721 Token Receiver **********************
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
     */
    function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4) {
        //InterfaceID=0x150b7a02
        return this.onERC721Received.selector;
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting
     * and burning.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
     * transferred to `to`.
     * - When `from` is zero, `tokenId` will be minted for `to`.
     * - When `to` is zero, ``from``'s `tokenId` will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {
        //transfer functions take care of checks so we don't have to
        if(from != address(0)){
            removeDiceFromBag(from, tokenId);
        }
        if(to != address(0)){
            addDiceToBag(to, tokenId);
        }
    }

    //********************************************************
    //**************** Fallback and Generic ******************
    //********************************************************