// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @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() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

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

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        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 {
        _transferOwnership(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");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: @openzeppelin/contracts/interfaces/IERC721.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721.sol)

pragma solidity ^0.8.0;

import "../token/ERC721/IERC721.sol";

// File: @openzeppelin/contracts/token/ERC721/IERC721.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @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`.
     *
     * 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 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 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: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * 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 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 the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

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

// File: @openzeppelin/contracts/utils/Base64.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides a set of functions to operate with Base64 strings.
 *
 * _Available since v4.5._
 */
library Base64 {
    /**
     * @dev Base64 Encoding/Decoding Table
     */
    string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    /**
     * @dev Converts a `bytes` to its Bytes64 `string` representation.
     */
    function encode(bytes memory data) internal pure returns (string memory) {
        /**
         * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
         * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
         */
        if (data.length == 0) return "";

        // Loads the table into memory
        string memory table = _TABLE;

        // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter
        // and split into 4 numbers of 6 bits.
        // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up
        // - `data.length + 2`  -> Round up
        // - `/ 3`              -> Number of 3-bytes chunks
        // - `4 *`              -> 4 characters for each chunk
        string memory result = new string(4 * ((data.length + 2) / 3));

        /// @solidity memory-safe-assembly
        assembly {
            // Prepare the lookup table (skip the first "length" byte)
            let tablePtr := add(table, 1)

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

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

            } {
                // Advance 3 bytes
                dataPtr := add(dataPtr, 3)
                let input := mload(dataPtr)

                // To write each character, shift the 3 bytes (18 bits) chunk
                // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
                // and apply logical AND with 0x3F which is the number of
                // the previous character in the ASCII table prior to the Base64 Table
                // The result is then added to the table to get the character to write,
                // and finally write it in the result pointer but with a left shift
                // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits

                mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance
            }

            // When data `bytes` is not exactly 3 bytes long
            // it is padded with `=` characters at the end
            switch mod(mload(data), 3)
            case 1 {
                mstore8(sub(resultPtr, 1), 0x3d)
                mstore8(sub(resultPtr, 2), 0x3d)
            }
            case 2 {
                mstore8(sub(resultPtr, 1), 0x3d)
            }
        }

        return result;
    }
}

// File: @openzeppelin/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

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

// File: @openzeppelin/contracts/utils/introspection/IERC165.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

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

// File: @openzeppelin/contracts/utils/math/Math.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator,
        Rounding rounding
    ) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10**64) {
                value /= 10**64;
                result += 64;
            }
            if (value >= 10**32) {
                value /= 10**32;
                result += 32;
            }
            if (value >= 10**16) {
                value /= 10**16;
                result += 16;
            }
            if (value >= 10**8) {
                value /= 10**8;
                result += 8;
            }
            if (value >= 10**4) {
                value /= 10**4;
                result += 4;
            }
            if (value >= 10**2) {
                value /= 10**2;
                result += 2;
            }
            if (value >= 10**1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
        }
    }
}

// File: @openzeppelin/contracts/utils/Strings.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/Math.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @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] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }
}

// File: contracts/array.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.17;

// Join
error EmptyArray();
error GlueOutOfBounds(uint256 length);

