/* The original version of this program can be found at http://damb.dk */
#include <stdio.h>
#include <windows.h>

void SetTimeOut(HANDLE Port, int sec)
{
  COMMTIMEOUTS commtimeouts;
  GetCommTimeouts(Port, &commtimeouts);
  commtimeouts.ReadIntervalTimeout = 1000*sec;
  commtimeouts.ReadTotalTimeoutMultiplier = 10;
  commtimeouts.ReadTotalTimeoutConstant = 1000*sec;
  SetCommTimeouts(Port, &commtimeouts);
}

void Tx(HANDLE Port, const char *data)
{
  DWORD Dummy;
  WriteFile(Port, data, strlen(data), &Dummy, 0);
  WriteFile(Port, "\r\n", 2, &Dummy, 0);
}

void Rx(HANDLE Port)
{
  char Buffer[128];
  DWORD Length, i;

  ReadFile(Port, Buffer, 128, &Length, 0);

  for(i = 0; i < Length; i++)
    if(Buffer[i] != '\r')
      printf("%c", Buffer[i]);
}

int main(void)
{
  DCB dcb;
  HANDLE ComPort = CreateFile("COM2", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);

  GetCommState(ComPort, &dcb);
  dcb.BaudRate = 9600;
  dcb.ByteSize = 8;
  dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
  dcb.fOutxCtsFlow = 1;
  SetCommState(ComPort, &dcb);
  SetTimeOut(ComPort, 1);

  Tx(ComPort, "AT");
  Rx(ComPort);
  Tx(ComPort, "ATZ");
  Rx(ComPort);

  CloseHandle(ComPort);

  return 0;
}