function [dx,dy,oWindow] = CmdWinToUpperLeft(window,clut)
% [dx,dy,oWindow] = CmdWinToUpperLeft(window,[clut])
%
% Bring command window to upper left, buffer screen
% in an offscreen window.  Return dx,dy necessary to
% restore command window to old position. Set "clut" if specified.
%
% See also SCREENWinToFront.
%
% BUG:  Student Matlab sometimes hangs up in the call to Screen('MoveWindow'), as though the
% pause(0) command that's in the C code implementing 'MoveWindow' resulted in an indefinite
% pause. The program continues if you hit command-period, even though command-period is 
% supposed to always cause a break.

% 3/5/97  	dhb		Wrote it.
% 10/15/97 	dhb		Add sideBarOffset
% 1/12/98 	dgp		Note bug related to Student Matlab and 'MoveWindow'.

% Optionally save the window content.
if nargout>2
	whichScreen = Screen(window,'WindowScreenNumber');
	oWindow = Screen(whichScreen,'OpenOffscreenWindow');
	Screen('CopyWindow',window,oWindow);
end

% Bring command window to front and offset it to upper left.
menuBarOffset = 20;
titleBarOffset = 18;
sideBarOffset = 18;
globalScreenRect = Screen(window,'GlobalRect');
cWindow = Screen('GetMatlabWindow');
globalCommandRect = Screen(cWindow,'GlobalRect');
dx = globalScreenRect(RectLeft) - globalCommandRect(RectLeft) + sideBarOffset;
dy = globalScreenRect(RectTop) - globalCommandRect(RectTop) + menuBarOffset + titleBarOffset;
Screen(cWindow,'MoveWindow',dx,dy);
Screen(cWindow,'WindowToFront');
if nargin>1
	Screen(window,'SetClut',clut);
end
