module external DetectParallelInfo, ParallelInfo, ParallelInfo_print:

ParallelInfo := proc(NrParallelProc:posint, ProcNr:posint)
    return(noeval(procname(args))):
end:
ParallelInfo_print := proc(pinf) option internal;
    printf('Process %d on %s: job nr %d of %d\n', getpid(), hostname(), 
        pinf['ProcNr'], pinf['NrParallelProc']);
end:
CompleteClass(ParallelInfo):

ErrorExplicitNrJobs := proc()
    msg := ['We require that job-arrays now explicitly specify the number of jobs ',
            'in the array. You should add to your submission script an environment ',
            'variable "NR_PROCESSES" that holds the total number of jobs you use. ',
            'Example:\n in bash:  export NR_PROCESSES=100\n in tcsh:  setenv NR_PROCESSES=100'];
    prints(ConcatStrings(msg,'\n'));
    error('require NR_PROCESSES to be assigned to an environment variable');
end:

Variables_Platform := proc(tot, cur)
    if type(tot, posint) and type(cur, posint) then
       if cur <= tot then return(ParallelInfo(tot, cur));
       else 
          error(sprintf('Inconsistency in parallel job setup:\n process nr (%d) must be smaller or equal to total nr of processes (%d)',cur, tot));
       fi:
    else
       error('parallel setup must be called with positive integer values');
    fi:
end:

DetectParallelInfo := proc()
    if type(NR_PROCESSES, posint) and type(THIS_PROC_NR, posint) then 
       return(Variables_Platform(NR_PROCESSES, THIS_PROC_NR));
    fi: 
    nr := getenv('NR_PROCESSES');
       
    if getenv('LSB_JOBID')<>'' then
        job_idx := getenv('LSB_JOBINDEX');
    elif getenv('SGE_TASK_ID')<>'' then
        job_idx := getenv('SGE_TASK_ID');
    elif getenv('SLURM_ARRAY_JOB_ID') <> '' then
        job_idx := getenv('SLURM_ARRAY_TASK_ID');
        if nr='' and getenv('SLURM_ARRAY_TASK_MAX')<>'' then
            nr := getenv('SLURM_ARRAY_TASK_MAX');
        fi:
    elif getenv('PBS_ARRAY_INDEX') <> '' then
        job_idx := getenv('PBS_ARRAY_INDEX');
    elif getenv('THIS_PROC_NR') <> '' then
        job_idx := getenv('THIS_PROC_NR');
    else 
        return(ParallelInfo(1,1));
    fi:
    if nr='' and (job_idx='' or job_idx='0' or lowercase(job_idx)='undefined') then
        warning('not run as a job-array. Will assume it is a single process');
        return(ParallelInfo(1,1));
    fi:
    if nr='' or not type(parse(nr), posint) then 
        ErrorExplicitNrJobs();
    fi:
    NrParallelJobs := parse(nr);
    job_idx := parse(job_idx);
    if not type(job_idx, posint) then
        warning('determined "job_idx" value is not an integer: ' . job_idx);
        if NrParallelJobs=1 then job_idx := 1;
        else error('job_idx not an integer: '.job_idx) fi:
    fi:
    return(Variables_Platform(NrParallelJobs, job_idx));
end:

end: #module
