function applyoptions(md,data,options)
%APPLYOPTIONS - apply the options to current plot
%
%   Usage:
%      applyoptions(md,data,options)
%
%   See also: PLOTMODEL, PARSE_OPTIONS
		

%some defaults
if strcmpi(md.mesh.hemisphere,'n'), options=addfielddefault(options,'hemisphere','n'); 
elseif strcmpi(md.mesh.hemisphere,'s'), options=addfielddefault(options,'hemisphere','s'); 
end

%fontsize
fontsize=getfieldvalue(options,'fontsize',14);

%fontweight
fontweight=getfieldvalue(options,'fontweight','normal');

%title
if exist(options,'title')
	titlevalue=getfieldvalue(options,'title');
	if iscell(titlevalue),
		title(titlevalue,'FontSize',fontsize,'FontWeight',fontweight);
	else
		if ~isnan(titlevalue),
			title(titlevalue,'FontSize',fontsize,'FontWeight',fontweight);
		end
	end
end

%xlabel
if exist(options,'xlabel');
	xlabel(getfieldvalue(options,'xlabel'),'FontSize',fontsize,'FontWeight',fontweight);
end

%ylabel
if exist(options,'ylabel');
	ylabel(getfieldvalue(options,'ylabel'),'FontSize',fontsize,'FontWeight',fontweight);
end

%zlabel
if exist(options,'zlabel');
	zlabel(getfieldvalue(options,'zlabel'),'FontSize',fontsize,'FontWeight',fontweight);
end

%xtikcs
if exist(options,'xtick'), set(gca,'XTick',getfieldvalue(options,'xtick')); end
if exist(options,'ytick'), set(gca,'YTick',getfieldvalue(options,'ytick')); end
if exist(options,'ztick'), set(gca,'ZTick',getfieldvalue(options,'ztick')); end

%view 
if md.mesh.dimension==3 & ~exist(options,'layer'),
	view(getfieldvalue(options,'view',3));
else
	view(getfieldvalue(options,'view',2));
end

%axis
set(gca,'FontSize',getfieldvalue(options,'axisfontsize',fontsize));;
if exist(options,'axis')
	eval(['axis ' getfieldvalue(options,'axis')]);
else
	if ((md.mesh.dimension==2) | exist(options,'layer')),
		axis tight equal;
	else
		axis auto tight
	end
end

%box
if exist(options,'box')
	eval(['box ' getfieldvalue(options,'box')]);
end

%xlim
if exist(options,'xlim');
	xlim(getfieldvalue(options,'xlim'));
end

%ylim
if exist(options,'ylim');
	ylim(getfieldvalue(options,'ylim'));
end

%latlon
%Must be done here (before xlim and ylim??) so that it uses the same xlim and ylim as plot_overlay
%these are changed by axis that follows
if ~strcmpi(getfieldvalue(options,'latlon','off'),'off')
	latlonoverlay(md,options);
end


%zlim
if exist(options,'zlim');
	zlim(getfieldvalue(options,'zlim'));
end

%Basinzoom
if exist(options,'basin');
	basinzoom(options);
end

%ShowBasins
if strcmpi(getfieldvalue(options,'showbasins','off'),'on')
	showbasins(options);
end


%Caxis
if exist(options,'caxis'),
	caxis(getfieldvalue(options,'caxis'));
end

%shading
if exist(options,'shading'),
	shading(getfieldvalue(options,'shading'));
end

%grid
if exist(options,'grid'),
	if strcmpi(getfieldvalue(options,'grid'),'on'),
		grid on;
	end
end

