/*

				Modem driver
				
*/

#include "netfone.h"

#ifdef MODEM

int modemHandle = -1;					// Open modem handle

/*  OPENMODEM  --  Open the modem and initialise modes.  */

int openModem(HWND hwnd)
{
	int s;
	DCB dcb;
	COMSTAT cs;

	if (modemHandle != -1) {
		closeModem(hwnd);
	}
	modemHandle = OpenComm(commport, modemInputQueue, modemOutputQueue);
	if (modemHandle < 0) {
        MsgBox(hwnd, MB_ICONSTOP | MB_OK, Format(46), modemHandle);
        modemHandle = -1;
        return FALSE;
	}
	
	if (GetCommState(modemHandle, &dcb) < 0) {
        MsgBox(hwnd, MB_ICONSTOP | MB_OK, rstring(IDS_T_MODEM_STATUS_ERR));
	    closeModem(hwnd);
	    return FALSE;
	}
	dcb.BaudRate = (UINT) atol(baudrate);
	dcb.ByteSize = 8;
	dcb.Parity = 0;
	dcb.StopBits = 0;
	dcb.fBinary = TRUE;
	dcb.fParity = FALSE;
	dcb.fOutxCtsFlow = FALSE;
	dcb.fOutxDsrFlow = FALSE;
	dcb.fOutX = FALSE;
	dcb.fInX = FALSE;
	dcb.fPeChar = FALSE;
	dcb.fChEvt = FALSE;
	dcb.fDtrflow = FALSE;
	dcb.fRtsflow = FALSE;
	
	s = SetCommState(&dcb);
	if (s < 0) {
        MsgBox(hwnd, MB_ICONSTOP | MB_OK, Format(47), s);
	    closeModem(hwnd);
        return FALSE;
	}
	
	FlushComm(modemHandle, 0);
	FlushComm(modemHandle, 1);
	V GetCommError(modemHandle, &cs);	
	SetCommEventMask(modemHandle, EV_RXCHAR | EV_TXEMPTY);
	V GetCommEventMask(modemHandle, EV_RXCHAR | EV_TXEMPTY); 
	EnableCommNotification(modemHandle, hwndMDIFrame, 150, 1);
    EscapeCommFunction(modemHandle, SETDTR);
    
    //	Send the modem initialisation string
    
	V GetCommError(modemHandle, &cs);
	WriteComm(modemHandle, modemInitString, strlen(modemInitString));
	V GetCommError(modemHandle, &cs);
	WriteComm(modemHandle, "\r", 1);
    
	return TRUE;
} 

/*  CLOSEMODEM  --  Close the modem.  OK to call even if modem isn't open.  */

int closeModem(HWND hwnd)
{
	if (modemHandle != -1) {
   		EnableCommNotification(modemHandle, NULL, -1, -1);
   		EscapeCommFunction(modemHandle, CLRDTR);
		CloseComm(modemHandle);
	}
	modemHandle = -1;
	return TRUE;
}
#endif
