added encode error check