<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def set_fold_lvl(block, val):
 """ Sets the block fold level. :param block: block to modify :param val: The new fold level [0-7] """

        if block is None:
            return
        state = block.userState()
        if state == -1:
            state = 0
        if val >= 0x3FF:
            val = 0x3FF
        state &= 0x7C00FFFF
        state |= val << 16
        block.setUserState(state)