# include "pcontrol.h"

int stdout_pc (int argc, char **argv) {

  int JobID, StackID;
  Job *job;
  IOBuffer *buffer;

  if (argc != 2) {
    gprint (GP_ERR, "USAGE: stdout (JobID)\n");
    gprint (GP_LOG, "STATUS %d\n", -1);
    return (FALSE);
  }
  
  /* find Job of interest (must be EXIT or CRASH) */
  JobID = atoi (argv[1]);

  StackID = PCONTROL_JOB_EXIT;
  job = PullJobFromStackByID (StackID, JobID);
  if (job != NULL) goto found_stdout;

  StackID = PCONTROL_JOB_CRASH;
  job = PullJobFromStackByID (StackID, JobID);
  if (job != NULL) goto found_stdout;

  gprint (GP_ERR, "job not found in EXIT or CRASH\n");
  gprint (GP_LOG, "STATUS %d\n", -2);
  return (FALSE);

found_stdout:
  buffer = &job[0].stdout;
  fwrite (buffer[0].buffer, 1, buffer[0].Nbuffer, stdout);
  gprint (GP_LOG, "STATUS %d\n", 0);
  PutJob (job, StackID, STACK_BOTTOM);
  return (TRUE);
}

int stderr_pc (int argc, char **argv) {

  int JobID, StackID;
  Job *job;
  IOBuffer *buffer;

  if (argc != 2) {
    gprint (GP_ERR, "USAGE: stderr (JobID)\n");
    gprint (GP_LOG, "STATUS %d\n", -1);
    return (FALSE);
  }
  
  /* find Job of interest (must be EXIT or CRASH) */
  JobID = atoi (argv[1]);

  StackID = PCONTROL_JOB_EXIT;
  job = PullJobFromStackByID (StackID, JobID);
  if (job != NULL) goto found_stderr;

  StackID = PCONTROL_JOB_CRASH;
  job = PullJobFromStackByID (StackID, JobID);
  if (job != NULL) goto found_stderr;

  gprint (GP_ERR, "job not found in EXIT or CRASH\n");
  gprint (GP_LOG, "STATUS %d\n", -2);
  return (FALSE);

found_stderr:
  buffer = &job[0].stderr;
  fwrite (buffer[0].buffer, 1, buffer[0].Nbuffer, stdout);
  gprint (GP_LOG, "STATUS %d\n", 0);
  PutJob (job, StackID, STACK_BOTTOM);
  return (TRUE);
}
