#include <windows.h>
#include <stdio.h>
#include <winioctl.h>
#include "ack_w32.h"

OVERLAPPED AcksysReadOverlap;
#define DBG_READ	if(AcksysReadDebug)fprintf

HANDLE
AcksysInitAsyncRead()
{
	AcksysReadOverlap.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
	if(AcksysReadOverlap.hEvent == NULL)
		DBG_READ(stderr,"Event failed, code %d\n",GetLastError());
	return AcksysReadOverlap.hEvent;
}


int
AcksysAsyncRead(HANDLE hfd,char *str, DWORD len)
{
	DWORD count;

	if( !ReadFile(hfd,str,len,&count,&AcksysReadOverlap) )
	{
		int lasterror = GetLastError();
		if(lasterror != ERROR_IO_PENDING) {
			DBG_READ(stderr,"Read failed, code %d\n",lasterror);
		} else
			DBG_READ(stderr,"r");
		SetLastError(lasterror);
		return -1;
	}
	if(len != count) {
		DBG_READ(stderr,"Read: len=%d count=%d\n",len,count);
	}
	return count;
}

int
AcksysWaitRead(HANDLE hfd)
{
	DWORD count;

	if(!GetOverlappedResult(hfd, &AcksysReadOverlap, &count,TRUE)){
		DBG_READ(stderr,"GetOver failed, code %d, count %d\n",
			GetLastError(), count);
		return -1;
	}
	ResetEvent(AcksysReadOverlap.hEvent);
	return count;
}
