# include "pantasks.h"

int CheckTasks () {

  Job *job;
  Task *task;
  int status;
  struct timeval now;

  /** test all tasks: ready to test? ready to run? **/
  while ((task = NextTask ()) != NULL) {

    if (!task[0].active) continue;

    /* ready to test? : check exec period */
    if (GetTaskTimer(task[0].last, FALSE) < task[0].exec_period) continue;

    /* need to check if the current time is within valid/invalid periods */
    if (!CheckTimeRanges (task[0].ranges, task[0].Nranges)) {
	gettimeofday (&task[0].last, (void *) NULL);
	continue;
    }
    if (task[0].Nmax && (task[0].Njobs >= task[0].Nmax)) {
	gettimeofday (&task[0].last, (void *) NULL);
	continue;
    }
    if (task[0].NpendingMax && (task[0].Npending >= task[0].NpendingMax)) {
	// fprintf (stderr, "npending: %d, max npending: %d\n", task[0].Npending, task[0].NpendingMax);
	gettimeofday (&task[0].last, (void *) NULL);
	continue;
    }

    // gettimeofday (&now, (void *) NULL);
    // fprintf (stderr, "t0: %d %6d  - \n", now.tv_sec, now.tv_usec);

    /* ready to run? : run task.exec macro */
    if (task[0].exec != NULL) {
      status = exec_loop (task[0].exec);
      if (!status) {
	  gettimeofday (&task[0].last, (void *) NULL);
	  continue;
      }
    }

    // gettimeofday (&now, (void *) NULL);
    // fprintf (stderr, "t1: %d %6d  - \n", now.tv_sec, now.tv_usec);

    /* check if there are errors with this task */
    if (!ValidateTask (task, TRUE)) { 
	gettimeofday (&task[0].last, (void *) NULL);
	continue;
    }
    
    // gettimeofday (&now, (void *) NULL);
    // fprintf (stderr, "t2: %d %6d  - \n", now.tv_sec, now.tv_usec);

    /* construct job from task */
    job = CreateJob (task);

    // gettimeofday (&now, (void *) NULL);
    // fprintf (stderr, "t3: %d %6d  - \n", now.tv_sec, now.tv_usec);

    /* execute job - XXX add status test */
    SubmitJob (job);

    // fprintf (stderr, "nl: %d %6d  - ",
    // task[0].last.tv_sec, task[0].last.tv_usec);

    /* reset timer on task (don't do this if Create/Submit fails) (why not??) */
    gettimeofday (&task[0].last, (void *) NULL);
    task[0].Njobs ++;
    task[0].Npending ++;

    // fprintf (stderr, "%d %6d\n", 
    // task[0].last.tv_sec, task[0].last.tv_usec);

    /* increment Nrun for inclusive ranges with Nmax */
    BumpTimeRanges (task[0].ranges, task[0].Nranges);

    if (TestElapsedCheck()) return (TRUE);
  }
  return (TRUE);
}
