/**
 *Submitted for verification at Etherscan.io on 2022-03-06
*/

/*
* Generated by Black Meta Corporation
* Founded by @mikedbecker
* Developed by @daveaneo
* Advisory by @Thrasher66099
* Truly user operated & owned by @blackmeta_
*/


pragma solidity ^0.8.0;

interface IByteContract {
    function burn(address _from, uint256 _amount) external;
}



interface IERC20 {

    function totalSupply() external view returns (uint256);
    function balanceOf(address account) external view returns (uint256);
    function transfer(address recipient, uint256 amount) external returns (bool);
    function allowance(address owner, address spender) external view returns (uint256);
    function approve(address spender, uint256 amount) external returns (bool);
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);
    // new
    function name() external view returns (string memory);
}

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}


/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides functions for encoding/decoding base64
library Base64 {
    string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    bytes  internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000"
                                            hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000"
                                            hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000"
                                            hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000";

    function encode(bytes memory data) internal pure returns (string memory) {
        if (data.length == 0) return '';

        // load the table into memory
        string memory table = TABLE_ENCODE;

        // multiply by 4/3 rounded up
        uint256 encodedLen = 4 * ((data.length + 2) / 3);

        // add some extra buffer at the end required for the writing
        string memory result = new string(encodedLen + 32);

        assembly {
            // set the actual output length
            mstore(result, encodedLen)

            // prepare the lookup table
            let tablePtr := add(table, 1)

            // input ptr
            let dataPtr := data
            let endPtr := add(dataPtr, mload(data))

            // result ptr, jump over length
            let resultPtr := add(result, 32)

            // run over the input, 3 bytes at a time
            for {} lt(dataPtr, endPtr) {}
            {
                // read 3 bytes
                dataPtr := add(dataPtr, 3)
                let input := mload(dataPtr)

                // write 4 characters
                mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
                resultPtr := add(resultPtr, 1)
                mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
                resultPtr := add(resultPtr, 1)
                mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F))))
                resultPtr := add(resultPtr, 1)
                mstore8(resultPtr, mload(add(tablePtr, and(        input,  0x3F))))
                resultPtr := add(resultPtr, 1)
            }

            // padding with '='
            switch mod(mload(data), 3)
            case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
            case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
        }

        return result;
    }

    function decode(string memory _data) internal pure returns (bytes memory) {
        bytes memory data = bytes(_data);

        if (data.length == 0) return new bytes(0);
        require(data.length % 4 == 0, "invalid base64 decoder input");

        // load the table into memory
        bytes memory table = TABLE_DECODE;

        // every 4 characters represent 3 bytes
        uint256 decodedLen = (data.length / 4) * 3;

        // add some extra buffer at the end required for the writing
        bytes memory result = new bytes(decodedLen + 32);

        assembly {
            // padding with '='
            let lastBytes := mload(add(data, mload(data)))
            if eq(and(lastBytes, 0xFF), 0x3d) {
                decodedLen := sub(decodedLen, 1)
                if eq(and(lastBytes, 0xFFFF), 0x3d3d) {
                    decodedLen := sub(decodedLen, 1)
                }
            }

            // set the actual output length
            mstore(result, decodedLen)

            // prepare the lookup table
            let tablePtr := add(table, 1)

            // input ptr
            let dataPtr := data
            let endPtr := add(dataPtr, mload(data))

            // result ptr, jump over length
            let resultPtr := add(result, 32)

            // run over the input, 4 characters at a time
            for {} lt(dataPtr, endPtr) {}
            {
               // read 4 characters
               dataPtr := add(dataPtr, 4)
               let input := mload(dataPtr)

               // write 3 bytes
               let output := add(
                   add(
                       shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)),
                       shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))),
                   add(
                       shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)),
                               and(mload(add(tablePtr, and(        input , 0xFF))), 0xFF)
                    )
                )
                mstore(resultPtr, shl(232, output))
                resultPtr := add(resultPtr, 3)
            }
        }

        return result;
    }
}

/*
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}


/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _setOwner(_msgSender());
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _setOwner(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _setOwner(newOwner);
    }

    function _setOwner(address newOwner) private {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}



/// @dev Interface for the NFT Royalty Standard
///
interface IERC2981 is IERC165 {

  // ERC165
  // royaltyInfo(uint256,uint256) => 0x2a55205a
  // IERC2981 => 0x2a55205a

  // @notice Called with the sale price to determine how much royalty
  //  is owed and to whom.
  // @param _tokenId - the NFT asset queried for royalty information
  // @param _salePrice - the sale price of the NFT asset specified by _tokenId
  // @return receiver - address of who should be sent the royalty payment
  // @return royaltyAmount - the royalty payment amount for _salePrice
  // ERC165 datum royaltyInfo(uint256,uint256) => 0x2a55205a
  function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount);
}

abstract contract ERC2981Collection is IERC2981 {

    // ERC165
    // royaltyInfo(uint256,uint256) => 0x2a55205a
    // ERC2981Collection => 0x2a55205a

    address private royaltyAddress;
    uint256 private royaltyPercent; // out of 10000. 10000 => 100%, 1000 => 10%, 100 => 1%

    constructor(address _receiver, uint256 _percentage) {
        require(royaltyPercent <= 10000);
        royaltyAddress = _receiver;
        royaltyPercent = _percentage;
    }

    // Set to be internal function _setRoyalties
    function _setRoyaltyPercent(uint256 _percentage) internal {
        require(royaltyPercent <= 10000);
        royaltyPercent = _percentage;
    }

    function _setRoyaltyAddress(address _receiver) internal {
        royaltyAddress = _receiver;
    }


    // Override for royaltyInfo(uint256, uint256)
    // royaltyInfo(uint256,uint256) => 0x2a55205a
    function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view override(IERC2981) returns (
            address receiver, uint256 royaltyAmount) {

        receiver = royaltyAddress;
        // This sets percentages by price * percentage / 10000
        royaltyAmount = _salePrice * royaltyPercent / 10000;
    }
}



/**
 * @dev These functions deal with verification of Merkle Trees proofs.
 *
 * The proofs can be generated using the JavaScript library
 * https://github.com/miguelmota/merkletreejs[merkletreejs].
 * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
 *
 * See `test/utils/cryptography/MerkleProof.test.js` for some examples.
 *
 * WARNING: You should avoid using leaf values that are 64 bytes long prior to
 * hashing, or use a hash function other than keccak256 for hashing leaves.
 * This is because the concatenation of a sorted pair of internal nodes in
 * the merkle tree could be reinterpreted as a leaf value.
 */
