/* libnexys.c
 * DPCUTIL compatibility driver for libnexys
 * libnexys, a free driver for Digilent NEXYS2 boards
 *
 * Copyright (c) 2007-2008 Joshua Wise
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License.
 *
 * Commercial licenses are available by request.
 */

#define LIBNEXYS_INTERNAL
#include "libnexys.h"
#include <stdio.h>

nexys2_t nexys2_init(void) {
	int device;
	char devname[32];
	HANDLE hand;
	ERC erc;
	
	if (!DpcInit(&erc))
	{
		printf("DpcInit failed\n");
		return NULL;
	}
	
	if ((device = DvmgGetDefaultDev(&erc)) == -1)
	{
		printf("We appear to lack a default device. Sadface :(\n");
		return NULL;
	}
	
	DvmgGetDevName(device, devname, &erc);
	printf("Interacting with device %d (%s)\n", device, devname);
	
	if (!DpcOpenJtag(&hand, devname, &erc, NULL))
	{
		printf("JTAG open failed\n");
		return NULL;
	}
	return hand;
}

int nexys2_jtag_enable(HANDLE hand)
{
	ERC erc;
	return DpcEnableJtag(hand, &erc, NULL) ? 0 : -1;
}

int nexys2_jtag_disable(HANDLE hand)
{
	ERC erc;
	return DpcDisableJtag(hand, &erc, NULL) ? 0 : -1;
}

int nexys2_jtag_setbits(HANDLE hand, int tms, int tdi, int tck)
{
	ERC erc;
	return DpcSetTmsTdiTck(hand, tms, tdi, tck, &erc, NULL) ? 0 : -1;
}

int nexys2_jtag_puttdi(HANDLE hand, int tms, int nbits, unsigned char *bits, unsigned char *obits)
{
	ERC erc;
	return DpcPutTdiBits(hand, nbits, bits, tms, obits ? 1 : 0, obits, &erc, NULL) ? 0 : -1;
}

int nexys2_jtag_puttmstdi(HANDLE hand, int nbits, unsigned char *bits, unsigned char *obits)
{
	ERC erc;
	return DpcPutTmsTdiBits(hand, nbits, bits, obits ? 1 : 0, obits, &erc, NULL) ? 0 : -1;
}

int nexys2_jtag_gettdo(HANDLE hand, int tdi, int tms, int nbits, unsigned char *obits)
{
	ERC erc;
	return DpcGetTdoBits(hand, nbits, tdi, tms, obits, &erc, NULL) ? 0 : -1;
}
