function [utm_zone_struct] = myutmzone(lat,lon);
% USAGE:
%    [utm_zone_struct] = utm_zone(lat,lon);
%    [utm_zone_struct] = utm_zone(zone);
%    [utm_zone_struct] = utm_zone();
%
% utm_zone_struct:
%   .number
%   .letter
%   .lat0
%   .lon0
%
% All input and output lat/lon values are in degrees. 
%
% Copyright 2001 Bluefin Robotics Corp
% Created  02-12-01 by JSW
% Modified 02-19-01 by DAP 

utm_zone_struct = [];

if nargin == 1,
	zone = lat;
	try,
		utm_zone_struct = getStructFromZone(lat);
		return
	catch,
		errorbox('Please enter latitude and longitude or UTM zone.')
		utm_zone_struct = myutmzone;
		return
	end
end

if ~nargin,
	prompt{1} = 'Enter Latitude:';
	prompt{2} = 'and Longitude:';
	prompt{3} = 'or enter UTM Zone:';
	title = 'Please enter latitude and longitude, or UTM zone.';
	answer = inputdlg(prompt,title);
	if isempty(answer), return
	elseif ~isempty(answer{3}),
		try,
			utm_zone_struct = getStructFromZone(answer{3});
			return
		catch,
			errorbox('Please enter latitude and longitude or UTM zone.')
			utm_zone_struct = myutmzone;
			return
		end
	elseif ~isempty(answer{1}) & ~isempty(answer{2}),
		if ischar(answer{1}), answer{1} = str2num(answer{1}); end
		if ischar(answer{2}), answer{2} = str2num(answer{2}); end
		lat = answer{1};
		lon = answer{2};
	else, return
	end
end


utm_zone_struct = struct('number',[],'letter','','lat0',[],'lon0',[]);
number = floor((lon + 180)/6) + 1;
letter = 'CDEFGHJKLMNPQRSTUVWXX';
letter = letter(floor((median(lat) + 80)/8) + 1);
utm_zone_struct.number = number;
utm_zone_struct.letter = letter;

% Calculate the origin latitude
letter_num = utm_zone_struct.letter - 'C';

% 'I' is not a valid UTM zone letter
if letter_num > 8, 
    letter_num = letter_num - 1; 
end; 

% base latitude of UTM zone [deg]
utm_zone_struct.lat0 = (letter_num - 1)*8 - 80;

% central meridian of UTM zone [deg]
utm_zone_struct.lon0 = (-177 + 6*(utm_zone_struct.number - 1));


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function utm_zone_struct = getStructFromZone(zone)
utm_zone_struct = struct('number',[],'letter','','lat0',[],'lon0',[]);
if ~ischar(zone), zone = num2str(zone); end
[latlim,lonlim] = utmzone(zone);
utm_zone_struct.lat0 = mean(latlim);
utm_zone_struct.lon0 = mean(lonlim);
number = [];
foundLetter = 0;
for ii=1:length(zone),
	if isletter(zone(ii)), foundLetter=1; break, end
	number = [number zone(ii)];
end
utm_zone_struct.number = str2num(number);
if foundLetter, utm_zone_struct.letter = zone(ii);
else utm_zone_struct.letter = []; end