# include "pantasks.h"

int CheckTasks () {

  Job *job;
  Task *task;
  int status;

  /** 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) < 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;
    }

    /* 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;
      }
    }

    /* check if there are errors with this task */
    if (!ValidateTask (task, TRUE)) { 
	gettimeofday (&task[0].last, (void *) NULL);
	continue;
    }

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

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

    /* 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 ++;

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

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