function img = pasteObjOnBg(obj,backgnd,pos,varargin);
% PASTEOBJONBG: paste an object image onto a larger background image
% at a specified position
%
% Usage: img = pasteObjOnBg(obj,backgnd,pos,varargin);
%  [explain args]
% please explain!!!!
%
%
%
% 06/01/03 ras.

% allow paths to be entered for images
if ischar(obj)
	obj = imread(obj,'jpg');
end
if ischar(backgnd)
	backgnd = imread(backgnd,'jpg');
end

colDepthObj = size(obj,3);
colDepthBg = size(backgnd,3);

% allow for pasting objects and backgrounds of diff't color depths
if colDepthBg > colDepthObj
	for i = colDepthObj+1:colDepthBg
		obj(:,:,i) = obj(:,:,1);
	end
end
if colDepthBg < colDepthObj
	for i = colDepthBg+1:colDepthObj
		bg(:,:,i) = bg(:,:,1);
	end
end

% defaults 
cropCol = -1;  	% won't crop out any part of object image
tintFlag = 0; 		 % don't tint object by default
tintVals = [1 1 1];  	% don't tint object by default

% Default position in middle of background
if ~exist('pos','var') | isempty(pos)
	pos = [size(backgnd,1)/2  size(backgnd,2)/2];
end

%%%%% Parse the option flags
if ~isempty(varargin)
	for i = 1:length(varargin)
		if ischar(varargin{i})
			switch lower(varargin{i})
			case 'crop'
				cropCol = varargin{i+1};
				if ischar(cropCol) & isequal(cropCol,'corner');
					% grab the background color to crop out
					% from the corner of the image
					cropCol = obj(1:5,1:5,1);
				end
			case 'tint'
				tintFlag = 1;
				tintVals = varargin{i+1};
			end
		end
	end
end

xrng = [pos(1)-size(obj,1)/2:pos(1)+size(obj,1)/2-1];
yrng = [pos(2)-size(obj,2)/2:pos(2)+size(obj,2)/2-1];
xrng = xrng(xrng>=0 & xrng<=size(backgnd,1));
yrng = yrng(yrng>=0 & yrng<=size(backgnd,1));
img = backgnd;

for z = 1:colDepthBg
	rect = backgnd(xrng,yrng,z);
	tmpObj = double(obj(:,:,z));
	crop = find(~ismember(tmpObj,cropCol));
	tmpObj(crop) = tintVals(z) * (tmpObj(crop));
	tmpObj = uint8(tmpObj);
	rect(crop) = tmpObj(crop);
	img(xrng,yrng,z) = rect;
end

return
