/*
 * avrdude - A Downloader/Uploader for AVR device programmers
 * Copyright (C) 2003, 2004, 2006
 *    Eric B. Weddington <eweddington@cso.atmel.com>
 * Copyright 2008, Joerg Wunsch
 *
 * 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
 */

/* $Id: ppiwin.c 936 2010-01-22 16:40:17Z joerg_wunsch $ */

/*
This is the parallel port interface for Windows built using Cygwin.

In the ppi_* functions that access the parallel port registers,
fd = parallel port address
reg = register as defined in an enum in ppi.h. This must be converted
   to a proper offset of the base address.
*/


#include "ac_cfg.h"
#include "avrdude.h"

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>

#if defined (WIN32NATIVE)
/* why is this double include needed ? */
#include <windows.h>
#include <sys/time.h>
#include <windows.h>
#else
#include <sys/time.h>
#endif

#if !defined(HAVE_GETTIMEOFDAY) && defined (WIN32NATIVE)
struct timezone;
int gettimeofday(struct timeval *tv, struct timezone *unused){
// i've found only ms resolution, avrdude expects us

	SYSTEMTIME st;
	GetSystemTime(&st);
  
	tv->tv_sec=(long)(st.wSecond+st.wMinute*60+st.wHour*3600);
	tv->tv_usec=(long)(st.wMilliseconds*1000);

	return 0;
}
#endif /* HAVE_GETTIMEOFDAY */

#if defined(HAVE_NANOSLEEP)
int microsleep(unsigned int us) {
    struct timespec req = {us / 1000000, (us % 1000000) * 1000};
    struct timespec rem;
    while( nanosleep(&req, &rem) == -1) {
	if (errno != EINTR) {
		return -1;
	}
	/* there is time left to sleep */
	req = rem;
    }
    return 0;
}
#elif defined(HAVE_USLEEP)
int microsleep(unsigned int us) {
    return usleep(us);
}
#elif defined (WIN32NATIVE)
// #define W32USLEEPDBG

#ifdef W32USLEEPDBG

#  define DEBUG_QueryPerformanceCounter(arg) QueryPerformanceCounter(arg)
#  define DEBUG_DisplayTimingInfo(start, stop, freq, us, has_highperf)     \
     do {                                                                  \
       unsigned long dt;                                                   \
       dt = (unsigned long)((stop.QuadPart - start.QuadPart) * 1000 * 1000 \
                            / freq.QuadPart);                              \
       fprintf(stderr,                                                     \
               "hpt:%i usleep usec:%lu sleep msec:%lu timed usec:%lu\n",   \
               has_highperf, us, ((us + 999) / 1000), dt);                 \
     } while (0)

#else

#  define DEBUG_QueryPerformanceCounter(arg)
#  define DEBUG_DisplayTimingInfo(start, stop, freq, us, has_highperf)

#endif

int microsleep(unsigned int us)
{
	int has_highperf;
	LARGE_INTEGER freq,start,stop,loopend;

	// workaround: although usleep is very precise if using
	// high-performance-timers there are sometimes problems with
	// verify - increasing the delay helps sometimes but not
	// realiably. There must be some other problem. Maybe just
	// with my test-hardware maybe in the code-base.
	//// us=(unsigned long) (us*1.5);

	has_highperf=QueryPerformanceFrequency(&freq);

	//has_highperf=0; // debug

	if (has_highperf) {
		QueryPerformanceCounter(&start);
		loopend.QuadPart=start.QuadPart+freq.QuadPart*us/(1000*1000);
		do {
			QueryPerformanceCounter(&stop);
		} while (stop.QuadPart<=loopend.QuadPart);
	}
	else {
		DEBUG_QueryPerformanceCounter(&start);

		Sleep(1);
		Sleep( (DWORD)((us+999)/1000) );

		DEBUG_QueryPerformanceCounter(&stop);
	}

    DEBUG_DisplayTimingInfo(start, stop, freq, us, has_highperf);

    return 0;
}
#else
#error Do not know how to implement microsleep().
#endif  /* !HAVE_USLEEP */
