//Example code: Commincation and sending pattern to SavvyGate.
// scan location is stored in locx, locy; any point outside the frame width*height is skipped for the pixelated detector recording.
//Written by Shahar Seifer, Weizmann Institute of Science (C) 2023

int packet_id_last;
int record_position = 0;
int state_counter = 0;
bool record_state = false;
bool previous_record_state = false;
int packet_id = 0;
for (int j = 0; j < NumSamples; j++)
{
                record_state = (locx[j] >= 0 && locy[j] >= 0 && locx[j] < width && locy[j] < height);
                if (record_state == previous_record_state && state_counter < 32765 )
                {
                        state_counter++;
                }
                else
                {
                        if (record_position <= max_record_count - 4)
                        {
                                if (record_position % 5000 == 4998) //control stamp at the end of each 5000 byte packet
                                {
                                        if (record_position < max_record_count - 5000)
                                        {
                                                ArinaGate_pattern[record_position] = packet_id; //stamp current packet id
                                                packet_id++;
                                                record_position++;
                                                ArinaGate_pattern[record_position] = packet_id; //stamp end packet id that is above current id to signal that another packet should be loaded 
                                                record_position++;
                                        }
                                }
                                ArinaGate_pattern[record_position] = (byte)(state_counter & 0b11111111);
                                record_position++;
                                if (previous_record_state)
                                {
                                        ArinaGate_pattern[record_position] = (byte)((state_counter >> 8 & 0b01111111) | 0b10000000);
                                }
                                else
                                {
                                        ArinaGate_pattern[record_position] = (byte)((state_counter >> 8 & 0b01111111));
                                }
                                record_position++;
                        }
                        state_counter = 1;
                }
                previous_record_state = record_state;
}
for (int pos = record_position; pos < 4998 + 5000 * packet_id; pos++)
{
        ArinaGate_pattern[pos] = 0;
}
ArinaGate_pattern[4998 + 5000 * packet_id] = packet_id; //Stamp the end of packet series
ArinaGate_pattern[4999 + 5000 * packet_id] = packet_id;
packet_id_last = packet_id; //say how many packets to transmit
if (packet_id_last<=20) 
	Send_SavvyGate_pattern();
else		
	printf("Size exceeded SavvyGate capacity");




bool Send_SavvyGate_pattern() 
{
	HANDLE hComm;
	DCB dcb;
	bool fSuccess;
	COMMTIMEOUTS timeouts;

	hComm = CreateFileA("COM3",                //port name
		GENERIC_READ | GENERIC_WRITE, //Read/Write  
		0,                            // 1=Yes Sharing
		NULL,                         // No Security
		OPEN_EXISTING,// Open existing port only
		0,            // Non Overlapped I/O
		NULL);        // Null for Comm Devices

	if (hComm == INVALID_HANDLE_VALUE)
	{
		printf("Error in opening serial port");
		return false;
	}
	else
	printf("Connection with ArinaGate COM Port \n");



	fSuccess = GetCommState(hComm, &dcb);
	dcb.BaudRate = CBR_115200;     //  baud rate
	dcb.ByteSize = DATABITS_8;             //  data size, xmit and rcv
	dcb.Parity = NOPARITY;      //  parity bit
	dcb.StopBits = ONESTOPBIT;    //  stop bit
	dcb.fDtrControl = 0;
	dcb.fRtsControl = 0;


	fSuccess=SetCommState(hComm, &dcb);
	//PurgeComm(hComm, PURGE_RXABORT |PURGE_RXCLEAR);

	DWORD dNoOfBytesWritten = 0;
	char message[6];

	fSuccess = GetCommTimeouts(hComm, &timeouts);
	timeouts.ReadTotalTimeoutConstant = 300;
	timeouts.WriteTotalTimeoutConstant = 0;
	timeouts.ReadIntervalTimeout = MAXDWORD;
	timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
	timeouts.WriteTotalTimeoutMultiplier = MAXDWORD;
	fSuccess = SetCommTimeouts(hComm, &timeouts);

	Sleep(200);
	fSuccess = PurgeComm(hComm, PURGE_TXABORT |
		PURGE_RXABORT |
		PURGE_TXCLEAR |
		PURGE_RXCLEAR);

	bool Status=true;
	int ccount = 0;
	int packet_counter = 0;

	while (Status && packet_counter <= packet_id_last)
	{
		Status = WriteFile(hComm,        // Handle to the Serial port
			(byte*) (ArinaGate_pattern+5000* packet_counter),     // Data to be written to the port   LPCVOID
			5000,  //No of bytes to write
			&dNoOfBytesWritten, //Bytes written
			NULL);

		if (Status)
		{
			Sleep(200);
			Status = ReadFile(hComm,        // Handle to the Serial port
				message,     // Data to be written to the port
				6,  //No of bytes to read
				&dNoOfBytesWritten, //Bytes read
				NULL);
			ccount = strncmp(message, "_OK_", 4);
			if (ccount == 0)
			{
				printf("Pattern transmitted\n");
				Status = true;
			}
			else
			{
				printf("No acknowledgement from ArinaGate \n");
				Status = false;
			}
		}
		else
		{
			printf(">>> Failed transmission to ArinaGate <<< \n");
		}
		packet_counter++;
	}
	

	CloseHandle(hComm);//Closing the Serial Port

	return Status;
}
