/* ESCAPE.CMD -- Quote a filename for use in command-interpreter exits */
/*
 * This is a REXX script that contains an escape() function that can be
 * used to quote filenames (and other arguments) that are to be passed
 * to command-interpreter exits, ensuring that characters within the
 * argument are not treated as command-interpreter metacharacters.
 *
 * (c) Copyright 2010 Jonathan de Boyne Pollard.  "Moral" rights asserted.
 *
 * Permission is hereby granted to copy, modify, and redistribute this script
 * as long as the author is not held responsible for any consequences of its
 * possession or use, and as long as you agree that it comes with no guarantee.
 */

escape: procedure
	parse arg s

	quote = ''
	temp = s
	do while temp \= ''
		c = left(temp,1)
		temp = substr(temp,2)
		if c = ' ' | c = X'09' then do
			quote = '"'
			leave
		end
	end

	r = ''
	if quote \= '' then do
		do while s \= ''
			c = left(s,1)
			s = substr(s,2)
			select
			when c = '"' then r = r||'\'||c
			when c = '%' then r = r||'%'||c
			otherwise         r = r||c
			end
		end
	end
	else
	do
		do while s \= ''
			c = left(s,1)
			s = substr(s,2)
			if c = '^' | c = '%' | c = '&' | c = '|' | c = '>' | c = '<' then
				r = r||'^'||c
			else
				r = r||c
		end
	end

	return quote||r||quote
