#include <process.h>
#include <dos.h>

/***************************************************************
** udelay(ticks)
**
** Returns after roughly ticks * 0.8381 microseconds (ticks must
** be non-negative and less than 32768 therefore the maximum
** delay is about 27.4 milliseconds).
**
****************************************************************/
void us_delay( unsigned int usecs )
{
	unsigned char lo_byte, hi_byte;
	unsigned char *byte_ptr;
	
	usecs = ( (long)usecs * 118 ) / 100;
	
	byte_ptr = &usecs;
	lo_byte = *byte_ptr;
	byte_ptr++;
	hi_byte = *byte_ptr;

	asm pushf					/* disable interrupts */
	asm cli

	asm in		al,0x61			/* PORTB */
	asm and		al,0xFD			/* disable speaker */
	asm or		al,0x01			/* enable timer 2 gate */
	asm out		0x61,al

	asm mov		al,0xB0
	asm out		0x43,al			/* send command */
	asm in		al,0x61			/* waste some time */
	asm mov		al,lo_byte
	asm out		0x42,al			/* load lo-byte */
	asm in		al,0x61			/* waste some time */
	asm mov		al,hi_byte
	asm out		0x42,al			/* load hi-byte */
	
	asm popf					/* reenable ineterrupts (if where before) */

	/****************************/
mschk:
	asm mov		al,0x80
	asm out		0x43,al			/* latch count */
	asm in		al,0x61			/* waste some time */
	asm in		al,0x42			/* read latched lo-byte */
	asm in		al,0x61			/* waste some time */
	asm in		al,0x42			/* read latched hi-byte */
	asm shl		al,1
	asm jnc		mschk			/* wait until count wraps around  */
	/****************************/

	asm pushf					/* disable interrupts */
	asm cli
	
	asm mov		al,0xB6			/* mode 3, two-byte reload */
	asm out		0x43,al			/* send command */

	asm in		al,0x61			/* PORTB */
	asm and		al,0xFC			/* disable speaker */
	asm out		0x61,al
	
	asm popf					/* reenable ineterrupts (if where before) */
}