%colormap
if exist(options,'colormap'),
	cname=getfieldvalue(options,'colormap');
	if strcmpi(cname,'Ala'),
		c = jet(64);
		c = c (32:end,:);
	elseif strcmpi(cname,'redblue'),
		%m = 30;
		%n = fix(0.5*m);
		%r = [(0:1:n-1)/n,ones(1,n)];
		%g = [(0:n-1)/n, (n-1:-1:0)/n];
		%b = [ones(1,n),(n-1:-1:0)/n];
		%c = [r(:), g(:), b(:)]; 

		c = hsv(64);
		c = rgb2hsv(c);
		c(:,2) = max(min( abs(c(:,1)-0.5)/0.5 ,1),0);
		c(1:32,1)   = 0.7;
		c(33:end,1) = 1;
		c = hsv2rgb(c);

	elseif strcmpi(cname,'Rignot'),
		c = hsv;

		%adjust saturation
		c = rgb2hsv(c);
		alpha=getfieldvalue(options,'alpha',1);
		c(:,2) = max(min( (0.1+c(:,1)).^(1/alpha) ,1),0);
		c = hsv2rgb(c);

	elseif strcmpi(cname,'Rignot2'),
		c = hsv;

		%adjust saturation
		c = rgb2hsv(c);
		alpha=getfieldvalue(options,'alpha',1);
		c(:,2) = max(min( (0.1+c(:,1)).^(1/alpha) ,1),0);
		c = hsv2rgb(c);

		c=flipud(c);

	elseif strcmpi(cname,'damage'),
		c=hsv(64);
		c(:,3)=1;
		a=1:-(1/35):0.1;
		c(1:32,2)=a;
		c(33:end,2)=fliplr(a);
		c(1:32,1)=2/3;
		c(33:end,1)=0.07;
		c=hsv2rgb(c);

	else
		c = cname;
	end
	h=colormap(c);
else
	h=colormap(jet(60));
end

%wrapping
if exist(options,'wrapping'),
	if ~exist(options,'colormap'),
		h=jet;
	end
	colormap(repmat(h,getfieldvalue(options,'wrapping',1),1));
end

%colorbar
if getfieldvalue(options,'colorbar',1)==1,
	if exist(options,'colorbarcornerposition'),
		c=colorbar(getfieldvalue(options,'colorbarcornerposition'),'peer',gca);
	else 
		c=colorbar('peer',gca);
	end
	set(c,'FontSize',getfieldvalue(options,'colorbarfontsize',fontsize),'YColor',getfieldvalue(options,'FontColor','k'));
	if exist(options,'wrapping')
		lim=get(c,'Ylim');
		lim=[lim(1) lim(1)+(lim(2)-lim(1))/getfieldvalue(options,'wrapping')];
		set(c,'Ylim',lim);
	end
	if exist(options,'colorbarpos'),
		set(c,'Position',getfieldvalue(options,'colorbarpos'));
	end
	if exist(options,'log'),
		nlab=5;
		logvalue=getfieldvalue(options,'log');

		scaleminmax=caxis;
		Min=min(scaleminmax);
		Max=max(scaleminmax);
		set(c,'YLim',[Min Max]); % set colorbar limits
		set(c,'YTick',linspace(Min,Max,nlab));     % set tick mark locations

		labels = cell(1,nlab);
		tick_vals = linspace(Min,Max,nlab);
		tick_vals = exp(log(logvalue)*tick_vals);
		warning off MATLAB:log:logOfZero;
		for i = 1:nlab
			labels{i} = sprintf('%-3.4g',round_ice(tick_vals(i),2));
			%labels{i} = sprintf('%-.4g',round_ice(tick_vals(i),2));
		end
		warning on MATLAB:log:logOfZero;
		set(c,'YTickLabel',labels);
	end 
 	if exist(options,'cbYLim'); 
		set(c,'YLim',getfieldvalue(options,'cbYLim'));
	end
	if exist(options,'colorbartitle'),
		set(get(c,'title'),'FontSize',getfieldvalue(options,'colorbarfontsize',fontsize),'String',getfieldvalue(options,'colorbartitle'),...
			'Color',getfieldvalue(options,'FontColor','k'));
	end
	if exist(options,'colorbarYLabel'),
		set(get(c,'Ylabel'),'FontSize',getfieldvalue(options,'colorbarfontsize',fontsize),'String',getfieldvalue(options,'colorbarYLabel'),...
			'Color',getfieldvalue(options,'FontColor','k'),'Interpreter',getfieldvalue(options,'Interpreter','none'));
	end
	if exist(options,'colorbarwidth'),
		posaxes=get(gca,'Position');
		alpha=getfieldvalue(options,'colorbarwidth',1);
		position=get(c,'Position');
		dx=position(3);
		newdx=dx*alpha;
		position(1)=position(1)+(dx-newdx)/2;
		position(3)=newdx;
		set(c,'Position',position);
		set(gca,'Position',posaxes);
	end
	if exist(options,'colorbarheight'),
		posaxes=get(gca,'Position');
		alpha=getfieldvalue(options,'colorbarheight',1);
		position=get(c,'Position');
		dy=position(4);
		newdy=dy*alpha;
		position(2)=position(2)+(dy-newdy)/2;
		position(4)=newdy;
		set(c,'Position',position);
		set(gca,'Position',posaxes);
	end


