/*	envsearch - search environment for given string

	usage...
		char buf[25];
		envsearch("ALPHA",buf);		puts value of the environment
						variable ALPHA into buf

	functions called...

	_lmove(#bytes,
		source_offset,source_segment,
		target_offset,target_segment)	moves bytes
	_showds()			returns current value of ds register
	_showcs()			returns current value of cs register

	notes...
		Compile with MAIN #defined to generate a standalone program
	which searches the environment for the value of the first argument
	(or PATH, by default).  Limitations...

		environment size:		64K
		target variable name:		23
		environment variable name:	98
		target value:			98-sizeof(target)

	author...
		James R. Van Zandt	(jrv @ mitre-bedford)
*/

envsearch(target,value) char *target,*value;
{	char buf[100],*s,t[25],*env;
	int nt, offset;

	s=t;
	while(*target) *s++=toupper(*target++);
	*s++= '='; *s=0;
	nt = strlen(t);
	offset=0;

/* DeSmet C sets up cs register to point 100H past the Program Segment
   Prefix.  The word at offset 44 in the PSP points to the segment with
   the environment */

	_lmove(2,44,_showcs()-0x10,&env,_showds()); /* get env. pointer */
	while(1)
		{_lmove(100,offset,env,buf,_showds()); /* get (part of) env. */
		s=buf;
		if(*s)
			{/* printf("examining entry: %s \n",s); getchar(); */
			if (strncmp(t,s,nt)==0) return (strcpy(value,s+nt));
			}
		else
			{*value=0;	/* no value found */
			return;
			}
		offset+=strlen(buf)+1;
		}
}


#ifdef MAIN

char val[25],target[]="path";

main(argc,argv) int argc; char **argv;
{	char *t;
	if(argc>1) t=argv[1]; else t=target;
	printf("searching environment for variable \"%s\" \n",t);
	envsearch(t,val);
	printf("the value is \"%s\" \n",val);
}
#endif
