/*---------------------------------------------------------------------------
 * filename - delay.c
 *
 * function(s)
 *        delay - wait for specified period.
 * $Revision: 1.2 $
 *--------------------------------------------------------------------------*/

/*
 *      C/C++ Run Time Library - Version 5.0
 *
 *      Copyright (c) 1987, 1992 by Borland International
 *      All Rights Reserved.
 *
 */


#include <dos.h>

static unsigned long multiplier = 1193*2L;

static void near dummy (void) {}

static unsigned near readtimer (void)
{
  asm pushf                    /* Save interrupt flag                       */
  asm cli                      /* Disable interrupts                        */
  asm mov  al,0h               /* Latch timer 0                             */
  asm out  43h,al
      dummy();                 /* Waste some time */
  asm in   al,40h              /* Counter --> bx                            */
  asm mov  bl,al               /* LSB in BL                                 */
      dummy();                 /* Waste some time */
  asm in   al,40h
  asm mov  bh,al               /* MSB in BH                                 */
  asm not  bx                  /* Need ascending counter                    */
  asm popf                     /* Restore interrupt flag                    */
  return( _BX );
}

void timer_init(void)
{
    int i;

    for (i = 0; i < 100; i++)
        if ((readtimer() & 1) == 0)     /* readtimer() returns complement */
            {
            multiplier = 1193L;
            return;
            }
}

void delay( unsigned milliseconds )
{
    unsigned long stop;
    unsigned cur, prev;

    stop = (prev = readtimer()) + (milliseconds * multiplier);

    while ((cur = readtimer()) < stop)
        {
        if (cur < prev)     /* Check for timer wraparound */
            {
            if (stop < 0x10000L)
                break;
            stop -= 0x10000L;
            }
        prev = cur;
        }
}
