// emul8852.cpp : Defines the entry point for the console application.
//
#define _CRT_SECURE_NO_DEPRECATE
#include <windows.h>
#include <stdio.h>
#include <process.h> 
#include <signal.h>
#include <assert.h>

// это - баг. файл блокировки должен находиться в конкретном месте, а не в текущем каталоге
#define LOCK_FILE_TRUENAME "8852.lck"

#define LOCK_FILE_NAME_SIZE 512


#ifdef WIN32
#define spawnl _spawnl
#define unlink _unlink
#endif 


int run_reader(int argc, char *argv[]) {
	char lockFileName[LOCK_FILE_NAME_SIZE];
	int tempPathLength=GetTempPath(LOCK_FILE_NAME_SIZE,lockFileName);
	if (!tempPathLength) exit(10); // unable to get lockfile dir
	if (sprintf_s(lockFileName+tempPathLength,LOCK_FILE_NAME_SIZE-tempPathLength,LOCK_FILE_TRUENAME)<int(strlen(LOCK_FILE_TRUENAME)))
		exit(11); // lock file name does not fit in buffer;
	assert(sizeof(HANDLE)==sizeof(DWORD)); 
	if (argc==1) { 
		// to allow async input from port, create lock-file, start sub-process, wait for any character 
		// on input, then kill sub-process and exit. 
		FILE *lock_file;
		fopen_s(&lock_file,lockFileName,"a");
		if (!lock_file) return(1);  // printf("unable to create " LOCK_FILE_NAME ", error %d\n", errno); 
		intptr_t child=spawnl( _P_NOWAIT, argv[0],argv[0],"1",NULL);
		if (child==-1) {  return(2); }; // printf("unable to spawn child, error %d\n", errno); 
		getc(stdin); 
		fclose(lock_file); 
		unlink(lockFileName);
		TerminateProcess(HANDLE(child),0);
		return(0);
	}
	else {
		Sleep(1500);
		for(int i=0;i<1000000;i++) {
			printf("t00%d.0C:t0023.9C\n",i);
			fflush(stdout); 
			Sleep(300);
	   }
	   return(0);
	}
}

int main(int argc, char *argv[]) {
	int res=run_reader(argc,argv); 
	putc('q',stdout);
	fflush(stdout); 
	return(res);
}
