// MteSrlTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "mtesrl.h"
#include "mteerr.h"

int main(int argc, char** argv)
{
	char ErrMsg[256], FileName[MAX_PATH], ConnectParams[1024], *p;
	int32_t Handle, err, hTable;
	MTEMSG *Msg;

	// change executable filename extension to .INI and read connect parameters from INI file
	p = FileName + GetModuleFileNameA(NULL, FileName, sizeof(FileName)); 
	while ((p > FileName) && (*p != '.')) p--;
	*p = '\0';
	strcat_s(FileName, ".ini");
	GetPrivateProfileSectionA("MTEConnect", ConnectParams, sizeof(ConnectParams), FileName);
	// replace \0 with \n
	p = ConnectParams;
	while (*p) {
		while (*p) p++;
		*p = '\n';
		p++;
	}
	printf(ConnectParams);

	printf("Connecting to localhost...\n");
	Handle = MTEConnect(ConnectParams, ErrMsg);
	if (Handle < MTE_OK) {
		CharToOemA(ErrMsg, ErrMsg);
		printf("Error %d: '%s'\n", Handle, ErrMsg);
		return Handle;
	}
	printf("Connected\n");

	err = MTEStructure(Handle, &Msg);
	if (err != MTE_OK) {
		CharToOemA(MTEErrorMsg(err), ErrMsg);
		printf("MTEStructure(): %d: '%s'\n", err, ErrMsg);
	} 
	else printf("MTEStructure() returned %d bytes\n", Msg->DataLen);

	hTable = MTEOpenTable(Handle, "TESYSTIME", NULL, true, &Msg);
	if (hTable >= MTE_OK) {
		printf("TESYSTIME table opened, %d bytes received\n", Msg->DataLen);

		for (int i = 0; i < 5; i++) {
			Sleep(50);
			MTEAddTable(Handle, hTable, 0x12345678);
			if (MTE_OK == MTERefresh(Handle, &Msg)) printf("MTERefresh() returned %d bytes\n", Msg->DataLen);
		}

		MTECloseTable(Handle, hTable);
	}
	else printf("MTEOpenTable('TESYSTIME'): %d\n", hTable);

	// for IFC_BROKER26 interface:
	err = MTEExecTrans(Handle, "ORDER", "S01-00000F00BLS P  TQBRMOEX        00001101000000000010000000000                                                                  ", ErrMsg);
	CharToOemA(ErrMsg, ErrMsg);
	printf("Error %d: '%s'\n", err, ErrMsg);

	MTEDisconnect(Handle);
	printf("Disconnected");
	return 0;
}

