/*
 * Some "cool" distro defines PATH_MAX as 4095 not as ussaly 4096
 * Becouse many members offset of libusb structures depends on 
 * PATH_MAX value. This makes not portable binary code which
 * uses libusb structures.
 *
 * So this code does it.
 *
 */
 
/* $Id: darwin.c 8416 2006-08-21 11:38:56Z mindaugas $ */

#include <stdio.h>

#include <usb.h>
#include <IOKit/usb/IOUSBLib.h>

#include "libusbw.h"

struct darwin_dev_handle
{
	void * device;
	void * interface;
};

struct usb_dev_handle
{
	int fd;
	void * bus;
	void * device;
	int config;
	int interface;
	int altsetting;
	struct darwin_dev_handle * impl_info;
};

void *
get_interface(struct usb_dev_handle * dev)
{
	struct darwin_dev_handle * darwin_dev;

	if (!dev)
	{
		return NULL;
	}

	darwin_dev = dev->impl_info;

	if (!darwin_dev)
	{
		return NULL;
	}

	return darwin_dev->interface;
}

int
get_endpoint_pipe(struct usb_dev_handle * dev, int endpoint)
{
	IOUSBInterfaceInterface ** intf;
	int i;
	int ret;

	UInt8 ep_num, direction, number;
	UInt8 bbd1;
	UInt16 bbd2;
	UInt8 bbd3;

	if (!dev)
	{
		return 0;
	}

	intf = (IOUSBInterfaceInterface **)get_interface(dev);
	if (!intf)
	{
		return 0;
	}

	ret = (*intf)->GetNumEndpoints(intf, &ep_num);
	if (ret != kIOReturnSuccess)
	{
		return 0;
	}


	for (i = 1; i <= ep_num; i++)
	{
		ret = (*intf)->GetPipeProperties(intf, i, &direction, &number, &bbd1, &bbd2, &bbd3);
		if (ret != kIOReturnSuccess)
		{
			return 0;
		}

		if ( (((direction << 7) & 0x80) | (number & 0x0f)) == endpoint)
		{
			return i;
		}
	}

	return 0;
}

