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

OVERLAPPED AcksysWriteOverlap;
#define DBG_WRITE	if(AcksysWriteDebug)fprintf

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


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

	if( !WriteFile(hfd,str,len,&count,&AcksysWriteOverlap) )
	{
		int lasterror = GetLastError();
		if(lasterror != ERROR_IO_PENDING) {
			DBG_WRITE(stderr,"Write failed, code %d\n",
				GetLastError());
		} else
			DBG_WRITE(stderr,"w");
		return -1;
	}
	if(len != count) {
		DBG_WRITE(stderr,"Write: len=%d count=%d\n",len,count);
	}
	return count;
}

int
AcksysWaitWrite(HANDLE hfd)
{
	DWORD count;

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