elseif getfieldvalue(options,'colorbar',1)==0,
	colorbar('off');
else
	%do nothing
	
end


%area
if exist(options,'area'),
	antzoom(getfieldvalue(options,'area'));
end

%expdisp
filename=(getfieldvalue(options,'expdisp'));
style=(getfieldvalue(options,'expstyle'));
for i=1:length(getfieldvalue(options,'expdisp')),
	filenamei=filename{i};
	stylei=style{i};
	expdisp(filenamei,gcf,stylei,getfieldvalue(options,'linewidth',1),getfieldvalue(options,'unit',1));
end

%text (default value is empty, not NaN...)
if exist(options,'text');
	textstring=getfieldvalue(options,'text');
	textweight=getfieldvalue(options,'textweight','b');
	textsize=getfieldvalue(options,'textsize');
	textcolor=getfieldvalue(options,'textcolor');
	textposition=getfieldvalue(options,'textposition');
	textrotation=getfieldvalue(options,'textrotation');
	for i=1:length(getfieldvalue(options,'text'));
		textstringi=textstring{i};
		textweighti=textweight{i};
		textsizei=textsize{i};
		textcolori=textcolor{i};
		textpositioni=textposition{i};
		textrotationi=textrotation{i};
		h=text(textpositioni(1),textpositioni(2),textstringi,'FontSize',textsizei,'FontWeight',textweighti,'Color',textcolori,'Rotation',textrotationi);
		set(h,'Clipping','on'); %prevent text from appearing outside of the box
	end
end

%north arrow
if exist(options,'northarrow'),
	northarrow(getfieldvalue(options,'northarrow'));
end

%Scale ruler
if exist(options,'scaleruler'),
	scaleruler(options);
end

%streamliness
if exist(options,'streamlines'),
	plot_streamlines(md,options);
end

%contours
if exist(options,'contourlevels'),
	plot_contour(md,data,options);
end

%YTickLabel
if exist(options,'yticklabel'),
	set(gca,'YTickLabel',getfieldvalue(options,'YTickLabel'));
end

%XTickLabel
if exist(options,'xticklabel'),
	set(gca,'XTickLabel',getfieldvalue(options,'XTickLabel'));
end

%xtick
if exist(options,'xtick'),
	set(gca,'xtick',getfieldvalue(options,'xtick'));
end

%ytick
if exist(options,'ytick'),
	set(gca,'ytick',getfieldvalue(options,'ytick'));
end

%Axis positions
if exist(options,'offsetaxispos'),
	offset=getfieldvalue(options,'offsetaxispos');
	P=get(gca,'pos');
	P(1)=P(1)+offset(1);
	P(2)=P(2)+offset(2);
	P(3)=P(3)+offset(3);
	P(3)=P(4)+offset(4);
	set(gca,'pos',P);
end
if exist(options,'axispos'),
	Axis=getfieldvalue(options,'axispos');
	set(gca,'pos',Axis);
end


