# include "pcontrol.h"

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

  char *Host, **targv;
  int i, N, Mode, targc, Timeout;
  IDtype JobID;

  if (get_argument (argc, argv, "-host") && get_argument (argc, argv, "+host")) {
      gprint (GP_ERR, "ERROR: -host and +host are incompatible\n");
      return (FALSE);
  }    

  Host = NULL;
  Mode = PCONTROL_JOB_ANYHOST;
  if ((N = get_argument (argc, argv, "-host"))) {
    remove_argument (N, &argc, argv);
    Host = strcreate (argv[N]);
    remove_argument (N, &argc, argv);
    Mode = PCONTROL_JOB_WANTHOST;
  }
  if ((N = get_argument (argc, argv, "+host"))) {
    remove_argument (N, &argc, argv);
    Host = strcreate (argv[N]);
    remove_argument (N, &argc, argv);
    Mode = PCONTROL_JOB_NEEDHOST;
  }
  if (Host == NULL) Host = strcreate ("anyhost");
 
  Timeout = 100;
  if ((N = get_argument (argc, argv, "-timeout"))) {
    remove_argument (N, &argc, argv);
    Timeout = atoi (argv[N]);
    remove_argument (N, &argc, argv);
  }

  if (argc < 2) {
    gprint (GP_ERR, "USAGE: job [options] (arg0) (arg1) ... (argN)\n");
    gprint (GP_ERR, "  arguments of the form @MAX_THREADS@ will be replaced when the job is launched\n");
    FREE (Host);
    return (FALSE);
  }
  
  targc = argc - 1;
  ALLOCATE (targv, char *, targc);
  for (i = 1; i < argc; i++) {
    targv[i-1] = strcreate (argv[i]);
  }

  JobID = AddJob (Host, Mode, Timeout, targc, targv);
  gprint (GP_LOG, "JobID: %d\n", (int) JobID);
  return (TRUE);
}
