/*
 *
 *  ALL03
 *
 *  26.07.2002
 *
 *  by Fabio Sturman
 *
 *  fabio.sturman@tiscali.it
 *
 *  sleep.c
 *
 *  timing module
 *
 */

/* Copyright (c) 2002 Fabio Sturman (fabio.sturman@tiscali.it)
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 */

#include <stdio.h>
#include <bios.h>
#include "../include/sleep.h"

unsigned long one_ms;

void (*pdelay)(float f);

long get_timer_ticks(void)
{
  long t;
  
  _bios_timeofday(_TIME_GETCLOCK, &t);
  return(t);

}

/* returns value of one_ms */
unsigned long get_one_ms(void)
{
  return(one_ms);
}

/* delay */
void dummy(unsigned long tl)
{
  unsigned long ul;

  ul=tl;
}
    
/* test processor speed & compute counter (one_ms) for 1ms delay */
int test_timer(void)
{
  unsigned long t, nt;
  long t0, t1, dt;
  int i;

  one_ms=0l;
  nt=1024l;

  for(i=0;i<22;i++)
  {
    t0=get_timer_ticks();
    for(t=0;t<nt;t++) dummy(t);
    t1=get_timer_ticks();

    dt=t1-t0;
#ifdef DEBUG
    printf("i=%3d  dt=%8ld  nt=%9ld\n",i,dt,nt);
#endif
    if(dt>50l)
    {
      one_ms=(unsigned long)(nt/(((float)dt) * 54.94));
#ifdef DEBUG
      printf("one_ms=%8ld\n",one_ms);
#endif
      break;
    }
    nt*=2;
  }
  
  if(one_ms)
  {
    pdelay=fdelay_ms;
    return 0;
  }
  else return(1);
}

/* delay in ms */
void delay_ms(int n)
{
  int i;
  unsigned long t;
    
  for(i=0;i<n;i++)
    for(t=0;t<one_ms;t++) dummy(t);
}

/* delay in ms float */
void fdelay_ms(float f)
{
  int i, n;
  unsigned long t, d;

  n=(int)f;
  d=(int)((f-n)*one_ms);  
  for(i=0;i<n;i++)
    for(t=0;t<one_ms;t++) dummy(t);
  for(t=0;t<d;t++) dummy(t);
}

