/* wport.    Wait for Port to appear, by Ed Mackey */
/* Source and binary are Public Domain.            */

/* Example script:  runback EdPlayer  ;start EdPlayer
                    wport EDPLAYER    ;wait for EdP to get ready
                    telled ...        ;send some EdP commands
*/

#include <stdio.h>
#include <functions.h>

struct Library *GfxBase;

main(argc,argv)
int argc;
char *argv[];
{

	char portname[255];
	long time,failc,i;

	time = 30;  /* Max time to wait, in seconds.       */
	            /* PAL machines may wait a bit longer. */
	            /* If port appears (like it should) before the time */
	            /* expires, the command returns immediately.        */

	failc = 10; /* How bad to fail if port doesn't show up */

	GfxBase = OpenLibrary("graphics.library",0l);

	if (argc == 2)
		if (!(strcmp(argv[1],"?")))   /* for "wport ?" */
			argc = 1;

	if (argc != 2)
	{
		printf("USAGE: wport <portname>           ;by Ed Mackey.\n");
		printf("   Waits about %d seconds for ARexx port to appear.\n",time);
		printf("   Returns when port appears, or fails if time expires.\n");
		printf("   PORT NAMES ARE CASE SENSITIVE.\n");
		printf("   Example:  wport EDPLAYER\n");
		printf("      This example waits for EdPlayer's ARexx port to open.\n");
	} else {
		i = time * 60;  /* Calculate approx. number of VBLANKs to wait */
		strcpy(portname,argv[1]);
		do
		{
			WaitTOF();  /* This is to prevent busy waiting. */
			if(FindPort(portname))
				i = failc = 0;
		} while (--i > 0);
	}

	CloseLibrary(GfxBase);
	exit(failc);
}