library Array {
    function join(string[] memory a, string memory glue)
        internal
        pure
        returns (string memory)
    {
        uint256 inputPointer;
        uint256 gluePointer;

        assembly {
            inputPointer := a
            gluePointer := glue
        }
        return string(_joinReferenceType(inputPointer, gluePointer));
    }

    function join(string[] memory a) internal pure returns (string memory) {
        return join(a, "");
    }

    function join(bytes[] memory a, bytes memory glue)
        internal
        pure
        returns (bytes memory)
    {
        uint256 inputPointer;
        uint256 gluePointer;

        assembly {
            inputPointer := a
            gluePointer := glue
        }
        return _joinReferenceType(inputPointer, gluePointer);
    }

    function join(bytes[] memory a) internal pure returns (bytes memory) {
        return join(a, bytes(""));
    }

    function join(bytes2[] memory a) internal pure returns (bytes memory) {
        uint256 pointer;

        assembly {
            pointer := a
        }
        return _joinValueType(pointer, 2, 0);
    }

    /// @dev Join the underlying array of bytes2 to a string.
    function join(uint16[] memory a) internal pure returns (bytes memory) {
        uint256 pointer;

        assembly {
            pointer := a
        }
        return _joinValueType(pointer, 2, 256 - 16);
    }

    function join(bytes3[] memory a) internal pure returns (bytes memory) {
        uint256 pointer;

        assembly {
            pointer := a
        }
        return _joinValueType(pointer, 3, 0);
    }

    function join(bytes4[] memory a) internal pure returns (bytes memory) {
        uint256 pointer;

        assembly {
            pointer := a
        }
        return _joinValueType(pointer, 4, 0);
    }

    function join(bytes8[] memory a) internal pure returns (bytes memory) {
        uint256 pointer;

        assembly {
            pointer := a
        }
        return _joinValueType(pointer, 8, 0);
    }

    function join(bytes16[] memory a) internal pure returns (bytes memory) {
        uint256 pointer;

        assembly {
            pointer := a
        }
        return _joinValueType(pointer, 16, 0);
    }

    function join(bytes32[] memory a) internal pure returns (bytes memory) {
        uint256 pointer;

        assembly {
            pointer := a
        }
        return _joinValueType(pointer, 32, 0);
    }

    function _joinValueType(
        uint256 a,
        uint256 typeLength,
        uint256 shiftLeft
    ) private pure returns (bytes memory) {
        bytes memory tempBytes;

        assembly {
            let inputLength := mload(a)
            let inputData := add(a, 0x20)
            let end := add(inputData, mul(inputLength, 0x20))

            // Get a location of some free memory and store it in tempBytes as
            // Solidity does for memory variables.
            tempBytes := mload(0x40)

            // Initialize the length of the final bytes: length is typeLength x inputLength (array of bytes4)
            mstore(tempBytes, mul(inputLength, typeLength))
            let memoryPointer := add(tempBytes, 0x20)

            // Iterate over all bytes4
            for {
                let pointer := inputData
            } lt(pointer, end) {
                pointer := add(pointer, 0x20)
            } {
                let currentSlot := shl(shiftLeft, mload(pointer))
                mstore(memoryPointer, currentSlot)
                memoryPointer := add(memoryPointer, typeLength)
            }

            mstore(0x40, and(add(memoryPointer, 31), not(31)))
        }
        return tempBytes;
    }

    function _joinReferenceType(uint256 inputPointer, uint256 gluePointer)
        internal
        pure
        returns (bytes memory tempBytes)
    {
        assembly {
            // Get a location of some free memory and store it in tempBytes as
            // Solidity does for memory variables.
            tempBytes := mload(0x40)

            // Skip the first 32 bytes where we will store the length of the result
            let memoryPointer := add(tempBytes, 0x20)

            // Load glue
            let glueLength := mload(gluePointer)
            if gt(glueLength, 0x20) {
                revert(gluePointer, 0x20)
            }
            let glue := mload(add(gluePointer, 0x20))

            // Load the length (first 32 bytes)
            let inputLength := mload(inputPointer)
            let inputData := add(inputPointer, 0x20)
            let end := add(inputData, mul(inputLength, 0x20))

            // Initialize the length of the final string
            let stringLength := 0

            // Iterate over all strings (a string is itself an array).
            for {
                let pointer := inputData
            } lt(pointer, end) {
                pointer := add(pointer, 0x20)
            } {
                let currentStringArray := mload(pointer)
                let currentStringLength := mload(currentStringArray)
                stringLength := add(stringLength, currentStringLength)
                let currentStringBytesCount := add(
                    div(currentStringLength, 0x20),
                    gt(mod(currentStringLength, 0x20), 0)
                )

                let currentPointer := add(currentStringArray, 0x20)

                for {
                    let copiedBytesCount := 0
                } lt(copiedBytesCount, currentStringBytesCount) {
                    copiedBytesCount := add(copiedBytesCount, 1)
                } {
                    mstore(
                        add(memoryPointer, mul(copiedBytesCount, 0x20)),
                        mload(currentPointer)
                    )
                    currentPointer := add(currentPointer, 0x20)
                }
                memoryPointer := add(memoryPointer, currentStringLength)
                mstore(memoryPointer, glue)
                memoryPointer := add(memoryPointer, glueLength)
            }

            mstore(
                tempBytes,
                add(stringLength, mul(sub(inputLength, 1), glueLength))
            )
            mstore(0x40, and(add(memoryPointer, 31), not(31)))
        }
        return tempBytes;
    }
}


