/*
 *  GemPC410Utils.c
 *  $Id: GemPC410Utils.c,v 1.13 2012/04/08 19:09:42 rousseau Exp $
 *  GemPC410 dedicated functions
 *
 *  Created by giraud on Sat Oct 20 2001.
 *  Modified by Ludovic Rousseau <ludovic.rousseau@free.fr>, Nov 2001
 *  Copyright (c) 2001 Jean-Luc Giraud and Ludovic Rousseau
 *  License:   See file COPYING.GPL
 *
 */

#include <stdio.h>

#include "gempc_ifdhandler.h"
#include "GemCore.h"
#include "Config.h"
#include "GemPC410Utils.h"
#include "GCCmds.h"
#include "gbpserial.h"
#include "GCdebug.h"
#include "GCTransport.h"

RESPONSECODE OpenGemPC410ByName(DWORD lun, LPSTR dev_name)
{
	UCHAR os_version[IFD_LEN_VERSION + 2];
	DWORD length;

	if (OpenGBP(lun, dev_name) != STATUS_SUCCESS)
	{
		DEBUG_CRITICAL("OpenGBP failed");
		return IFD_COMMUNICATION_ERROR;
	}
	/* Get the GemCore OS version */
	length = sizeof(os_version);
	if (GCCmdGetOSVersion(lun, &length, os_version) != IFD_SUCCESS)
	{
		DEBUG_CRITICAL("GCCmdGetOSVersion failed");
		return IFD_COMMUNICATION_ERROR;
	}

	DEBUG_CRITICAL2("OS string: %s", os_version);

	/* Set the mode to ROS but no TLP (ATR should then be fine) */
	if (GCCmdSetMode(lun, IFD_MODE_ROSNOTLP) != IFD_SUCCESS)
	{
		DEBUG_CRITICAL("Setmode failed");
		CloseGBP(lun);
		return IFD_COMMUNICATION_ERROR;
	}

	return IFD_SUCCESS;
} /* OpenGemPC410ByName */

RESPONSECODE OpenGemPC410(DWORD lun, DWORD channel)
{
	char dev_name[FILENAME_MAX];

	/*
	 * Conversion of old-style ifd-hanler 1.0 CHANNELID
	 */
	if (channel == 0x0103F8)
		channel = 1;
	else
		if (channel == 0x0102F8)
			channel = 2;
		else
			if (channel == 0x0103E8)
				channel = 3;
			else
				if (channel == 0x0102E8)
					channel = 4;

	sprintf(dev_name, "/dev/pcsc/%d", (int) channel);

	return OpenGemPC410ByName(lun, dev_name);
}	/* OpenGemPC410 */

RESPONSECODE CloseGemPC410(DWORD lun)
{
	if (CloseGBP(lun) != STATUS_SUCCESS)
		return IFD_COMMUNICATION_ERROR;

	return IFD_SUCCESS;
}	/* CloseGemPC410 */

