%author : Gael Forget
%date :	Oct 31rst 2005
%object : non linear colormap, with associated colorbar
%inputs : 	-vecval = [a1 a2 ... aN], each interval [aI aI+1]
%			will be associated with a color
%		-colormap_name (e.g. 'jet') 
%output : 	-bbb, the colorbar handle
function [bbb]=gael_cbar3(vecval,colormap_name);

%remark1 : to renew a colorbar generated with this routine,
%	first delete it manually ... delete(bbb);
%remark2 : because this routine regenerates the colormap, 
%	keeping the parameters (vecval,colormap_name) 
%	constant between subplots is safer 
%remark3 : the (hard coded) choices were to not modify the parent 
%	axes position, and to put the colorbar axes on its right. 
%	... It might happen that labels go out of the paper : 
%	change the code below for the colorbar axes properties, 
%	or change the parent axes position. 
%remark4 : the parameter nb_colors must increase with the 
%	non linearity of the color scale, e.g. 
%	[[0:0.5:4] [5:10] [20 30 50 100 500]];

%vecval must be strickly increasing : 
tmp1=vecval(2:end)-vecval(1:end-1);
if ~isempty(find(tmp1<=0)); fprintf('please use increasing values \n'); 
bbb=-1; return; end;

%original colormap precision :
%nb_colors=64*3;
tmp1=min(vecval(2:end)-vecval(1:end-1));
tmp2=vecval(end)-vecval(1);
tmp3=ceil(tmp2/tmp1/64);
nb_colors=64*10*tmp3;
%nb_colors=64*500*tmp3;

%colormap and caxis : 
eval(['tmp_map=colormap(' colormap_name  '(nb_colors));']);
tmp_val=[vecval(1) vecval(end)];
tmp_val=[tmp_val(1) : (tmp_val(2)-tmp_val(1))/(nb_colors-1) : tmp_val(2)];
caxis([tmp_val(1) tmp_val(end)]);

%subset of colours :
tmp_colors=round( [1:length(vecval)-1] * nb_colors/(length(vecval)-1) );
tmp_colors(1)=1; tmp_colors(end)=nb_colors;
tmp_colors=tmp_map(tmp_colors,:);

%final colormap :
tmp_map2=tmp_map;
for kkk=1:nb_colors
tmp1=min(find(vecval>=tmp_val(kkk)));
if isempty(tmp1)
tmp_map2(kkk,:)=tmp_colors(end,:);
elseif tmp1==1
tmp_map2(kkk,:)=tmp_colors(1,:);
elseif tmp1==length(vecval)
tmp_map2(kkk,:)=tmp_colors(end,:);
else
tmp_map2(kkk,:)=tmp_colors(tmp1-1,:);
end
end
colormap(tmp_map2);

%colorbar :
aaa=gca;
tmp1=get(aaa,'Position'); tmp1=[sum(tmp1([1 3]))+0.01 tmp1(2) 0.03 tmp1(4)];
bbb=axes('position',tmp1);

tmp1=[1:2]'*ones(1,length(vecval));
tmp2=[1:length(vecval)]; tmp2=[tmp2;tmp2];
tmp3=[0.5*( vecval(2:end)+vecval(1:end-1) ) vecval(end)]; tmp3=[tmp3;tmp3];

pcolor(tmp1,tmp2,tmp3); caxis([vecval(1) vecval(end)]);
set(bbb,'YAxisLocation','right');
set(bbb,'XTick',[]);
set(bbb,'YTick',[1:length(vecval)]);
set(bbb,'YTickLabel',num2str(vecval'));

axes(aaa);