%position of figure
if exist(options,'figposition'),
	
	figposition=getfieldvalue(options,'figposition');
	if ischar(figposition),
		if strcmpi(figposition,'larour'),
			set(gcf,'Position',[1604 4 1594 1177]);
		elseif strcmpi(figposition,'larour2'),
			set(gcf,'Position',[756    62   827   504]);
		elseif strcmpi(figposition,'mathieu'),
			set(gcf,'Position',[300 1 1580 1150]);
		elseif strcmpi(figposition,'fullscreen'),
			set(gcf,'Position',get(0,'ScreenSize'));
		elseif strcmpi(figposition,'halfright'),
			screen=get(0,'ScreenSize');
			left=screen(1); bott=screen(2); widt=screen(3); heig=screen(4)-25;
			set(gcf,'Position',fix([left+widt/2 bott widt/2 heig]));
		elseif strcmpi(figposition,'halfleft'),
			screen=get(0,'ScreenSize');
			left=screen(1); bott=screen(2); widt=screen(3); heig=screen(4)-25;
			set(gcf,'Position',fix([left bott widt/2 heig]));
		elseif strcmpi(figposition,'portrait'),
			%reformat with letter paper size (8.5" x 11")
			screen=get(0,'ScreenSize');
			left=screen(1); bott=screen(2); widt=screen(3); heig=screen(4)-25;
			portrait=fix([left+widt-(heig*8.5/11) bott heig*8.5/11 heig]);
			set(gcf,'Position',portrait)
		elseif strcmpi(figposition,'landscape'),
			%reformat with letter paper size (8.5" x 11")
			screen=get(0,'ScreenSize');
			left=screen(1); bott=screen(2); widt=screen(3); heig=screen(4)-25;
			landscape=fix([left+widt-(heig*11/8.5) bott heig*11/8.5 heig]);
			set(gcf,'Position',landscape)
		else
			disp('''figposition'' string not supported yet');
		end
	else
		set(gcf,'Position',figposition);
	end

end

%axes position
if exist(options,'axesPosition')
	set(gca,'Position',getfieldvalue(options,'axesPosition'));
end

%showregion
if strcmpi(getfieldvalue(options,'showregion','off'),'on'),
	%Keep pointer of main axis
	maingca=gca;
	%get inset relative position (x,y,width,height)
	insetpos=getfieldvalue(options,'insetpos',[0.02 0.70 0.18 0.18]);
	%get current plos position
	cplotpos=get(maingca,'pos');
	%compute inset position
	PosInset=[cplotpos(1)+insetpos(1)*cplotpos(3),cplotpos(2)+insetpos(2)*cplotpos(4), insetpos(3)*cplotpos(3), insetpos(4)*cplotpos(4)];
	axes('pos',PosInset);
	axis equal off
	%box off
	if strcmpi(md.mesh.hemisphere,'n') | strcmpi(md.mesh.hemisphere,'north'),
		A=expread([ issmdir() '/projects/Exp/GreenlandBoxFront.exp']);
		[A.x A.y]=ll2xy(A.x,A.y,+1,45,70);
	elseif strcmpi(md.mesh.hemisphere,'s') | strcmpi(md.mesh.hemisphere,'south'),
		A=expread([ issmdir() '/projects/Exp/Antarctica.exp']);
	else
		error('applyoptions error message: hemisphere not defined');
	end
	Ax=[min(A.x) max(A.x)];
	Ay=[min(A.y) max(A.y)];
	%if we are zooming on a basin, don't take the mesh for the boundaries!
	if exist(options,'basin'),
		[mdx mdy]=basinzoom(options);
	else
		offset=3*10^4;
		mdx=[min(md.mesh.x)-offset max(md.mesh.x)+offset];
		mdy=[min(md.mesh.y)-offset max(md.mesh.y)+offset];
	end
	line(A.x,A.y,ones(size(A.x)),'color','b');
	patch([Ax(1)  Ax(2)  Ax(2)  Ax(1) Ax(1)],[Ay(1)  Ay(1)  Ay(2)  Ay(2) Ay(1)],[1 1 1],'EdgeColor',[0 0 0],'LineWidth',1,'FaceLighting','none')
	patch( [mdx(1) mdx(2) mdx(2) mdx(1)],[mdy(1) mdy(1) mdy(2) mdy(2)],ones(4,1),'EdgeColor',[0 0 0],'FaceColor','r','FaceAlpha',0.5)
	colorbar('off');
	%back to main gca
	set(gcf,'CurrentAxes',maingca)
end

%flag edges of a partition
if exist(options,'partitionedges')
[xsegments ysegments]=flagedges(md.mesh.elements,md.mesh.x,md.mesh.y,md.qmu.partition);
xsegments=xsegments*getfieldvalue(options,'unit',1);
ysegments=ysegments*getfieldvalue(options,'unit',1);
color=getfieldvalue(options,'partitionedgescolor','r-');
linewidth=getfieldvalue(options,'linewidth',1);
hold on;
for i=1:length(xsegments),
	plot(xsegments(i,:),ysegments(i,:),color,'LineWidth',linewidth);
end
end

%backgroundcolor
set(gca,'color',getfieldvalue(options,'backgroundcolor','none'));

%figurebackgrounbcolor
set(gcf,'color',getfieldvalue(options,'figurebackgroundcolor','w'));

%lighting
if strcmpi(getfieldvalue(options,'light','off'),'on'),
	set(gca,'FaceLighting','gouraud','FaceColor','interp','AmbientStrength',0.5);
	light('Position',[0 0.1 0.1],'Style','infinite');
end

%cloud of points: 
if exist(options,'cloud'),
	field=getfieldvalue(options,'cloud');
	x=field(:,1);
	y=field(:,2);
	%unit multiplier:
	if exist(options,'unit'),
		unit=getfieldvalue(options,'unit');
		x=x*unit;
		y=y*unit;
	end
	hold on,p=plot(x,y,'k.');
	markersize=getfieldvalue(options,'markersize',5);
	color=getfieldvalue(options,'cloudcolor','k');
	set(p,'Color',color);
end

%========================%
%OK VERY LAST STEP: INSET|
%========================%
if exist(options,'inset'),

	%Keep pointer of main axis
	maingca=gca;
	%get inset relative position (x,y,width,height)
	insetpos=getfieldvalue(options,'insetpos',[0.56 0.55 0.35 0.35]);
	%get current plot position
	cplotpos=get(gca,'pos');
	%compute inset position
	PosInset=[cplotpos(1)+insetpos(1)*cplotpos(3),cplotpos(2)+insetpos(2)*cplotpos(4), insetpos(3)*cplotpos(3), insetpos(4)*cplotpos(4)];
	%show pos
	X1=getfieldvalue(options,'insetx',xlim);
	Y1=getfieldvalue(options,'insety',ylim);
	if strcmpi(getfieldvalue(options,'showinset','off'),'on')
		line(X1([1 2 2 1 1]),Y1([1 1 2 2 1]),zeros(1,5),'Color','k','LineWidth',2);
	end

	%Get current figure
	ax1=gca;

	%plot inset
	axes('pos',PosInset);
	copyobj(get(ax1,'children'),gca);
	patch('Faces',[1 2 3 4 1],'Vertices',[X1([1 2 2 1])' Y1([1 1 2 2])'],'FaceColor','None','EdgeColor','k','LineWidth',2);

	%applay options
	options=removefield(options,'text',0);
	options=removefield(options,'title',0);
	options=removefield(options,'xlabel',0);
	options=removefield(options,'ylabel',0);
	options=removefield(options,'inset',0);
	options=removefield(options,'offsetaxispos',0);
	options=removefield(options,'showregion',0);
	options=changefieldvalue(options,'colorbar',0);
	options=changefieldvalue(options,'latlon','off');
	options=changefieldvalue(options,'axis','equal off');
	options=changefieldvalue(options,'xlim',getfieldvalue(options,'insetx',xlim));
	options=changefieldvalue(options,'ylim',getfieldvalue(options,'insety',ylim));
	applyoptions(md,data,options);

	%back to main gca
	set(gcf,'CurrentAxes',maingca)
end
