/*
 *========================================================================
 * $Id: work.c 225 2004-05-18 14:16:59Z rgb $
 *
 * See copyright in copyright.h and the accompanying file COPYING
 *========================================================================
 */

/*
 *========================================================================
 * This is the main loop of the program.  We should remain here looping
 * until the program is terminated.
 *========================================================================
 */

#include "wulfstat.h"

void work()
{

 int i,j,k;
 char *xpval;
 static int cycle=0;
 static int cycle_seconds=0,cycle_last=0,cycle_time;
 struct timeval sleepytime;
 fd_set in;
 char keyin;
 Host *hostptr;
 ListElement *element;

 if((verbose == D_ALL) || (verbose == D_WORK)){
   fprintf(OUTFP,"D_WORK: Starting wulfstat_work().  Use -v %d to focus.\n",D_WORK);
   sleep(1);
 }

 /* 
  * Zero the cycle counter and off to work-loop we go...
  */
 cycle_cnt = 0;

 /*
  * We loop forever, with a variable (user selectable) delay and a keyboard
  * escape (where we CAN do e.g. dynamic reconfiguration therein).
  */
 while(1){

   sleepytime.tv_sec = update_delay;
   sleepytime.tv_usec = 0;
   FD_ZERO(&in);
   FD_SET(0, &in);
   if((verbose == D_ALL) || (verbose == D_WORK)){
     fprintf(OUTFP,"D_WORK: About to wait for keystroke or %d seconds\n",update_delay);
   }
   if(select(1, &in, 0, 0, &sleepytime) > 0 && read(0, &keyin, 1) == 1) {
     if((verbose == D_ALL) || (verbose == D_WORK)){
       fprintf(OUTFP,"D_WORK: Got %c keystroke, calling select_option().\n",keyin);
     }
     select_option(keyin);
   } else {
     /* 
      * Increment cycle counter, but only on a timeout.
      */
     cycle_cnt++;
   }

   /*
    * receive the results and put them where they belong.
    */
   if((verbose == D_ALL) || (verbose == D_WORK)){
     fprintf(OUTFP,"D_WORK:\n");
     fprintf(OUTFP,"D_WORK: UPDATING ALL INITIALIZED HOSTS\n");
     fprintf(OUTFP,"D_WORK:\n");
   }
   update_host_values(hostlist);

   /*
    * display them.
    */
   if((verbose == D_ALL) || (verbose == D_WORK)){
     fprintf(OUTFP,"D_WORK:\n");
     fprintf(OUTFP,"D_WORK: DISPLAYING ALL INITIALIZED HOSTS\n");
     fprintf(OUTFP,"D_WORK:\n");
   }
   display_values(hostlist);

   if(count != -1 && cycle_cnt >= count) quit();

 }

}
