%function result = viewMap(whichMap,forceReload = 0)
function viewMap(whichMap,forceReload)
	global mapData, global mapColor, global mapInfo, global origin
	global lastMap, global mission, global lastName

% check arguments
if nargin == 0,
	help viewMap
	return
elseif nargin == 1,
	forceReload = 0;
end

% check reload
chartName = '';
reload = forceReload | isempty(mapData);
if ~reload, reload = ~strcmp(whichMap,lastMap); end
if ~isempty(mission) & isfield(mission{1},'chart'),
	chartName = getfield(mission{1},'chart');
	if ~isstr(chartName), chartName = int2str(chartName); end
	if ~reload, reload = ~strcmp(chartName,lastName); end
end

% get file name
if reload,
	[mapName,chartName] = getMapFile(chartName,whichMap);
	if mapName == 0,
		mapData = [];
		lastMap = [];
		h = findobj('Tag','chart_checkbox');
		if ~isempty(h), set(h,'Value',0); end
		return,
	end
	if ~isempty(mission),
		chartName = strtok(chartName,'gu.');
		mission{1} = setfield(mission{1},'chart',chartName);
	end
end

% assign last map
lastMap = whichMap;
lastName = chartName;

% plot map
try,
	pause(0.1), set(gcbf,'Pointer','watch')
	
	if reload,
		mapData = [];
		[mapData,mapColor] = imread(mapName,'tif');
		mapInfo = load([mapName 'w']);
	end
	
	sz = size(mapData);
	X = mapInfo(5) + (1:sz(2))*mapInfo(1);
	Y = fliplr(mapInfo(6) + (sz(1):-1:1)*mapInfo(4));
	
	if ~isempty(origin) & strcmp(whichMap,'utm'),
		X = X - origin(1);
		Y = Y - origin(2);
	end

	image(X,Y,mapData)
	colormap(mapColor)
	axis xy
	hold on
	h = colorbar;
	delete(h)
	
catch, errorbox('viewMap failed'), end

set(gcbf,'Pointer','arrow')


%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [mapName,fname] = getMapFile(chartName,whichMap)
	global chartPathName
mapName = 0;
fname = [];
if isempty(chartName) | ~length(chartName), chartName = '*'; end
try,
	if strcmp(whichMap,'geo'),
		filterSpec{1,1} = [chartName 'g.tif'];
	else
		filterSpec{1,1} = [chartName 'u.tif'];
	end
	
	% check for match
	d = dir([chartPathName filterSpec{1,1}]);
	if length(d) == 1,
		mapName = [chartPathName filterSpec{1,1}];
		fname = filterSpec{1,1};
		return
	end
	
	% otherwise open file dialog
	filterSpec{1,2} = 'Maptech TIFF Chart';
	curdir = [];
	if ~isempty(chartPathName) & isstr(chartPathName),
		curdir = pwd;
		cd(chartPathName)
	end
	str = ['Select Nautical Chart: ' chartName];
	[fname,chartPathName] = uigetfile(filterSpec,str);
	mapName = [chartPathName fname];
	if ~isempty(curdir) & ~strcmp(curdir,pwd),
		cd(curdir)
	end
catch, errorbox, end