% pipein - start shell command and return stream for reading standard output
% pipein :: 
%    text ~'bash shell command',
%    bool ~'quiet operation flag'
% -> java.io.InputStream ~ 'connected to stdout of command',
%    (void -> action void) ~'call this to clean up afterwards'.
%
% If quiet flag is not supplied, it defaults to false.
function [str,cleanup]=pipein(cmd,q)
	if nargin<2, q=false; end
	if ~q, fprintf('Starting sub-process: %s\n',cmd); end

	% OK, here's the deal: the line below doesn't work if Matlab and
	% Java do not agree about their default character encoding, which
	% can happen if you change Matlab's character encoding with, eg
	% >> feature('DefaultCharacterSet','UTF-8')
	% As far as a I can tell, you cannot change the character encoding
	% using by Runtime.exec() for command line arguments once the JVM
	% has been started, and, somewhat perversely, Matlab ingores the 
	% value of the LANG environment variable on startup, preferring to
	% us the encoding specified in $MATLAB_ROOT/bin/lcdata.xml

	% NOT GOOD:
	% process=java.lang.Runtime.getRuntime().exec({'bash','-c',cmd});

	% this is what we're going to do instead: start bash with no
	% arguments to make it read from standard input, then write cmd 
	% with proper encoding to that stream.

	% BETTER:
	cs=feature('DefaultCharacterSet');
	process=java.lang.Runtime.getRuntime().exec('bash');
	writer=java.io.OutputStreamWriter(process.getOutputStream(),cs);
	writer.write(cmd); writer.close();

	str=process.getInputStream();
	cleanup=@dispose;

	function dispose
		if ~q, fprintf('Killing subprocess...\n'); end
		process.destroy();
	end
end
