function haxx=splitaxes(hax,sep,num,orient)
% function haxx=splitaxes(hax,separation,number,orient)
% split axes and return the new handle (old handle still valid)
% sep: distance between axes
% number: number of axes to split in
% orient: 'h' or 'v' for orientation of splitting

if ~any(strcmp(orient,{'h','v'}))
    error('invalid orientation')
end

if numel(hax)==1
    pp=get(hax,'position');
    pos1 = pp(1);
    pos2 = pp(2);
    wtot = pp(3);
    htot = pp(4);
else % span area of multiple axes
    pos1=1; pos2=1;
    pos3=0; pos4=0;
    for ii=1:numel(hax);
        pp=get(hax(ii),'position');
        pos1=min(pos1,pp(1)); % most left
        pos2=min(pos2,pp(2)); % most low
        pos3=max(pos3,pp(1)+pp(3)); % most top
        pos4=max(pos4,pp(2)+pp(4)); % most right
    end
    wtot = pos3-pos1;
    htot = pos4-pos2;   
end


if strcmp(orient,'h') % horiz split
    weach = (wtot-(num-1)*sep)/num;
    for ii=1:num
        posnew(ii,:) = [pos1+(ii-1)*(weach+sep),pos2,weach,htot];
        haxx(ii) = axes('position',posnew(ii,:));
    end
else
    heach = (htot-(num-1)*sep)/num;
    for ii=1:num
        posnew(ii,:) = [pos1,pos2+(ii-1)*(heach+sep),wtot,heach];
        haxx(ii) = axes('position',posnew(ii,:));
    end
end
    
delete(hax)

return
