//-----------------------------------------------------------------------------
// F34x_MSD_Util.c
//-----------------------------------------------------------------------------
// Copyright 2006 Silicon Laboratories, Inc.
// http://www.silabs.com
//
// Program Description:
//
// This file contains a function which is used to searching the string for
// the first occurrence of whitespace. The whitespace is a special sign like 
// new line, space, etc.
//
//
//
// How To Test:    See Readme.txt
//
//
// FID:            34X000067
// Target:         C8051F34x
// Tool chain:     Keil
// Command Line:   See Readme.txt
// Project Name:   F34x_USB_MSD
//
// Release 1.1
//    -All changes by PKC
//    -09 JUN 2006
//    -Replaced SFR definitions file "c8051f320.h" with "c8051f340.h"
//
// Release 1.0
//    -Initial Release
//

//-----------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------

#include "util.h"
#include <string.h>
#include <limits.h>
#include "c8051f340.h"

#ifdef ENDIAN_CORRECT_BY_FUNC
u32 swap_u32(u32 dw){
  DWORD dw2;
  dw2.c[0] = (DWORD)(dw).c[3];
  dw2.c[1] = (DWORD)(dw).c[2];
  dw2.c[2] = (DWORD)(dw).c[1];
  dw2.c[3] = (DWORD)(dw).c[0];
  return dw2.i;
}
u16 swap_u16(u16 w){
  WORD w2;
  w2.c[0] = (DWORD)(w).c[1];
  w2.c[1] = (DWORD)(w).c[0];
  return w2.i;
}
#endif

#define whitespace " \t\0\n\r"

//----------------------------------------------------------------------------
// Str_Token
//----------------------------------------------------------------------------
//
// This function searches the whitespaces and returns the address of first
// found whitespace sign.
//
// Parameters   : str - command string
// Return Value : address of found whitespace
//----------------------------------------------------------------------------

char* Str_Token(char* str) {
	static char* s;
	static char old;
	char*rtn;

	if(str) s=str; else *s=old;
	while(*s && strchr(whitespace,*s)) 	// Skip leading whitespace
		s++;
	if(!*s) return 0;
	rtn=s;
	while(*s && !strchr(whitespace,*s))	// Find next whitespace
		s++;
	old=*s;
	*s='\0';
	return rtn;
}

void wait_10n4clk(unsigned char i){
  while(i--);
/*_asm
start_wait_10n4:
  mov r2,dpl            ; 2clk
  mov ar3,r2            ; 2clk
  dec r2                ; 1clk
  mov a,r3              ; 1clk
  jnz start_wait_10n4   ; 2/4clk
_endasm;*/
  //ret                 ; 6clk
}

/**
 * Delay function with declared wait time in microseconds
 * 
 * @param count time in ns
 */
void wait_us(unsigned int count){
#ifdef F340_M24
  count/=2;
#endif
  while(count--) wait_10n4clk(4); // (2+2+1+1+4)*4 - (4-2) + 6 = 44clk
}

/**
 * Delay function with declared wait time in milliseconds
 * 
 * @param count - time in ms
 */
void wait_ms(unsigned int count){
  int i;
  for(i = 0; i < count; i++) wait_us(1000);
}