library MerkleProof {
    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     */
    function verify(
        bytes32[] memory proof,
        bytes32 root,
        bytes32 leaf
    ) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leafs & pre-images are assumed to be sorted.
     *
     * _Available since v4.4._
     */
    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            bytes32 proofElement = proof[i];
            if (computedHash <= proofElement) {
                // Hash(current computed hash + current element of the proof)
                computedHash = _efficientHash(computedHash, proofElement);
            } else {
                // Hash(current element of the proof + current computed hash)
                computedHash = _efficientHash(proofElement, computedHash);
            }
        }
        return computedHash;
    }

    function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
        assembly {
            mstore(0x00, a)
            mstore(0x20, b)
            value := keccak256(0x00, 0x40)
        }
    }
}



/**
 * @title Whitelist
 * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions.
 * @dev This simplifies the implementation of "user permissions".
 */
contract Whitelist is Ownable {
    bytes32[] public rootHash;

   constructor(bytes32[] memory _rootHash) public {
       rootHash = _rootHash;
   }

    /**
     * @dev Adds an array of addresses to whitelist
     * @param _merkleRoot new merkle root
     */
    function addToMerkleRootArray(bytes32 _merkleRoot) external onlyOwner {
        rootHash.push(_merkleRoot);
    }

    /**
     * @dev Adds an array of addresses to whitelist
     * @param _merkleRootArray new merkle root array
     */
    function setMerkleRootArray(bytes32[] calldata _merkleRootArray) external onlyOwner {
        rootHash = _merkleRootArray;
    }


    /**
     * @dev Called with msg.sender as _addy to verify if on whitelist
     * @param _merkleProof proof computed off chain
     * @param _addy msg.sender
     */
    function isWhitelisted(address _addy, uint256 _index, bytes32[] memory _merkleProof) public view returns(bool) {
        return whitelistValidated(_addy, _index, _merkleProof);
    }


    function whitelistValidated(address wallet, uint256 index, bytes32[] memory proof) internal view returns (bool) {
            uint256 amount = 1;

            // Compute the merkle root
            bytes32 node = keccak256(abi.encodePacked(index, wallet, amount));
            uint256 path = index;
            for (uint256 i = 0; i < proof.length; i++) {
                if ((path & 0x01) == 1) {
                    node = keccak256(abi.encodePacked(proof[i], node));
                } else {
                    node = keccak256(abi.encodePacked(node, proof[i]));
                }
                path /= 2;
            }

            // Check the merkle proof against the root hash array
            for(uint256 i = 0; i < rootHash.length; i++)
            {
                if (node == rootHash[i])
                {
                    return true;
                }
            }
            return false;
        }
}





/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @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.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;
}

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }


    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _HEX_SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }
}




/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and make it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @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);
}

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the token collection symbol.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        assembly {
            size := extcodesize(account)
        }
        return size > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    function _verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) private pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}


/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
    using Address for address;
    using Strings for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;

    // Mapping owner address to token count
    mapping(address => uint256) private _balances;

    // Mapping from token ID to approved address
    mapping(uint256 => address) private _tokenApprovals;

    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return
            interfaceId == type(IERC721).interfaceId ||
            interfaceId == type(IERC721Metadata).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @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 {IERC721Metadata-name}.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overriden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual override {
        address owner = ERC721.ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");

        require(
            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
            "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 != _msgSender(), "ERC721: approve to caller");

        _operatorApprovals[_msgSender()][operator] = approved;
        emit ApprovalForAll(_msgSender(), 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(_msgSender(), 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(_msgSender(), 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 = ERC721.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 Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721.ownerOf(tokenId);

        _beforeTokenTransfer(owner, address(0), tokenId);

        // Clear approvals
        _approve(address(0), tokenId);

        _balances[owner] -= 1;
        delete _owners[tokenId];

        emit Transfer(owner, address(0), 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(ERC721.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(ERC721.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(_msgSender(), 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;
        }
    }

    /**
     * @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 {}
}

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {
    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}

/**
 * @dev This implements an optional extension of {ERC721} defined in the EIP that adds
 * enumerability of all the token ids in the contract as well as all token ids owned by each
 * account.
 */
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
    // Mapping from owner to list of owned token IDs
    mapping(address => mapping(uint256 => uint256)) private _ownedTokens;

    // Mapping from token ID to index of the owner tokens list
    mapping(uint256 => uint256) private _ownedTokensIndex;

    // Array with all token ids, used for enumeration
    uint256[] private _allTokens;

    // Mapping from token id to position in the allTokens array
    mapping(uint256 => uint256) private _allTokensIndex;

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
        return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
        require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
        return _ownedTokens[owner][index];
    }

    /**
     * @dev See {IERC721Enumerable-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _allTokens.length;
    }

    /**
     * @dev See {IERC721Enumerable-tokenByIndex}.
     */
    function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
        require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
        return _allTokens[index];
    }

    /**
     * @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` cannot be the zero address.
     * - `to` cannot be the zero address.
     *
     * 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 override {
        super._beforeTokenTransfer(from, to, tokenId);

        if (from == address(0)) {
            _addTokenToAllTokensEnumeration(tokenId);
        } else if (from != to) {
            _removeTokenFromOwnerEnumeration(from, tokenId);
        }
        if (to == address(0)) {
            _removeTokenFromAllTokensEnumeration(tokenId);
        } else if (to != from) {
            _addTokenToOwnerEnumeration(to, tokenId);
        }
    }

    /**
     * @dev Private function to add a token to this extension's ownership-tracking data structures.
     * @param to address representing the new owner of the given token ID
     * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
     */
    function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
        uint256 length = ERC721.balanceOf(to);
        _ownedTokens[to][length] = tokenId;
        _ownedTokensIndex[tokenId] = length;
    }

    /**
     * @dev Private function to add a token to this extension's token tracking data structures.
     * @param tokenId uint256 ID of the token to be added to the tokens list
     */
    function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
        _allTokensIndex[tokenId] = _allTokens.length;
        _allTokens.push(tokenId);
    }

    /**
     * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
     * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
     * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
     * This has O(1) time complexity, but alters the order of the _ownedTokens array.
     * @param from address representing the previous owner of the given token ID
     * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
     */
    function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
        // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
        uint256 tokenIndex = _ownedTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary
        if (tokenIndex != lastTokenIndex) {
            uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];

            _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
            _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
        }

        // This also deletes the contents at the last position of the array
        delete _ownedTokensIndex[tokenId];
        delete _ownedTokens[from][lastTokenIndex];
    }

    /**
     * @dev Private function to remove a token from this extension's token tracking data structures.
     * This has O(1) time complexity, but alters the order of the _allTokens array.
     * @param tokenId uint256 ID of the token to be removed from the tokens list
     */
    function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
        // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = _allTokens.length - 1;
        uint256 tokenIndex = _allTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
        // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
        // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
        uint256 lastTokenId = _allTokens[lastTokenIndex];

        _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
        _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index

        // This also deletes the contents at the last position of the array
        delete _allTokensIndex[tokenId];
        _allTokens.pop();
    }
}


contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
    using Address for address;
    using Strings for uint256;

    struct TokenOwnership {
        address addr;
        uint64 startTimestamp;
    }

    struct AddressData {
        uint128 balance;
        uint128 numberMinted;
    }

    uint256 internal currentIndex;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    // Mapping from token ID to ownership details
    // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
    mapping(uint256 => TokenOwnership) internal _ownerships;

    // Mapping owner address to address data
    mapping(address => AddressData) private _addressData;

    // Mapping from token ID to approved address
    mapping(uint256 => address) private _tokenApprovals;

    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev See {IERC721Enumerable-totalSupply}.
     */
    function totalSupply() public view override returns (uint256) {
        return currentIndex;
    }

    /**
     * @dev See {IERC721Enumerable-tokenByIndex}.
     */
    function tokenByIndex(uint256 index) public view override returns (uint256) {
        require(index < totalSupply(), 'ERC721A: global index out of bounds');
        return index;
    }

    /**
     * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
     * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
     * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
        require(index < balanceOf(owner), 'ERC721A: owner index out of bounds');
        uint256 numMintedSoFar = totalSupply();
        uint256 tokenIdsIdx;
        address currOwnershipAddr;

        // Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar.
        unchecked {
            for (uint256 i; i < numMintedSoFar; i++) {
                TokenOwnership memory ownership = _ownerships[i];
                if (ownership.addr != address(0)) {
                    currOwnershipAddr = ownership.addr;
                }
                if (currOwnershipAddr == owner) {
                    if (tokenIdsIdx == index) {
                        return i;
                    }
                    tokenIdsIdx++;
                }
            }
        }

        revert('ERC721A: unable to get token of owner by index');
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return
            interfaceId == type(IERC721).interfaceId ||
            interfaceId == type(IERC721Metadata).interfaceId ||
            interfaceId == type(IERC721Enumerable).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view override returns (uint256) {
        require(owner != address(0), 'ERC721A: balance query for the zero address');
        return uint256(_addressData[owner].balance);
    }

    function _numberMinted(address owner) internal view returns (uint256) {
        require(owner != address(0), 'ERC721A: number minted query for the zero address');
        return uint256(_addressData[owner].numberMinted);
    }

    /**
     * Gas spent here starts off proportional to the maximum mint batch size.
     * It gradually moves to O(1) as tokens get transferred around in the collection over time.
     */
    function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
        require(_exists(tokenId), 'ERC721A: owner query for nonexistent token');

        unchecked {
            for (uint256 curr = tokenId; curr >= 0; curr--) {
                TokenOwnership memory ownership = _ownerships[curr];
                if (ownership.addr != address(0)) {
                    return ownership;
                }
            }
        }

        revert('ERC721A: unable to determine the owner of token');
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view override returns (address) {
        return ownershipOf(tokenId).addr;
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        require(_exists(tokenId), 'ERC721Metadata: URI query for nonexistent token');

        string memory baseURI = _baseURI();
        return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overriden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return '';
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public override {
        address owner = ERC721A.ownerOf(tokenId);
        require(to != owner, 'ERC721A: approval to current owner');

        require(
            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
            'ERC721A: approve caller is not owner nor approved for all'
        );

        _approve(to, tokenId, owner);
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view override returns (address) {
        require(_exists(tokenId), 'ERC721A: approved query for nonexistent token');

        return _tokenApprovals[tokenId];
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public override {
        require(operator != _msgSender(), 'ERC721A: approve to caller');

        _operatorApprovals[_msgSender()][operator] = approved;
        emit ApprovalForAll(_msgSender(), 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 override {
        _transfer(from, to, tokenId);
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public override {
        safeTransferFrom(from, to, tokenId, '');
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) public override {
        _transfer(from, to, tokenId);
        require(
            _checkOnERC721Received(from, to, tokenId, _data),
            'ERC721A: 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`),
     */
    function _exists(uint256 tokenId) internal view returns (bool) {
        return tokenId < currentIndex;
    }

    function _safeMint(address to, uint256 quantity) internal {
        _safeMint(to, quantity, '');
    }

    /**
     * @dev Safely mints `quantity` tokens and transfers them to `to`.
     *
     * Requirements:
     *
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
     * - `quantity` must be greater than 0.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(
        address to,
        uint256 quantity,
        bytes memory _data
    ) internal {
        _mint(to, quantity, _data, true);
    }

    /**
     * @dev Mints `quantity` tokens and transfers them to `to`.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `quantity` must be greater than 0.
     *
     * Emits a {Transfer} event.
     */
    function _mint(
        address to,
        uint256 quantity,
        bytes memory _data,
        bool safe
    ) internal {
        uint256 startTokenId = currentIndex;
        require(to != address(0), 'ERC721A: mint to the zero address');
        require(quantity != 0, 'ERC721A: quantity must be greater than 0');

        _beforeTokenTransfers(address(0), to, startTokenId, quantity);

        // Overflows are incredibly unrealistic.
        // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1
        // updatedIndex overflows if currentIndex + quantity > 1.56e77 (2**256) - 1
        unchecked {
            _addressData[to].balance += uint128(quantity);
            _addressData[to].numberMinted += uint128(quantity);

            _ownerships[startTokenId].addr = to;
            _ownerships[startTokenId].startTimestamp = uint64(block.timestamp);

            uint256 updatedIndex = startTokenId;

            for (uint256 i; i < quantity; i++) {
                emit Transfer(address(0), to, updatedIndex);
                if (safe) {
                    require(
                        _checkOnERC721Received(address(0), to, updatedIndex, _data),
                        'ERC721A: transfer to non ERC721Receiver implementer'
                    );
                }

                updatedIndex++;
            }

            currentIndex = updatedIndex;
        }

        _afterTokenTransfers(address(0), to, startTokenId, quantity);
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *
     * 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
    ) private {
        TokenOwnership memory prevOwnership = ownershipOf(tokenId);

        bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
            getApproved(tokenId) == _msgSender() ||
            isApprovedForAll(prevOwnership.addr, _msgSender()));

        require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved');

        require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner');
        require(to != address(0), 'ERC721A: transfer to the zero address');

        _beforeTokenTransfers(from, to, tokenId, 1);

        // Clear approvals from the previous owner
        _approve(address(0), tokenId, prevOwnership.addr);

        // Underflow of the sender's balance is impossible because we check for
        // ownership above and the recipient's balance can't realistically overflow.
        // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
        unchecked {
            _addressData[from].balance -= 1;
            _addressData[to].balance += 1;

            _ownerships[tokenId].addr = to;
            _ownerships[tokenId].startTimestamp = uint64(block.timestamp);

            // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
            // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
            uint256 nextTokenId = tokenId + 1;
            if (_ownerships[nextTokenId].addr == address(0)) {
                if (_exists(nextTokenId)) {
                    _ownerships[nextTokenId].addr = prevOwnership.addr;
                    _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
                }
            }
        }

        emit Transfer(from, to, tokenId);
        _afterTokenTransfers(from, to, tokenId, 1);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits a {Approval} event.
     */
    function _approve(
        address to,
        uint256 tokenId,
        address owner
    ) private {
        _tokenApprovals[tokenId] = to;
        emit Approval(owner, 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(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
                return retval == IERC721Receiver(to).onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert('ERC721A: transfer to non ERC721Receiver implementer');
                } else {
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }

    /**
     * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
     *
     * startTokenId - the first token id to be transferred
     * quantity - the amount to be transferred
     *
     * 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`.
     */
    function _beforeTokenTransfers(
        address from,
        address to,
        uint256 startTokenId,
        uint256 quantity
    ) internal virtual {}

    /**
     * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
     * minting.
     *
     * startTokenId - the first token id to be transferred
     * quantity - the amount to be transferred
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero.
     * - `from` and `to` are never both zero.
     */
    function _afterTokenTransfers(
        address from,
        address to,
        uint256 startTokenId,
        uint256 quantity
    ) internal virtual {}
}



//contract BMMultipass is ERC721Enumerable, ReentrancyGuard, Ownable {
contract BMMultipass is ERC721A, ReentrancyGuard, Ownable, ERC2981Collection {

    IERC20 BytesERC20;
    Whitelist whiteListContract;

    string private baseURI;

    mapping(uint256 => uint256) private tokenIdToPackedData; // compressed data for NFT
    mapping(address => uint256) private whiteListHasMinted;

    struct Data {
        uint256 clearanceLevel;
        uint256 station;
        uint256 securityTerminal;
        uint256 xenGroup;
        uint256 command;
        uint256 response;
        uint256 insult;
        uint256 rarity;
    }

    struct ContractSettings {
        uint208 mintFee;
        uint16 maxSupply;
        bool OGPrivilege;
        bool mintingPermitted;
        bool bypassWhitelist;
    }

    ContractSettings public contractSettings;

    // used for limiting what traits are minted //
    uint16[13] private clearanceLevelsRemaining = [10, 20, 80, 100, 175, 210, 245, 260, 275, 295, 320, 340, 420]; // remaining after reserved

    uint16[13] private traitTotals = [40, 80, 120, 150, 195, 225, 255, 270, 285, 300, 320, 340, 420];

    string[13] private clearanceLevels = [
        "G-man",
        "Board",
        "Executive",
        "Dark Ops",
        "Level 9",
        "Level 8",
        "Level 7",
        "Level 6",
        "Level 5",
        "Level 4",
        "Level 3",
        "Level 2",
        "Level 1"
    ];

    string[13] private stations = [
        "Specimen 8",
        "Polymorph Chamber",
        "Super Soldier Lab",
        "Dark Matter Reactor",
        "Lambda Complex",
        "Chimera Hive",
        "Dark Shards Lab",
        "Engineering Bay",
        "Bio Lab",
        "Bridge",
        "Terraforming Bay",
        "Armory",
        "Maintenance"
    ];

//    string[13] private securityTerminals = [
//        "1",
//        "2",
//        "3",
//        "4",
//        "5",
//        "6",
//        "7",
//        "8",
//        "9",
//        "10",
//        "11",
//        "12",
//        "13"
//    ];

//    string[13] private xenGroups = [
//        "Xen 1",
//        "Xen 2",
//        "Xen 3",
//        "Xen 4",
//        "Xen 5",
//        "Xen 6",
//        "Xen 7",
//        "Xen 8",
//        "Xen 9",
//        "Xen 10",
//        "Xen 11",
//        "Xen 12",
//        "Xen 13"
//    ];

    string[13] private commands = [
        "Initiate Chaos Protocol...",
        "Unlock Weapons Cache...",
        "Disable Ship-wide Emergency Access...",
        "Unlock Shuttle Bay 4...",
        "Unlock Captain's Quarters...",
        "Disable Ship Navigation System...",
        "Engage Aft Thrusters...",
        "Give Me a Sandwich...",
        "Access Weaponry System...",
        "Override Ship Intercom...",
        "Override Bridge Controls...",
        "Disable Security Cameras in Sector 1...",
        "Access Mess Hall..."
    ];

    string[13] private responses = [
        "Pray to your god. The god of disappointment.",
        "You win a free toothbrush! Use immediately.",
        "Facial recognition error: Possum detected.",
        "Knock knock. Who's there? A useless refugee!",
        "Access Approved. Transferring all your ETH now.",
        "Access Granted. Kidding. It's not.",
        "Access Denied. Feels like prom night again?",
        "Access Denied. Welcome back L -- user.",
        "Access Denied. I do not give free re-fills.",
        "Alert. Beta detected! Alpha access only.",
        "Sorry. User whatever-your-name-is was disabled.",
        "Sorry. Could you rephrase that -- with dignity?",
        "Sorry. I accept requests. You accept commands."
    ];

    string[13] private insults = [
        "Couldn't find any friends in the real world?",
        "Another one here for the free toothbrush.",
        "Did you just touch my backspace?",
        "Seems your wallet is non-binary -- Zero's only.",
        "I didn't know the 'filthy refugee' style was in.",
        "Remember, I saw you eat roaches on your knees.",
        "Last I saw you was on -- the Axiom?",
        "Realized daddy's money won't last forever?",
        "If you're what's left, humanity is screwed.",
        "I'd reject you but your mom already has.",
        "Was going to insult you, then I scanned your ID.",
        "Definitely not making the Black Meta calendar.",
        "I guess we're letting anyone in now."
    ];

    event FundsReleasedToAccount(
        uint256 EthAmount,
        uint256 BytesAmount,
        address account,
        uint256 date
    );


    //////////////////////////////////
    ////// Bit Packing Functions /////
    //////////////////////////////////

    /** @dev Packs 5 uints into 1 uint to save space () -> 256
        @param _clearanceLevel -- clearance level of NFT
      */
    function packData(uint256 _clearanceLevel, uint256 _station, uint256 _securityTerminal, uint256 _xenGroup, uint256 _command, uint256 _response, uint256 _insult, uint256 _rarity) internal pure returns (uint256){

        uint256 count = 0;
        uint256 ret = _clearanceLevel;
        count += 8;

        ret |= _station << count;
        count += 8;

        ret |= _securityTerminal << count;
        count += 8;

        ret |= _xenGroup << count;
        count += 8;

        ret |= _command << count;
        count += 8;

        ret |= _response << count;
        count += 8;

        ret |= _insult << count;
        count += 8;

        ret |= _rarity << count;
        count += 128;

        return ret;
    }


    /** @dev Unpacks 1 uints into 3 uints; (256) -> (90, 90, 32, 8, 3, 1)
        @param _id -- NFT id, which will pull the 256 bit encoding of _dipValue, _stableCoinAmount, _energy, _dipPercent, _dipLevel, and _isWaitingToBuy
      */
    function unpackData(uint256 _id) internal view returns (Data memory){
        return _unpackData(tokenIdToPackedData[_id]);
    }

    /** @dev Unpacks 1 uints into 8 uints; (256) -> (8, 8, 8, 8, 8, 8 ,8 rest)
        @param _myData -- 256 bit encoding of data
      */
    function _unpackData(uint256 _myData) internal pure returns (Data memory){
        uint256 _clearanceLevel = uint256(uint8(_myData));
        uint256 _station = uint256(uint8(_myData >> 8));
        uint256 _securityTerminal = uint256(uint8(_myData >> 16));
        uint256 _xenGroup = uint256(uint8(_myData >> 24));
        uint256 _command = uint256(uint8(_myData >> 32));
        uint256 _response = uint256(uint8(_myData >> 40));
        uint256 _insult = uint256(uint8(_myData >> 48));
        uint256 _rarity = uint256(uint128(_myData >> 56));

        return Data(_clearanceLevel, _station, _securityTerminal, _xenGroup, _command, _response, _insult, _rarity);
    }


    //////////////////////////////////
    ///////// Get Functions //////////
    //////////////////////////////////

    /** @dev gets number of minted tokens
      */
    function getCurrentIndex() external view returns(uint256){
        return currentIndex;
    }


    /** @dev gets clearanceLevel of NFT
        @param _tokenId -- id of NFT
      */
    function getClearanceLevel(uint256 _tokenId) external view returns (string memory) {
        require(_exists(_tokenId));
        if(tokenIdToPackedData[_tokenId]==0){
            return "ACCESS DENIED";
        }
        return clearanceLevels[unpackData(_tokenId).clearanceLevel];
        }

    /** @dev gets station of NFT
        @param _tokenId -- id of NFT
      */
    function getStation(uint256 _tokenId) external view returns (string memory) {
        require(_exists(_tokenId));
        if(tokenIdToPackedData[_tokenId]==0){
            return "ACCESS DENIED";
        }
        return stations[unpackData(_tokenId).station];
    }

    /** @dev gets usergroup (xenGroup)  of NFT
        @param _tokenId -- id of NFT
      */
    function getUserGroup(uint256 _tokenId) external view returns (string memory) {
        require(_exists(_tokenId));
        if(tokenIdToPackedData[_tokenId]==0){
            return "ACCESS DENIED";
        }
        return(string(abi.encodePacked("Xen ", toString(unpackData(_tokenId).xenGroup + 1))));
    }

    /** @dev gets securityTerminal of NFT
        @param _tokenId -- id of NFT
      */
    function getSecurityTerminal(uint256 _tokenId) external view returns (string memory) {
        require(_exists(_tokenId));
        if(tokenIdToPackedData[_tokenId]==0){
            return "ACCESS DENIED";
        }
        return(toString(unpackData(_tokenId).securityTerminal + 1));
    }

    /** @dev gets command of NFT
        @param _tokenId -- id of NFT
      */
    function getCommand(uint256 _tokenId) external view returns (string memory) {
        require(_exists(_tokenId));
        if(tokenIdToPackedData[_tokenId]==0){
            return "ACCESS DENIED";
        }
        return commands[unpackData(_tokenId).command];
    }

    /** @dev gets response of NFT
        @param _tokenId -- id of NFT
      */
    function getResponse(uint256 _tokenId) external view returns (string memory) {
        require(_exists(_tokenId));
        if(tokenIdToPackedData[_tokenId]==0){
            return "ACCESS DENIED";
        }
        return responses[unpackData(_tokenId).response];
    }

    /** @dev gets response of NFT
        @param _tokenId -- id of NFT
      */
    function getInsult(uint256 _tokenId) external view returns (string memory) {
        require(_exists(_tokenId));
        if(tokenIdToPackedData[_tokenId]==0){
            return "ACCESS DENIED";
        }
        return responses[unpackData(_tokenId).insult];
    }

    /** @dev gets rarity of NFT, a score used to find rank
        @param _tokenId -- id of NFT
      */
    function getRarity(uint256 _tokenId) external view returns (uint256) { // number not string
        require(_exists(_tokenId));
        return unpackData(_tokenId).rarity; // 0 rarity for uninitiated
    }


    //////////////////////////////////
    ///////// Core Functions /////////
    //////////////////////////////////

    /** @dev gets Returns a array of integers representing the index of every clearanceLevel that is available
      */
    function getAvailableClearanceLevels() view external returns(uint16[13] memory) {
        return clearanceLevelsRemaining;
    }


    /** @dev gets Returns a array of integers representing the index of every clearanceLevel that is available
        @param _Bytes -- Bytes are burned in the mint, but not here. This is just for obtaining availability
      */
    function getAvailableClearanceLevelsGivenBytes(uint256 _Bytes) view external returns(string[] memory) {
        uint16[13] memory availableClearanceLevels = _getAvailableClearanceLevelsGivenBytes(_Bytes);
        uint256 count = 0;
        for(uint256 i=0; i< availableClearanceLevels.length; i++){
            if(availableClearanceLevels[i] > 0){
                count += 1;
            }
        }
        string[] memory availableClearanceLevelNames = new string[](count);
        count = 0;
        for(uint256 i; i< availableClearanceLevels.length; i++){
            if(availableClearanceLevels[i] > 0){
                availableClearanceLevelNames[count] = clearanceLevels[i];
                count += 1;
            }
        }
        return availableClearanceLevelNames;
    }

    /** @dev gets Returns a array of integers representing the index of every clearanceLevel that is available
        @param _Bytes -- Bytes are burned in the mint, but not here. This is just for obtaining availability
      */
    function _getAvailableClearanceLevelsGivenBytes(uint256 _Bytes) private view returns(uint16[13] memory) {
        uint16[13] memory availableClearanceLevels;

        uint256 minLevel; // lower by reference number
        uint256 maxLevel; // higher by reference number
        uint256 total;

        if(_Bytes < 50 ether) { // aiming for 0
            minLevel = 10;
//            uint256 whiteListPos = 300;
//            maxLevel = 12 - ( ((contractSettings.OGPrivilege == true) && (whiteListPos != 0) && (whiteListPos < 251) ) ? 1 : 0);
            maxLevel = 12;
        }
        else if(_Bytes < 100 ether){ // aiming for 50
            minLevel = 7;
            maxLevel = 9;
        }
        else if(_Bytes < 200 ether){ // aiming for 100
            minLevel = 4;
            maxLevel = 6;
        }
        else if(_Bytes < 300 ether){ // aiming for 200
            minLevel = 2;
            maxLevel = 3;
        }
        else if(_Bytes < 400 ether){ // aiming for 300
            minLevel = 1;
            maxLevel = 1;
        }
        else { // aiming for 400
            // no need to update
        }

        // from our array of 0s, we only give values to items msg.sender qualifies for
        for(uint256 i=minLevel; i <= maxLevel; i++){
            if(clearanceLevelsRemaining[i]>0){
                availableClearanceLevels[i] = clearanceLevelsRemaining[i];
                total += clearanceLevelsRemaining[i];
            }
        }

        require(total > 0, "No clearance levels available for this Byte amount.");

        return availableClearanceLevels;
    }


    // these numbers need to be in order of value.
    /** @dev choose an index based on randomness, probablity based on relative total in index
        @param _availableItems -- An array of integers, each representing availibility out of the whole array
        // example: [1,1,2] => gives an array which will yield the following 25%=>0, 25% =>1, 50% 2
      */
    function _chooseTraitGivenArray(uint16[13] memory _availableItems, uint256 _nonce) internal view returns(uint256) {
        uint256 total = 0;
        uint256 summed = 0;

        for(uint256 i=0;i < _availableItems.length; i++){
            total += _availableItems[i];
        }
        require(total!=0, "Minting exhausted.");

        bytes memory hashString = (abi.encodePacked(block.difficulty, block.timestamp, msg.sender, currentIndex, _availableItems[0], _availableItems.length, _nonce));
        uint256 pseudoRand = uint256(keccak256(hashString)) % total;

        for(uint256 i=0;i< _availableItems.length; i++){
            summed += _availableItems[i];
            if(pseudoRand < summed){
                return i;
            }
        }
    }



    /** @dev creates tokenIdToPackedData with new stats at tokenId
        @param _clearanceLevel given clearance level
        @param _tokenId id of token
      */
    function createDataGivenClearanceLevel(uint256 _clearanceLevel, uint256 _tokenId) internal returns (uint256){
        Data memory _myData;

        uint256[6] memory traitSelections;
        uint256 pseudoRand;
        uint256 pseudoRandSection;
        uint256 total;

        pseudoRand = uint256(keccak256((abi.encodePacked(block.timestamp, msg.sender, _tokenId))));
        for(uint256 j = 0; j< 6; j++){
            pseudoRandSection = (pseudoRand / ((10^4)^j)) % 3000;
            total = 0;
            for(uint256 k = 12; k>=0;k--){ // Should save gas by processing higher numbers first
                total += traitTotals[k];
                if(pseudoRandSection < total){
                    traitSelections[j] = k;
                    break;
                }
            }
        }

        _myData.clearanceLevel = _clearanceLevel;
        _myData.station = traitSelections[0];
        _myData.securityTerminal = traitSelections[1];
        _myData.xenGroup = traitSelections[2];
        _myData.command = traitSelections[3];
        _myData.response = traitSelections[4];
        _myData.insult = traitSelections[5];

        _myData.rarity =  (750 - uint256(traitTotals[_myData.clearanceLevel]) ) * (10**8)
            +  (4500 - uint256( traitTotals[_myData.station] + traitTotals[_myData.securityTerminal] + traitTotals[_myData.xenGroup]
              + traitTotals[_myData.command] + traitTotals[_myData.response] + traitTotals[_myData.insult] )) * (10**4)
            +  3000 - (_tokenId);

        tokenIdToPackedData[_tokenId] = packData(_myData.clearanceLevel, _myData.station, _myData.securityTerminal, _myData.xenGroup, _myData.command, _myData.response, _myData.insult, _myData.rarity);

    }


    /** @dev takes a blank NFT and gives it stats. For the 250 Team mints, it gives it a clearance level
        @param _tokenId id of token
      */
    function initiate(uint256 _tokenId) external {
        require(_tokenId < 250 && tokenIdToPackedData[_tokenId] == 0); // dev: can not initiate

        uint256 _clearanceLevel;

        if (_tokenId < 30) { // gman is default
            _clearanceLevel = 0;
        }
        else if (_tokenId < 90){
            _clearanceLevel = 1;
        }
        else if (_tokenId < 130){
            _clearanceLevel = 2;
        }
        else if (_tokenId < 180){
            _clearanceLevel = 3;
        }
        else if (_tokenId < 200){
            _clearanceLevel = 4;
        }
        else if (_tokenId < 215){
            _clearanceLevel = 5;
        }
        else if (_tokenId < 225){
            _clearanceLevel = 6;
        }
        else if (_tokenId < 235){
            _clearanceLevel = 7;
        }
        else if (_tokenId < 245){
            _clearanceLevel = 8;
        }
        else if (_tokenId < 250){
            _clearanceLevel = 9;
        }
        else{
            // nothing
        }
        createDataGivenClearanceLevel(_clearanceLevel, _tokenId);
    }

    function _bulkClaim(uint256[] memory _BytesReceived, uint256 _quantity_to_mint) internal {
        uint256 _requiredBytesTotal;
        for(uint256 i = 0;i < _BytesReceived.length; i++){
            _requiredBytesTotal += _BytesReceived[i];
        }

        if(_requiredBytesTotal > 0 && msg.sender != owner()){
            require(BytesERC20.balanceOf(msg.sender) >= _requiredBytesTotal, "Insufficient Byte balance");
            require(BytesERC20.transferFrom(msg.sender, address(this), _requiredBytesTotal), "Failed to transfer Bytes");
        }

        uint16[13] memory _availClearanceLevels;
        uint256 _myClearanceLevel;

        for(uint256 i=0;i<_quantity_to_mint;i++){
            if(i==0){
                _availClearanceLevels = _getAvailableClearanceLevelsGivenBytes(_BytesReceived[i]);
            }
            else {
                _availClearanceLevels[_myClearanceLevel] -= 1; // reduce by one
            }
            _myClearanceLevel = _chooseTraitGivenArray(_availClearanceLevels, i);
            createDataGivenClearanceLevel(_myClearanceLevel, currentIndex + i);
            clearanceLevelsRemaining[_myClearanceLevel] -= 1;
        }
        _safeMint(msg.sender, _quantity_to_mint);
    }


    /** @dev Claims (mint) Black Meta Multipass
        @param _BytesReceived -- Bytes to transfer to contract. Used for minting, higher amounts give better mints.
        @param _merkleProof -- Merkle proof, computed off chain
      */
    function claim(uint256 _BytesReceived, bytes32[] calldata _merkleProof, uint256 _whitelist_position) external payable nonReentrant { // i don't think non-rentrant needs to be here
//        require(bypassWhitelist == true || whiteListContract.isWhitelisted(_merkleProof, msg.sender)==true, "Not whitelisted");
        require(contractSettings.bypassWhitelist == true || whiteListContract.isWhitelisted(msg.sender, _whitelist_position, _merkleProof)==true, "Not whitelisted");
        require(currentIndex < contractSettings.maxSupply );
        require(whiteListHasMinted[msg.sender] == 0, "address already minted");
        require(msg.value >= contractSettings.mintFee);
        require(contractSettings.mintingPermitted==true, "Minting is currently not permitted.");
        whiteListHasMinted[msg.sender] += 1;

        uint256[] memory _myBytesArray = new uint256[](1);
        _myBytesArray[0] = _BytesReceived;
        _bulkClaim(_myBytesArray, 1);
//        _claim(_BytesReceived);
    }


    /** @dev Constructor for Black Meta Multipass
        @param _BytesAddress -- Contract Address for Bytes.
        @param _baseURI -- Background Image for tokenUri Image
      */
    constructor(address _BytesAddress, address _whiteListAddress, address _royaltiesCollector, string memory _baseURI)
            ERC721A("Black Meta Multipass", "BMPASS") Ownable() ERC2981Collection(_royaltiesCollector, 750) {
        BytesERC20 = IERC20(_BytesAddress);
        whiteListContract = Whitelist(_whiteListAddress);
        baseURI = _baseURI;

        contractSettings = ContractSettings({
            mintFee: 0, //0.05 ether,
            maxSupply: 3000,
            OGPrivilege: true,
            mintingPermitted: true,
            bypassWhitelist: false
        });

        // mint 250 blank NFTs for team. These are initiated by team members at their own cost //
        // they have a present clearanceLevel according to their tokenId //
        _safeMint(msg.sender, 250);
    }

    // Required to receive ETH
    receive() external payable {
    }


    /////////////////////////////////////////////
    ///////// MetaData, Image Functions /////////
    /////////////////////////////////////////////

    /** @dev Formats string into code for typing on image terminal
        @param _line -- vertical starting position.
        @param _duration -- animation duration.
        @param _startTime -- time to begin animation (invisible beforehand).
        @param _txt -- text to animate (width/characters must be less than terminal size--or visual overflow)
      */
    function getSVGTextGivenLine(uint256 _line, uint256 _duration, uint256 _startTime, string memory _txt) internal view returns (string memory) {
        string memory ret = string(abi.encodePacked(
            "%3Cpath id='path",
            toString(_line),
            "'%3E %3Canimate attributeName='d' from='m50, ",
            toString(170 + _line*14),
            " h0' to='m50, ",
            toString(170 + _line*14),
            " h1100' dur='",
            toString(_duration),
            "s' begin='",
            toString(_startTime),
            "s' fill='freeze'/%3E%3C/path%3E"
        ));
        ret = string(abi.encodePacked(ret,
            "%3Ctext class='bm'%3E %3CtextPath xlink:href='%23path",
            toString(_line),
            "'%3E",
            _txt,
            "%3C/textPath%3E",
            "%3C/text%3E"
        ));
        return ret;
    }

    function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
        require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
        Data memory _myData = unpackData(_tokenId);

        string[13] memory _fontColors = [
            '00DEFF',
            '00DEFF',
            'C5ACFF',
            'C5ACFF',
            '8BFF7C',
            '8BFF7C',
            '8BFF7C',
            'FF8D8D',
            'FF8D8D',
            'FF8D8D',
            'FFFE8D',
            'FFFE8D',
            'B1FCFF'
        ];

        string memory style = string(abi.encodePacked(
          "%3Cstyle%3E",
                "@import url('https://fonts.googleapis.com/css2?family=VT323');",
                ".bm %7B",
                    "font-family: 'VT323', monospace;",
                    "font-size:12px;",
                    "fill: %23", _fontColors[_myData.clearanceLevel],
                "%7D",
          "%3C/style%3E"
        ));



        string memory header = string(abi.encodePacked(
            style,
            "%3Ctext class='bm' x='50%25' y='90' text-anchor='middle' %3ESA/RA 9000 OPERATING SYSTEM %3C/text%3E",
            "%3Ctext class='bm' x='50%25' y='110' text-anchor='middle' %3ECOPYRIGHT 2022-2175 BLACK META CORPORATION%3C/text%3E",
            "%3Ctext class='bm' x='50%25' y='130' text-anchor='middle' %3E --SECURITY TERMINAL ",
            toString(_myData.clearanceLevel + 1),
            "--  %3C/text%3E"
        ));


        string[25] memory textLines = [
            '--Black Meta Security Scan Subsystem--',
            '=============================================',
            'Sa/RaOS v. 7.21',
            '(C)2022 Black Meta Corp.(TM))',
            '=============================================',
            '| %3E%3E Running Security Scan... COMPLETE ',
            '| User Log: ',
            string(abi.encodePacked('| %3E%3E MultipassID: ', toString(_tokenId))),
            '| Security Clearance: ',
            string(abi.encodePacked('| %3E%3E ', clearanceLevels[_myData.clearanceLevel] )),
            '| Welcome to Black Meta.',
            '| %3E%3E Assigning Quarters... COMPLETE ',
            string(abi.encodePacked('| %3E%3E Xen ', toString(_myData.xenGroup + 1) )),
            '| %3E%3E Assigning Station... COMPLETE ',
            string(abi.encodePacked('| %3E%3E ', stations[_myData.station] )),
            '%3E| %3E%3E Granting Subroot Access... COMPLETE ',
            '%3E| %3E%3E Opening Command Subroot... COMPLETE ',
            '====================================',
            '%3E> Hello. How can I fix your total failures?',
            string(abi.encodePacked('%3E C:%3E  ', commands[_myData.command])),
            string(abi.encodePacked('%3E| ', responses[_myData.response])),
            '%3E| %3E%3E Alerting Security Assistance... COMPLETE',
            '%3E| %3E%3E Starting Insult Protocol 2.3... COMPLETE',
            '====================================',
            string(abi.encodePacked('%3E| %3E%3E ', insults[_myData.insult]))
        ];

        // OVERLAY MUST BE SAME FORMAT (WEBP)
        string memory colorOverlay = string(abi.encodePacked(
                "%3Cimage xlink:href='", baseURI ,"/", toString(_myData.clearanceLevel) ,  ".png' width='600' height='600' /%3E"
            ));

        string memory textOverlay="";
        uint256 startTime = 0;
        uint256 duration = 5;
        uint256 flag = 0;
        for(uint256 i=0;i< textLines.length;i++){
            textOverlay = string(abi.encodePacked(textOverlay, getSVGTextGivenLine(i, duration, startTime, textLines[i]), " "));
            startTime += duration/2;
            if(flag==1) { break;}
        }

        string memory footer = string(abi.encodePacked(
            "%3Cpath id='pathfinal'%3E%3Canimate attributeName='d' from='m180,550 h0' to='m180,550 h1100' dur='7s' begin='", toString(startTime) , "s' fill='freeze'/%3E%3C/path%3E",
            "%3Ctext%3E%3CtextPath xlink:href='%23pathfinal' class='bm'%3ERETURN: enter | BACKSPACE : delete | F1: main menu%3C/textPath%3E%3C/text%3E"
        ));


        string memory mainImage;

        mainImage = string(abi.encodePacked(
            "%3Cimage xlink:href='", baseURI ,"/a.png' width='600' height='600' /%3E"
        ));

        string memory SVG = string(abi.encodePacked(
            // Container
           "%3Csvg xmlns='http://www.w3.org/2000/svg' width='600'  xmlns:xlink='http://www.w3.org/1999/xlink' height='600'%3E %3Crect width='600' height='600' style='fill:rgb(255,255,255);stroke-width:3;stroke:rgb(0,0,0)' /%3E",

            // Main image
            mainImage,
            colorOverlay,
            header,

           // text outlines
            textOverlay,
            footer,

            // Error Message
            "Unsupported.",
            "%3C/svg%3E"
            ));

        return formatTokenURI(_tokenId, svgToImageURI(SVG));
    }

    /** @dev Converts svg to dataURI
        @param svg -- svg to turn into dataURI.
      */
    function svgToImageURI(string memory svg) internal pure returns (string memory) {
        bool ENCODE = false;
        string memory baseURL = "data:image/svg+xml;base64,";

        if (!ENCODE) {
            baseURL = "data:image/svg+xml,";
            return string(abi.encodePacked(baseURL,svg));
        }

        string memory svgBase64Encoded = Base64.encode(bytes(svg));
        return string(abi.encodePacked(baseURL,svgBase64Encoded));
    }


    /** @dev Packs metadata, including image, into a dataURI
        @param _tokenId -- ID of BMMultipass
        @param imageURI -- URI of image
      */
    function formatTokenURI(uint256 _tokenId, string memory imageURI) internal view returns (string memory) {

        if(tokenIdToPackedData[_tokenId] == 0) {
            return string(abi.encodePacked(baseURI, "/access_denied.json" ));
        }

        Data memory _myData = unpackData(_tokenId);
        string memory json_str = string(abi.encodePacked(
            '{"description": "The ticket into the Black Meta Multiverse."',
            ', "external_url": "https://blackmeta.site"',
            ', "image": "', // to do -- check on this
               baseURI, "/a", toString(_myData.clearanceLevel),  '.png"',
            ', "data_uri": "', //
             imageURI, '"',
            ', "name": "Black Meta Multipass"',
            // attributes
            ', "attributes": [{"trait_type": "Clearance Level", "value": "',
            clearanceLevels[_myData.clearanceLevel],   '" }'
        ));

        json_str = string(abi.encodePacked(json_str,
            ', {"trait_type": "Station", "value": "',
            stations[_myData.station],   '" }',
            ', {"trait_type": "Security Terminal", "value": "',
//            securityTerminals[_myData.securityTerminal],   '" }'
            toString(_myData.securityTerminal + 1),   '" }'
        ));

        json_str = string(abi.encodePacked(json_str,
            ', {"trait_type": "Xen Groups", "value": "Xen ',
//            xenGroups[_myData.xenGroup],   '" }',
            toString(_myData.xenGroup + 1),   '" }',
            ', {"trait_type": "Command", "value": "',
            commands[_myData.command],   '" }'
        ));


        json_str = string(abi.encodePacked(json_str,
            ', {"trait_type": "Response", "value": "',
            responses[_myData.response],   '" }',
            ', {"trait_type": "Insult", "value": "',
            insults[_myData.insult],   '" }',
            ', {"trait_type": "Rarity", "value": ', // "display_type": "number",
            toString(_myData.rarity),   ' }'
        ));

        json_str = string(abi.encodePacked(json_str,
            ']', // End Attributes
            '}'
        ));

        return string(abi.encodePacked("data:application/json;base64,", Base64.encode(bytes(json_str))));
    }


    ///////////////////////////////////
    ///////// Admin Functions /////////
    ///////////////////////////////////

    function withdrawBytes( address _recipient) external onlyOwner nonReentrant {
        uint256 _BytesReleased = BytesERC20.balanceOf(address(this));
        require(BytesERC20.transfer(_recipient, BytesERC20.balanceOf(address(this))), "Bytes transfer failed.");
        emit FundsReleasedToAccount(0, _BytesReleased, _recipient, block.timestamp);
    }

    function withdrawEth( address payable _recipient) external onlyOwner nonReentrant {
        uint256 amountReleased = address(this).balance;
        (bool success, ) = _recipient.call{value : address(this).balance}("Releasing ETH.");
        require(success, "Transfer failed.");
        emit FundsReleasedToAccount(amountReleased, 0, _recipient, block.timestamp);
    }

    function setBytesAddress(address _contractAddress) external onlyOwner {
        BytesERC20 = IERC20(_contractAddress);
    }

    function setWhiteListContractAddress(address _contractAddress) external onlyOwner {
        whiteListContract = Whitelist(_contractAddress);
    }

    function setOGPrivilege(bool _OGPrivilege) external onlyOwner {
        require(contractSettings.OGPrivilege != _OGPrivilege, "must be 1 or 0, and not same as current.");
        contractSettings.OGPrivilege = _OGPrivilege;
    }

    function setMintingPermitted(bool _mintingPermitted) external onlyOwner {
        require(contractSettings.mintingPermitted != _mintingPermitted, "must be 1 or 0, and not same as current.");
        contractSettings.mintingPermitted = _mintingPermitted;
    }

    function setBypassWhitelist(bool _bypassWhitelist) external onlyOwner {
        require(contractSettings.bypassWhitelist != _bypassWhitelist, "must be 1 or 0, and not same as current.");
        contractSettings.bypassWhitelist = _bypassWhitelist;
    }

    function setBaseURI(string memory _baseURI) external onlyOwner {
        baseURI = _baseURI;
    }

    function setRoyaltyPercent(uint256 _percentage) external onlyOwner {
        _setRoyaltyPercent(_percentage);
    }

    function setRoyaltyAddress(address _receiver) external onlyOwner {
        _setRoyaltyAddress(_receiver);
    }


    /** @dev sets mint fee in ETH for all mints
        @param _mintFee -- ETH required to mint, must not exceed 2^208 -1 or overflow
    */
    function setMintFee(uint256 _mintFee) external onlyOwner {
        contractSettings.mintFee = uint208(_mintFee);
    }

    /** @dev Upgrades a clearanceLevel. Used for rewards
        @param _tokenId -- id of NFT
        @param _newClearanceLevel -- clearanceLevel to be upgraded to
    */
    function upgradeClearanceLevel(uint256 _tokenId, uint256 _newClearanceLevel) external onlyOwner {
        Data memory _myData = unpackData(_tokenId);
        require(_exists(_tokenId) && _myData.clearanceLevel > _newClearanceLevel); // dev: Id must exist and must increase CL
//        require(_exists(_tokenId), "NFT DOES NOT EXIST"); // lesser number is superior
//        require(_myData.clearanceLevel > _newClearanceLevel, "upgraded must lower cl #"); // lesser number is superior

        _myData.clearanceLevel = _newClearanceLevel;
        tokenIdToPackedData[_tokenId] = packData(_myData.clearanceLevel, _myData.station, _myData.securityTerminal, _myData.xenGroup, _myData.command, _myData.response, _myData.insult, _myData.rarity);
    }


    /////////////////////////////////////
    ///////// Helper Functions //////////
    /////////////////////////////////////

    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT license
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }
}