// File: contracts/IQR.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.17;

enum ErrorCorrectionLevel{LOW, MEDIUM, QUARTILE, HIGH}
contract IQRCode{
    struct QR{
        uint256[10000] bitmap; // 2560000 bits for storage, where version 40 includes at most 40000 bits (> 171 * 171)
        uint256 currentLength;
        uint256 version;
        ErrorCorrectionLevel errorLevel;
        uint256 totalBits;
        uint256 numDataCodewords;
        uint256 charCounts;
        uint8[] result;
    }
    function initQR(string memory text, ErrorCorrectionLevel errorLevel, uint256 version) public view virtual returns(uint8[][] memory graph){
    }
}

// File: contracts/IRenderer.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.17;
import "./IQR.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract IRenderer is Ownable{
    address QRAdress;

    function setQRAdress(address QRAdress_) external onlyOwner{
        QRAdress = QRAdress_;
    }
    function getGraph(string memory text) public view returns (uint8[][] memory graph){
        return IQRCode(QRAdress).initQR(text, ErrorCorrectionLevel.LOW, 0);
    }

    function tokenURI(uint256 tokenId, address holder) public view virtual returns(string memory){
    }
}

// File: contracts/Renderer.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.17;
import "./IRenderer.sol";
import "./array.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/Base64.sol";
import "@openzeppelin/contracts/interfaces/IERC721.sol";
contract Renderer is IRenderer{
    using Array for string[];
    mapping(address=>string) names;
    mapping(address=>string) twitterNames;
    string[5] collectionNames;
    address[5] collectionAddresses;

///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////// Token URI Generation //////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    struct Style{
        address holder;
        uint256 tokenId;
        uint256 size;
        uint256 halfSize;
        // Pattern
        uint256 patternStyle;
        uint256 multiplePatterns;
        // Colors
        string[5] palette;
        uint256 mainColorIndex;
        uint256 colorDistribution;
        uint256 numColors;
        bool flip;
        bool darkBackground;
        // Filters
        uint256 shapeFilter;
        uint256 backgroundFilter;
    }

    function random(string memory key, uint256 tokenId) internal pure returns(uint256){
        return uint256(keccak256(abi.encodePacked(key, tokenId)));
    }

    function randomChoice(string memory key, uint256 tokenId, uint8[8] memory possibilities) internal pure returns(uint256 choice){
        uint256 randomResult = random(key, tokenId) % 100;
        for (choice=0; choice<possibilities.length; ++choice){
            if (possibilities[choice] > randomResult){
                break;
            }
        }
    }

    function getStyle(uint256 tokenId, address holder) internal pure returns(Style memory style){
        style.tokenId = tokenId;
        style.holder = holder;
        style.multiplePatterns=randomChoice("MultiplePattern", tokenId, [50, 70, 90, 100, 0, 0, 0, 0]);
        style.patternStyle=randomChoice("PatternStyle", tokenId, [10, 30, 60, 89, 90, 100, 0, 0]);
        style.numColors=(style.multiplePatterns>0? 2: randomChoice("NumColors", tokenId, [10, 30, 60, 100, 0, 0, 0, 0])+1);
        style.palette = [
            ["423737", "80A3A2", "ABCECF", "C4DCE0", "DAF4F5"], // 16%
            ["2E282A", "c4e7d4", "c4dacf", "b9c0da", "998da0"], // 16%
            ["251F47", "AEC3B0", "9381FF", "B3B8FF", "FAE3C6"], // 16%
            ["181f1c", "ef798a", "f7a9a8", "7d82b8", "e5c3d1"], // 16%
            ["FFFFFF", "000000", "000000", "000000", "000000"], // 2%
            ["E5F4E3", "0B2027", "21302D", "3B343B", "35452A"], // 16%, Dark
            ["461220", "C74451", "D64757", "FCB9B2", "FED0BB"], // 16%, Dark
            ["000000", "FFFFFF", "FFFFFF", "FFFFFF", "FFFFFF"]  // 2%, Dark
        ][randomChoice("Color", tokenId, [16, 32, 48, 64, 66, 82, 98, 100])];
        style.mainColorIndex = (random("Main Color Index", tokenId) % 4);
        style.colorDistribution= randomChoice("ColorDistribution", tokenId, [15, 30, 45, 60, 75, 76, 88, 100]);
        style.shapeFilter=randomChoice("ShapeFilter", tokenId, [10,20,30,40,100,0,0, 0]);
        style.backgroundFilter=randomChoice("BackgroundFilter", tokenId, [10,20,30,100,0,0,0,0]);
        style.flip = (random("Flip?", tokenId) % 4 == 0);
        style.darkBackground = (randomChoice("Color", tokenId, [16, 32, 48, 64, 66, 82, 98, 100]) > 4);
    }

    function tokenURI(uint256 tokenId, address holder) public view override returns(string memory){
        Style memory style = getStyle(tokenId, holder);
        string memory svg = draw(style);
        string memory properties = getProperties(style);
        string memory res = string.concat(
            "data:application/json;base64,",
            Base64.encode(
                abi.encodePacked(
                    '{"name":"', string.concat("Q-aRt #", Strings.toString(tokenId)),
                    '", "description": "An on-chain QR code generative art.",'
                    ' "attributes": [', properties,
                    '], "image":"', svg,
                    '"}'
                )
            )
        );
        return res;
    }

    function getProperties(Style memory style) internal pure returns (string memory properties){
        string[] memory output = new string[](9);
        output[0] = addTrait("Multicell pattern?",
                             ["No", "Horizontal", "Vertical", "Vertical + Horizontal"][style.multiplePatterns],
                             false,
                             false
                            );
        output[1] = style.multiplePatterns == 0?addTrait("Pattern style",
                             ["Knife", "Rotated Square", "Square", "Circle", "Checks", "None"][style.patternStyle],
                             false,
                             false
                            ): "";
        output[2] = addTrait("Number Of Colors",
                             Strings.toString(style.numColors),
                             true,
                             false
                            );
        output[3] = addTrait("Background",
                             style.palette[0],
                             false,
                             false
                            );
        output[4] = addTrait("Main Foreground",
                             style.palette[1 + style.mainColorIndex],
                             false,
                             false
                            );
        output[5] = addTrait("Color distribution",
                             ["Vertical Tunnel", "Horizontal Tunnel", "Diagonal Tunnel", "Inverse", "Square", "Monochrome", "Diagonal", "Grid"][style.colorDistribution],
                             false,
                             false
                            );
        output[6] = addTrait("QR Code Effect",
                             ["Hand-drawn", "Fat", "Stroke", "3D", "None"][style.shapeFilter],
                             false,
                             false
                            );
        output[7] = addTrait("Flipped?",
                             style.flip? "True": "False",
                             false,
                             false
                            );
        output[8] = addTrait("Background Effect",
                             ["Glass", "Large glass", "Cloud", "None"][style.backgroundFilter],
                             false,
                             true
                            );
        properties = output.join();
    }

    function addTrait(string memory traitName, string memory value, bool numeric, bool end) internal pure returns (string memory){
        return string.concat('{"trait_type":"', 
                             traitName, 
                             numeric? '","display_type":"number':'',
                             '","value":', 
                             numeric? '': '"',
                             value, 
                             numeric? '': '"',
                             end? '}': '},'
                            );
    }

    function draw(Style memory style) internal view returns (string memory svg){
        string memory content = getContent(style.holder);
        uint8[][] memory graph = getGraph(content);
        uint256 size = graph.length;
        style.size = size;
        style.halfSize = size / 2;
        string memory sizeString = Strings.toString(size + 8 + (style.multiplePatterns > 0? 1: 0));
        svg = string.concat(
            string.concat( // Header
                "<svg xmlns='http://www.w3.org/2000/svg' preserveAspectRatio='xMinYMin meet' viewBox='",
                style.multiplePatterns > 0? "-5 -5": "-4 -4",
                " ",
                sizeString,
                " ",
                sizeString,
                "'><style>.m {stroke-width:0.9;fill:none;stroke-linejoin:round;stroke-linecap:round;}</style>"
                "<path filter='url(#b)' fill='#", // Background
                style.palette[0],
                "' d='M",
                style.multiplePatterns > 0? "-5-5": "-4-4",
                "h",
                sizeString,
                "v",
                sizeString,
                "h-",
                sizeString,
                "Z'/>"
            ),
            string.concat( // Filters, patterns and paths.
                getShapeFilter(style),
                getBackgroundFilter(style),
                getPattern(style),
                getPaths(graph, style)
            ),
            "</svg>"
        );
        svg = string.concat('data:image/svg+xml,', svg);
    }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////// Helper functions //////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////

    function getShapeFilter(Style memory style) internal pure returns(string memory filter){
        if (style.shapeFilter == 0){
            filter = "<feTurbulence in='SourceGRaphic' baseFrequency='1 1' numOctaves='1' result='NOISE'/><feDisplacementMap in='SourceGraphic' in2='turbulence' scale='.4' xChannelSelector='R' yChannelSelector='G' />";
        }
        else if (style.shapeFilter == 1){
            filter = "<feMorphology operator='dilate' radius='0.1'/>";
        }
        else if (style.shapeFilter == 2){
            filter = "<feConvolveMatrix order='3' kernelMatrix='1 1 1 1 -6 1 1 1 1' edgeMode='none'/>";
        }
        else if (style.shapeFilter == 3){
            filter = "<feConvolveMatrix order='3' kernelMatrix='-2 -1 0 -1 1 1 0 1 2' edgeMode='none'/>";
        }
        else{
            filter = "<feMorphology operator='dilate' radius='0'/>";
        }
        filter = string.concat("<defs><filter id='s'>", filter, "</filter></defs>");
    }

    function getBackgroundFilter(Style memory style) internal pure returns(string memory filter){
        if (style.backgroundFilter == 0){ // Glass
            filter = string.concat(
                "<feTurbulence in='SourceGRaphic' baseFrequency='1 1' numOctaves='1' seed='",
                Strings.toString(style.tokenId),
                "'/><feBlend in='SourceGraphic' mode='",
                style.darkBackground? 'darken': 'lighten',
                "'/>"
            );
        }
        else if (style.backgroundFilter == 1){ // Square glass
            filter = string.concat(
                "<feTurbulence in='SourceGRaphic' baseFrequency='1 1' numOctaves='1' seed='",
                Strings.toString(style.tokenId),
                "'/><feMorphology operator='dilate' radius='0.06'/><feBlend in='SourceGraphic' mode='",
                style.darkBackground? 'darken': 'lighten',
                "'/>"
            );
        }
        else if (style.backgroundFilter == 2){ // Cloud
            filter = string.concat(
                "<feTurbulence type='fractalNoise' baseFrequency='0.4' numOctaves='5' result='n1' seed='",
                Strings.toString(style.tokenId),
                "'/><feGaussianBlur in='SourceGraphic' stdDeviation='5' /><feDisplacementMap scale='5' in2='n1'/>"
            );
        }
        else{
            filter = "<feMorphology operator='dilate' radius='0'/>";
        }
        filter = string.concat("<defs><filter id='b'>", filter, "</filter></defs>");
    }
    function getPattern(Style memory style) internal pure returns(string memory defs){
        string memory head = "<defs>";
        string memory tail = "</defs>";
        if (style.patternStyle < 3){
            if (style.patternStyle == 0){ // Knife, 10%
                defs = ".2-.2l2.5 2.5l-.05.05l-1.25-1.25l-.4.4l-.9-.9";
            }
            else if (style.patternStyle == 1){ // Rotate square, 20%
                defs = "0 0l.9.2l-.2.9l-.9-.2";
            }
            else if (style.patternStyle == 2){ // Square, 30%
                defs = ".05.05h.9v.9h-.9";
            }
            defs = string.concat("<path id='p' d='M", defs, "Z'/>");
        }
        else if (style.patternStyle < 5){
            if (style.patternStyle == 3){ // Circle, 29%
                defs = "<circle id='p' cx='0.5' cy='0.5' r='0.6'/>";
            }
            else if (style.patternStyle == 4){ // Checks, 1%
                defs = "<g id='p'><path d='M0 0a.2.2 0 0 0-.106-.178.207.207 0 0 0 .011-.07.194.194 0 0 0-.189-.197.178.178 0 0 0-.066.012.188.188 0 0 0-.17-.112.189.189 0 0 0-.17.112.178.178 0 0 0-.066-.013.194.194 0 0 0-.189.198c0 .025.004.048.012.07A.2.2 0 0 0-1.04 0a.2.2 0 0 0 .097.173.194.194 0 0 0 .187.223A.18.18 0 0 0-.69.384c.03.066.095.111.17.111.075 0 .14-.045.17-.111a.18.18 0 0 0 .066.012.194.194 0 0 0 .188-.223A.2.2 0 0 0 0 0 M0 0v-2.054Zm-.328-.165-.214.322a.037.037 0 0 1-.052.01L-.599.162l-.12-.12A.037.037 0 1 1-.666-.01l.087.088.19-.284a.037.037 0 0 1 .061.04v-2.028Z'/></g>";
            }
        }
        else{
            defs = "<path id='p' d='M0 0h1v1h-1Z'/>";
        }
        defs = string.concat(head, defs, getMarkers(style), tail);
    }
    function getMarkers(Style memory style) internal pure returns(string memory){
        return string.concat(
            getMarker(style, 0),
            getMarker(style, 1),
            getMarker(style, 2),
            getMarker(style, 3)
        );
    }

    function getMarker(Style memory style, uint256 index) internal pure returns(string memory){
        if (style.numColors <= index){
            return '';
        }
        return string.concat(
            "<marker id='b",
            Strings.toString(index),
            "' fill='#",
            style.palette[1 + ((style.mainColorIndex + index) % 4)],
            "' viewBox='-1 -1 3 3'><use href='#p'/></marker>"
        );
    }

    // Get path draw.
    function getPaths(uint8[][] memory graph, Style memory style) internal pure returns(string memory path){
        if (style.multiplePatterns > 0){
            string[] memory paths = new string[](style.numColors);
            for (uint256 i=0; i<style.size; ++i){
                for (uint256 j=0; j<style.size; ++j){
                    if (graph[j][i]%2 == 1){
                        graph[j][i] = getColorIndex(i, j, style);
                    }
                    else{
                        graph[j][i] = uint8(style.numColors);
                    }
                }
            }
            for (uint256 i=0; i<style.numColors; ++i){
                paths[i] = getPathMultiplePatterns(graph, i, style);
            }
            path = paths.join();
        }
        else{
            string[] memory paths = new string[](style.numColors);
            for (uint256 i=0; i<style.size; ++i){
                for (uint256 j=0; j<style.size; ++j){
                    if (graph[j][i]%2 == 1){
                        graph[j][i] = getColorIndex(i, j, style);
                    }
                    else{
                        graph[j][i] = uint8(style.numColors);
                    }
                }
            }
            for (uint256 i=0; i<style.numColors; ++i){
                paths[i] = getPathSinglePattern(graph, style.size, i);
            }
            path = paths.join();
        }
        path = string.concat("<g filter='url(#s)'>", path, "</g>");
    }
    function getColorIndex(uint256 i, uint256 j, Style memory style) internal pure returns(uint8 k){
        j = style.flip? style.size - 1 - j: j;
        if (style.colorDistribution < 4){ // value based
            uint256 a;
            if (style.colorDistribution == 0){ // Vertical tunnel, 15%
                a = i>style.halfSize? i-style.halfSize: style.halfSize-i;
            }
            else if (style.colorDistribution == 1){ // Horizontal tunnel, 15%
                a = j>style.halfSize? j-style.halfSize: style.halfSize-j;
            }
            else if (style.colorDistribution == 2){ // Diagonal tunnel, 15%
                a = (i+j)>style.size? (i+j)-style.size: style.size-(i+j);
            }
            else{ // Inverse, 15%
                a = (1937 / (i*j+1))/2;
                return uint8(a%style.numColors);
            }
            if (a < style.halfSize/2){
                k = 0;
            }
            else if (a < style.halfSize/2+1){
                k = uint8(1%style.numColors);
            }
            else if (a < style.halfSize){
                k = uint8(2%style.numColors);
            }
            else{
                k = uint8(3%style.numColors);
            }
        }
        else if (style.colorDistribution == 4){ // Square, 15%
            k = uint8((i > j? i: j)%style.numColors);
        }
        // 5: monochrome, 1%

        else if (style.colorDistribution == 6){
            k = uint8(((i + j)/7)%style.numColors); // Diagonal, 12%
        }
        else if (style.colorDistribution == 7){
            k = uint8((i/9 + j/9)%style.numColors); // Grid, 12%
        }
    }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////// Multiple cell patterns //////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    function getPathMultiplePatterns(uint8[][] memory graph, uint256 index, Style memory style) internal pure returns(string memory path){
        path = string.concat("<path class='m' stroke='#",
                             style.palette[1 + ((style.mainColorIndex + index) % 4)],
                             "' d='",
                             drawPointsMultiplePatterns(graph,
                                                        style.size,
                                                        index,
                                                        (style.multiplePatterns == 3? index%2==0: style.multiplePatterns == 2)
                                                       ),
                             "'/>"
                            );
    }
    function drawPointsMultiplePatterns(uint8[][] memory graph, uint256 size, uint256 index, bool vertical) internal pure returns(string memory){
        string[] memory temp = new string[](size * size);
        uint256 lastI = size;
        uint256 lastJ = 100;
        uint256 mode = 0;
        if (vertical){
            for (uint256 i=0; i<size; ++i){
                for (uint256 j=0; j<size; ++j){
                    if ((graph[j][i] == index) && (mode == 0)){ 
                        temp[i*size+j] = string.concat(
                            "M",
                            Strings.toString(i),
                            " ",
                            Strings.toString(j)
                        );
                        lastI = i;
                        lastJ = j;
                        mode = 1;
                    }
                    else if ((graph[j][i] != index) && (mode == 1)){
                        temp[i*size+j] = string.concat(
                            "v",
                            Strings.toString(j - 1 - lastJ)
                        );
                        mode = 0;
                    }
                    if ((j == size-1) && (mode == 1)){
                        temp[i*size+j] = string.concat(
                            temp[i*size+j],
                            "v",
                            Strings.toString(j - lastJ)
                        );
                        mode = 0;
                    }
                }
            }
        }
        else{
            for (uint256 j=0; j<size; ++j){
                for (uint256 i=0; i<size; ++i){
                    if ((graph[j][i] == index) && (mode == 0)){ 
                        temp[j*size+i] = string.concat(
                            "M",
                            Strings.toString(i),
                            " ",
                            Strings.toString(j)
                        );
                        lastI = i;
                        lastJ = j;
                        mode = 1;
                    }
                    else if ((graph[j][i] != index) && (mode == 1)){
                        temp[j*size+i] = string.concat(
                            "h",
                            Strings.toString(i - 1 - lastI)
                        );
                        mode = 0;
                    }
                    if ((i == size-1) && (mode == 1)){
                        temp[j*size+i] = string.concat(
                            temp[j*size+i],
                            "h",
                            Strings.toString(i - lastI)
                        );
                        mode = 0;
                    }
                }
            }
        }
        return temp.join();
    }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////// Single cell patterns //////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////

    function getPathSinglePattern(uint8[][] memory graph, uint256 size, uint256 index) internal pure returns(string memory path){
        path = string.concat("<path fill='none' marker-start='url(#b",
                             Strings.toString(index),
                             ")' marker-mid='url(#b",
                             Strings.toString(index),
                             ")' marker-end='url(#b",
                             Strings.toString(index),
                             ")' d='",
                             drawPointsSinglePattern(graph, size, index),
                             "'/>"
                            );
    }
    function drawPointsSinglePattern(uint8[][] memory graph, uint256 size, uint256 index) internal pure returns(string memory){
        string[] memory temp = new string[](size * size);
        uint256 lastI = size;
        uint256 lastJ = 0;
        uint256 mode = 0; // 0: M, 1: L, 2: v 
        for (uint256 i=0; i<size; ++i){
            for (uint256 j=0; j<size; ++j){
                if (graph[j][i] == index){ 
                    if ((lastI == i) && (mode == 2)){
                        temp[i*size+j] = string.concat(" ", Strings.toString(j - lastJ));
                        lastJ = j;
                    }
                    else if (lastI == i){
                        mode = 2;
                        temp[i*size+j] = string.concat("v", Strings.toString(j - lastJ));
                        lastJ = j;
                    }
                    else{
                        temp[i*size+j] = string.concat(
                            (mode == 0? "M": "L"),
                            Strings.toString(i),
                            " ",
                            Strings.toString(j),
                            ""
                        );
                        mode = 1;
                        lastI = i;
                        lastJ = j;
                    }
                }
            }
        }
        return temp.join();
    }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////// Content //////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    function getContent(address holder) internal view returns (string memory result){
        string memory name = names[holder];
        if (bytes(name).length > 0){ 
            // 14 + 25 + 6 + 10 + len(ens) + len(twitter names) + holdings(24) = 69 + name + twitter name.
            // Case customize. Name + twitter + holdings. 
            result = string.concat('BEGIN:VCARD\nN:',
                                   name,
                                   '\nURL:https://twitter.com/',
                                   twitterNames[holder],
                                   '\nNOTE:',
                                   getHoldings(holder),
                                   '\nEND:VCARD'
                                  );
        }
        else{ // Case without name, 51 chars.
            result = string.concat('ethereum:', Strings.toHexString(uint160(holder), 20));
        }
    }

    function getHoldings(address holder) internal view returns (string memory holdings){
        string[] memory holdings_ = new string[](10);
        holdings_[0] = Strings.toString(IERC721(collectionAddresses[0]).balanceOf(holder));
        holdings_[1] = string.concat(' ', collectionNames[0], ', ');
        holdings_[2] = Strings.toString(IERC721(collectionAddresses[1]).balanceOf(holder));
        holdings_[3] = string.concat(' ', collectionNames[1], ', ');
        holdings_[4] = Strings.toString(IERC721(collectionAddresses[2]).balanceOf(holder));
        holdings_[5] = string.concat(' ', collectionNames[2], ', ');
        holdings_[6] = Strings.toString(IERC721(collectionAddresses[3]).balanceOf(holder));
        holdings_[7] = string.concat(' ', collectionNames[3], ' and ');
        holdings_[8] = Strings.toString(IERC721(collectionAddresses[4]).balanceOf(holder));
        holdings_[9] = string.concat(' ', collectionNames[4]);
        holdings = holdings_.join();
    }
    function setCollection(string memory collectionName, address collectionAddress, uint256 index) external onlyOwner{
        collectionNames[index] = collectionName;
        collectionAddresses[index] = collectionAddress;
    }

    /// @notice Set your name and your twitter name to transform the QR code to a business card! Attention do not bypass 30 characters (The limit of the whole business card chars number should be smaller than 153). Check tokenURI function with your token ID and address to check if it works before you refresh the metadata on opensea.
    function setName(string memory name, string memory twitterName) external{
        names[msg.sender] = name;
        twitterNames[msg.sender] = twitterName;
    }

    /// @notice Reset the art to wallet scanable address.
    function reset() external{
        names[msg.sender] = '';
    }
}