//#include <unistd.h> - for non-blocking I/O
//#include <fcntl.h>  - for non-blocking I/O
#include<fstream>

#include "../macros.h"
#include "user_abort.h"

//hopefully long enough buffer for reading STDIN
//(to prevent from dynamically alocating over and over)
//static char buf[100];

bool UserAbort(const char *file, const bool stop)
{
	/*
	 * Indicator of user requested abort, which is recognized when
	 * user typed any sequence that contained 'q' and pressed enter.
	 * 
	 * The routine performs non-blocking read from std. input of some
	 * 100 characters and searches for 'q'. It found and \e stop is true,
	 * it throws a 'user requested interrupt' exception.
	//non-blocking read of STDIN
	int backup=fcntl(0, F_GETFL);
	fcntl(0, F_SETFL, backup | O_NONBLOCK);
	int retval=read(0,buf,100);
	fcntl(0, F_SETFL, backup);

	for (int i=0; (retval > 0) && (i < retval); ++i)
		if (buf[i]=='q') {
			if (stop)
			  throw ERROR_REPORT("user requested interrupt");
			else
			  return (true);
		}
	*/

	std::ifstream stopFile;
	stopFile.open(file);

	if (stopFile.is_open()) {
		//manged to open file, that's OK
		stopFile.close();

		return (false);
	} else {
		//file si maybe missing, how to indicate the abort?
		if (stop)
		  throw ERROR_REPORT("user requested interrupt");
		else
		  return (true);
	}

	return (false); //should never get here... but anyway: do not stop :)
}
