/**********************************************************************
* 
* user_abort.cpp
*
* This file is part of MitoGen
* 
* Copyright (C) 2013-2016 -- Centre for Biomedical Image Analysis (CBIA)
* http://cbia.fi.muni.cz/
* 
* MitoGen is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* 
* MitoGen is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with MitoGen. If not, see <http://www.gnu.org/licenses/>.
* 
* Author: Vladimir Ulman
* 
* Description: A module that controls the presence of LOCK file in the
* current directory. If the file is missing, the application correctly
* completes the phases of all living cells in the population. This way,
* we prevent from invasive interruption of the generation process.
*
***********************************************************************/

//#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 :)
}
