/*
	Using pvm_gsize()
*/

#include <stdio.h>
#include "pvm3.h"

int
main(argc, argv)
int argc;
char *argv[];
{
	int mytid, mygid, ctid[32];
	int nproc, i;

	mytid = pvm_mytid();
	fprintf(stderr, "%s 0x%x enrolled\n", argv[0], mytid);
	if (mytid < 0) {
		pvm_perror(argv[0]);
		return -1;
		}

	if (argc != 2) goto usage;
	if ((nproc = atoi(argv[1])) < 1) goto usage;
	if (nproc > 32) goto usage;

	/* join a group */
	mygid = pvm_joingroup(argv[0]);

	/* if I'm the first to join then start the others */
	if (mygid == 0) {
		/* start a bunch of children */
    	pvm_spawn(argv[0], argv+1, 0, "", nproc-1, ctid);
		/* check them */
		for (i = 0; i < nproc-1; i++)
			fprintf(stderr, "0x%x\n", ctid[i]);
		}

	while(pvm_gsize(argv[0]) < nproc)
		if (mygid == 0)
			fputs("waiting on kids to join\n", stderr);

	/* sync */
	pvm_barrier(argv[0], nproc);

	/* leave the group */
	if(pvm_lvgroup(argv[0]) < 0)
			pvm_perror(argv[0]);

	pvm_exit();
	return 0;
usage:
	fprintf(stderr, "usage: %s <nproc>\n", argv[0]);
	return -1;
}
