import binascii


def unhexlify(blob):
    """
    Takes a hexlified script and turns it back into a string of Python code.
    """
    lines = blob.split('\n')[1:]
    output = []
    for line in lines:
        # Discard the address, length etc. and reverse the hexlification
        output.append(binascii.unhexlify(line[9:-2]))
    # Check the header is correct ("MP<size>")
    if (output[0][0:2].decode('utf-8') != u'MP'):
        return ''
    # Strip off header
    output[0] = output[0][4:]
    # and strip any null bytes from the end
    output[-1] = output[-1].strip(b'\x00')
    script = b''.join(output)
    try:
        result = script.decode('utf-8')
        return result
    except UnicodeDecodeError:
        # Return an empty string because in certain rare circumstances (where
        # the source hex doesn't include any embedded Python code) this
        # function may be passed in "raw" bytes from MicroPython.
        return ''