function varargout = to_pos(deg, islat, varargin)
%------------------------------------------------------------------
% NAME
%
%   to_pos - Convert a position in decimal degrees to a specified
%            format
%
% SYNOPSIS
%
%   str = to_pos(deg, islat, fmt)
%   [id, rm] = to_pos(deg, islat)
%   [id, im, rs] = to_pos(deg, islat)
%
% PARAMETERS
%
%   deg
%      Decimal degrees.
%
%   fmt
%      String specifying the output format. Possible values are:
%
%         'dm'
%         'dms'
%         'dmsh'
%   
%   islat
%      If non-zero, current degrees specify a latitude, else a longitude is
%      assumed.
%
% RETURNS
%
%   str
%      Position in form of a string.
%
%   id 
%      Integer degree
%
%   im
%      Integer minutes
%
%   rm
%      Real minutes
%
%   rs
%      Real seconds
%
%------------------------------------------------------------------

%--- Get the hemisphere:
if islat,
	hemi = repmat('N', size(deg,1), size(deg,2));
	ii = find(deg < 0);
	if length(ii) > 0,
		hemi(ii) = 'S';
	end
else
	hemi = repmat('E', size(deg,1), size(deg,2));
	ii = find(deg < 0);
	if length(ii) > 0,
		hemi(ii) = 'W';
	end
end	

%--- Calculate integer and real components:
id = fix(deg);
rm = (deg - id) .* 60.0;
im = fix(rm);
rs = (rm - im) .* 60.0;

%--- Return Value:
switch nargout
	case 3,
		varargout{1} = id;
		varargout{2} = im;
		varargout{3} = rs;
	case 2,
		varargout{1} = id;
		varargout{2} = rm;
	otherwise,
		if nargin < 1,
			error('Need an output format');
		end
		fmt = varargin{1};
		switch fmt
			case 'dm',
				if islat,
					varargout{1} = sprintf('%02d %07.4f %c', abs(id), abs(rm), hemi);
				else
					varargout{1} = sprintf('%03d %07.4f %c', abs(id), abs(rm), hemi);
				end		
			case 'dms',
				if islat,
					varargout{1} = sprintf('%02d %02d %02d %c', ...
							abs(id), abs(im), abs(is), hemi);
				else
					varargout{1} = sprintf('%03d %02d %02d %c', ...
							abs(id), abs(im), abs(is), hemi);
				end		
			case 'dmsh',
				if islat,
					varargout{1} = sprintf('%02d %02d %05.2f %c', ...
							abs(id), abs(im), abs(rs), hemi);
				else
					varargout{1} = sprintf('%03d %02d %05.2f %c', ...
							abs(id), abs(im), abs(rs), hemi);
				end		
		end
end






