/*
;:ts = 4

A script to let the user choose to which running copy of BareED he/she would like
to refer. Note: Currently only running copies of BareED from 1 to 9 become supported!
To run this script you need the RequestChoice application in your C drawer,
i.e. you need at least OS 3.0 ! 

*/

IF ~EXISTS('C:RequestChoice') THEN
	EXIT 50

CALL SETCLIP( 'BAREED', '0')

/* Get all public ports (in one single string) */
PORT_STRING = SHOW('P')

/* Create a string that could look likes this: "BAREED.3|BAREED.4|BAREED.1|Cancel" */
OFFSET = 0
GADGET_LINE = '"'
NUMBER_PORTS = 0

DO FOREVER
	/* Get each port which starts with "BAREED." */
	OFFSET = POS( 'BAREED.', PORT_STRING, OFFSET + 1)
	IF OFFSET = 0 THEN
		BREAK
	ELSE
		NUMBER_PORTS = NUMBER_PORTS + 1												/* Amount of ports remembered */
		BAREED_NAME = SUBSTR( PORT_STRING, OFFSET, 8)								/* 8 for BAREED.n */
		BAREED_NAME = OVERLAY("|", BAREED_NAME, LENGTH(BAREED_NAME) + 1)			/* From �"BAREED.n� to �"BAREED.n|� */
		GADGET_LINE = OVERLAY( BAREED_NAME, GADGET_LINE, LENGTH(GADGET_LINE) + 1)	/* From �"BAREED.n|� to �"BAREED.n|BAREED.n|� */
	END

IF NUMBER_PORTS = 0 THEN DO	/* Opps, no running copy of BareED ! */
	ADDRESS COMMAND			/* Let a CLI command do the work */
	'C:RequestChoice >NIL: "BareED Grabber" "Missing a running copy of BareED.*NPlease start BareED manually and*Nthen restart this script!." "I will do it (maybe)"'
	EXIT	20
	END

GADGET_LINE = OVERLAY( 'Cancel"', GADGET_LINE, LENGTH(GADGET_LINE) + 1)				/* From �"BAREED.n|BAREED.n|� to �"BAREED.n|BAREED.n|Cancel"� */

ADDRESS COMMAND			/* Let a CLI command do the work */
'C:RequestChoice >T:BResult "BareED Grabber" "Enter the name of the port whose name*Nrepresents the running application that*Nyou would like to use for this script."' GADGET_LINE

BAREED_NUMBER = '0'		/* Default, in case 'T:BResult cannot be read */

IF OPEN('portnumber', 'T:BResult', 'R') THEN DO		/* Try to open T:BResult where RequestChoice dropped its result */
	BAREED_NUMBER = READCH('portnumber', 1)			/* Read 0 for Cancel and any other value for usecount! */
	CALL CLOSE 'portnumber'
	'C:Delete >NIL: T:BResult'
	END

IF BAREED_NUMBER = '0'	THEN						/* If user cancelled... */
	EXIT 5
		ELSE DO
	BAREED_NUMBER = BAREED_NUMBER - 1				/* Else, create index from given value */
	END

	DEFAULT_BAREED = SUBSTR( GADGET_LINE,  BAREED_NUMBER * 9 + 2 , 8)	/* From index to string (port name) */

CALL SETCLIP( 'BAREED', DEFAULT_BAREED)	/*	Make variable BARRED available to other
											AREXX applications which can use it as host, e.g.:
												BAREED_HOST = GetClip( 'BAREED')
												IF BAREED_HOST = '0' THEN EXIT
												ADDRESS VALUE BAREED_HOST */
EXIT 0