/*****************************************************************************
Copyright (c) 2006 Analog Devices.  All Rights Reserved.

This software is proprietary and confidential.  By using this software you agree
to the terms of the associated Analog Devices License Agreement.  
******************************************************************************

$File: usb_fileio.c $
$Revision: 1.1 $
$Date: 2008/03/17 14:28:20 $

Project:    Audio Kit
Title:      USB_FILEIO
Author(s):  ADA
Revised by:

Description:
		This module implements USB fileio workarounds
		Currently, fread (and fwrite??) via USB on the demo kit has problems when reading odd size blocks.
		The temporary solution is to read data into an interim buffer

*********************************************************************************			
	
Modification History:
====================
$Log: usb_fileio.c,v $
Revision 1.1  2008/03/17 14:28:20  gstephan
Updates for SDK 3.00


	
*********************************************************************************/
#include <stdio.h>
#include <string.h>

#include "usb_fileio.h"

#define USB_INTERIM_BUFFER_SIZE 1048576  // must be even size
#pragma align 4
static unsigned char usb_input_buffer[USB_INTERIM_BUFFER_SIZE];
#pragma align 4
static unsigned char usb_output_buffer[USB_INTERIM_BUFFER_SIZE];

int usbio_fread(unsigned char *dst, int blk_size, FILE *fileptr)
{
	int bytes_read, block_size_four, block_size_remain, rewind, i;
	
	if(blk_size>USB_INTERIM_BUFFER_SIZE) 
	{
		blk_size = USB_INTERIM_BUFFER_SIZE;
		printf("Error... block size exceeds buffer size\n");
	}	

#if 1  // read 4 byte multiple + 4, then rewind where necessary
	block_size_four = (blk_size&0xFFFFFFFC);
	if (block_size_four == blk_size) rewind = 0;
	else 
	{
	    block_size_four += 4;
	    rewind = block_size_four - blk_size;
	}
	bytes_read = fread(usb_input_buffer, 1, block_size_four, fileptr);
	if(rewind && (bytes_read == block_size_four)) fseek(fileptr, -rewind, SEEK_CUR);
	memcpy(dst, usb_input_buffer, (bytes_read - rewind));
	return (bytes_read - rewind);
#else
	bytes_read = fread(usb_input_buffer, 1, blk_size, fileptr);
	memcpy(dst, usb_input_buffer, bytes_read);
	return bytes_read;
#endif
}

int usbio_fwrite(unsigned char *src, int blk_size, FILE *fileptr)
{
	int bytes_written;
	
	if(blk_size>USB_INTERIM_BUFFER_SIZE) 
	{
		blk_size = USB_INTERIM_BUFFER_SIZE;
		printf("Error... block size exceeds buffer size\n");
	}
	memcpy(usb_input_buffer, src, blk_size);
	bytes_written = fwrite(usb_input_buffer, 1, blk_size, fileptr);
	//fflush(fileptr);

	return bytes_written;	
}
