Encode one item of a BTC script
    Return the encoded item (as a string)

    Based on code from pybitcointools (https://github.com/vbuterin/pybitcointools)
    by Vitalik Buterin

def _btc_script_serialize_unit(unit):
    """
    Encode one item of a BTC script
    Return the encoded item (as a string)

    Based on code from pybitcointools (https://github.com/vbuterin/pybitcointools)
    by Vitalik Buterin
    """
    
    if isinstance(unit, int):
        # cannot be less than -1, since btc_script_deserialize() never returns such numbers
        if unit < -1:
            raise ValueError('Invalid integer: {}'.format(unit))

        if unit < 16:
            if unit == 0:
                # OP_RESERVED
                return encoding.from_int_to_byte(OPCODE_VALUES['OP_RESERVED'])
            else:
                # OP_1 thru OP_16, or OP_1NEGATE
                return encoding.from_int_to_byte(unit + 80)
        else:
            # pass as numeric literal or raw opcode
            return encoding.from_int_to_byte(unit)

    elif unit is None:
        # None means OP_0
        return b'\x00'

    else:
        if len(unit) <= 75:
            # length + payload
            return encoding.from_int_to_byte(len(unit)) + unit

        elif len(unit) < 256:
            # OP_PUSHDATA1 + length (1 byte) + payload
            return encoding.from_int_to_byte(OPCODE_VALUES['OP_PUSHDATA1']) + encoding.from_int_to_byte(len(unit)) + unit

        elif len(unit) < 65536:
            # OP_PUSHDATA2 + length (2 bytes, big-endian) + payload
            return encoding.from_int_to_byte(OPCODE_VALUES['OP_PUSHDATA2']) + encoding.encode(len(unit), 256, 2)[::-1] + unit
        else:
            # OP_PUSHDATA4 + length (4 bytes, big-endian) + payload
            return encoding.from_int_to_byte(OPCODE_VALUES['OP_PUSHDATA4']) + encoding.encode(len(unit), 256, 4)[::-1] + unit