/*
  Copyright 2003-2005 Ronald S. Burkey <info@sandroid.org>
  
  This file is part of yaAGC.

  yaAGC 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 2 of the License, or
  (at your option) any later version.

  yaAGC 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 yaAGC; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

  In addition, as a special exception, Ronald S. Burkey gives permission to
  link the code of this program with the Orbiter SDK library (or with 
  modified versions of the Orbiter SDK library that use the same license as 
  the Orbiter SDK library), and distribute linked combinations including 
  the two. You must obey the GNU General Public License in all respects for 
  all of the code used other than the Orbiter SDK library. If you modify 
  this file, you may extend this exception to your version of the file, 
  but you are not obligated to do so. If you do not wish to do so, delete 
  this exception statement from your version. 
 
  Filename:	nbfgets.c
  Purpose:	A portable (i.e., Linux AND Win32) non-blocking variant of fgets. 
  		Requires pthreads (on *nix) or "POSIX Threads for Win32"
		(http://sources.redhat.com/pthreads-win32/).
  Compiler:	GNU gcc.
  Contact:	Ron Burkey <info@sandroid.org>
  Reference:	http://www.ibiblio.org/apollo/index.html
  Mods:		08/09/04 RSB.	Began.
		02/27/05 RSB	Added the license exception, as required by
				the GPL, for linking to Orbiter SDK libraries.
		05/14/05 RSB	Corrected website references.
*/

#include <pthread.h>
#include <stdio.h>
#include <string.h>

#define MAX_NBFGETS 256
static int nbfgetsInitialized = 0;
static volatile int nbfgetsReady = 0;
static char nbfgetsBuffer[MAX_NBFGETS];
static pthread_cond_t nbfgetsCond = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t nbfgetsMutex;
static pthread_t nbfgetsThread;

static void *
nbfgetsThreadFunction (void *Arg)
{
  nbfgetsBuffer[MAX_NBFGETS - 1] = 0;
  while (1)
    {
      // Wait for an input string, presumably sleeping.
      if (nbfgetsBuffer != fgets (nbfgetsBuffer, MAX_NBFGETS - 1, stdin))
        {
#ifndef WIN32	    
	  struct timespec req, rem;
	  req.tv_sec = 0;
	  req.tv_nsec = 10000000;
	  nanosleep (&req, &rem);
#endif // WIN32
          continue;
	}
      nbfgetsReady = 1;
      // Go to sleep until the string has been processed.
      pthread_cond_wait (&nbfgetsCond, &nbfgetsMutex);
    }
}

// Returns NULL until a string is ready.  The string is always fetched from
// stdin, and has a maximum size of MAX_NBFGETS (including the nul-terminator).
// (In other words, making Length bigger than MAX_NBFGETS has the same effect
// as making it equal to MAX_NBFGETS.)  Length also includes the nul-termination.

char *
nbfgets (char *Buffer, int Length)
{
  if (!nbfgetsInitialized)
    {
      // We haven't started the other thread yet.  Better do that.
      nbfgetsReady = 0;
      pthread_create (&nbfgetsThread, NULL, nbfgetsThreadFunction, NULL);
      nbfgetsInitialized = 1;
    }
  // Has the other thread managed to fetch a string yet?
  if (!nbfgetsReady || Length < 1)
    return (NULL);		// No string ready yet.
  Length--;
  strncpy (Buffer, nbfgetsBuffer, Length);
  Buffer[Length] = 0;		// Make sure nul-terminated.
  nbfgetsReady = 0;
  // Tell the other thread to wake up and get another string.
  pthread_cond_broadcast (&nbfgetsCond);
  return (Buffer);
}

#if 0
// A test program.
int
main (void)
{
  char String[100] = { 0 };
  setvbuf (stdout, NULL, _IONBF, 0);
  while (1)
    {
      printf ("> ");
      while (NULL == nbfgets (String, sizeof (String)));
      printf ("< %s", String);
    }
}
#endif //0

