function minspace(fig,nr,nc,varargin)
%Two possible pairs for varargin: outermargin and innermargin
%outermargin is the normalized space on the edges of the figure space given
%by [left, bottom, right, top]
%innermargin is the normalized space between plots given by [width height]
%This function does not support plots with different final sizes

narg=length(varargin);
om=[1 1 1 1]*0.01;
im=[0 0];
if narg>0
    for i=1:2:narg
        if strcmpi(varargin{i},'outermargin')
            om=varargin{i+1};
        elseif strcmpi(varargin{i},'innermargin')
            im=varargin{i+1};
        end
    end
end           

ch=findobj('parent',fig,'type','axes','tag','');
set(fig,'units','pixel')
fp=get(fig,'position');
set(fig,'units','normalized')   
t=zeros(nr*nc,4);
chmat=zeros(nr,nc);

for i=1:length(ch)
    chpos=single(get(ch(i),'position'));
    chp1(i)=chpos(1);
    chp2(i)=chpos(2);
end
chp1=sort(chp1); %Sometimes the positions in the same row
chp2=sort(chp2); %or column are very slightly different.
chp1=chp1(1:nr:end);
chp2=chp2(1:nc:end);

for i=1:length(ch)
    chpos = single(get(ch(i),'position'));
    if nc==1
        col=1;
    else
        [~,col]=min(abs(chp1-chpos(1)));
    end
    if nr==1
        row=1;
    else
        [~,row]=min(abs(chp2-chpos(2)));
    end
    chmat(row,col)=i; %Determines the row and column position of the axis
    cbextra=[0,0,0,0];
    %Find colorbars and account for their space
%     if isappdata(ch(i),'LegendColorbarOuterList') && ~isempty(getappdata(ch(i),'LegendColorbarOuterList'))
%         cb=find(getappdata(ch(i),'LegendColorbarLayoutSides')); %gives side of plot that colorbar is on
%         s=getappdata(ch(i),'LegendColorbarOuterList');
%         if any(cb==[1,3])
%             cbextra(cb)=(45+s.tightinset(cb)*fp(3))/fp(3); %35-45 pixels accounts for standard colorbar width
%         else
%             cbextra(cb)=(45+s.tightinset(cb)*fp(4))/fp(4);
%         end
%     end

    if isappdata(ch(i),'ColorbarPeerHandle') 
        info=getappdata(ch(i),'ColorbarPeerHandle');
        try
        cbloc=info.Position;
        parentloc = get(ch(i),'position');
        edgesparent = [parentloc(1) parentloc(2) parentloc(1)+parentloc(3) parentloc(2)+parentloc(4)];
        
        if cbloc(3)/parentloc(3)<0.5 && cbloc(1) > edgesparent(3) %located on left side
            cbextra(3) = cbloc(3)*3; % times 3 seems to do the trick  - may need to be adjusted later.
        elseif cbloc(3)/parentloc(3)<0.5 && cbloc(1) < edgesparent(1) %located on right side
            cbextra(1) = cbloc(3)*3;
        elseif cbloc(4)/parentloc(4)<0.5 && cbloc(2) > edgesparent(4) %located on top side
            cbextra(4) = cbloc(4)*3;
        elseif cbloc(4)/parentloc(4)<0.5 && cbloc(2) < edgesparent(2) %located on bottom side
            cbextra(2) = cbloc(4)*3;
        end %If none of these conditions then CB is inside the plot
        catch
        end
        
    end
    t(i,:)=get(ch(i),'tightinset')+cbextra;    
end

%Find the vertical and horizontal spacing between plots
swidth=zeros(nc+1,1);
sheight=zeros(nr+1,1);

swidth(1)=max(t(chmat(:,1),1));
swidth(nc+1)=max(t(chmat(:,nc),3));
sheight(1)=max(t(chmat(1,:),2));
sheight(nr+1)=max(t(chmat(nr,:),4));

if nc>1
    swidth(2:nc)=max(t(chmat(:,1:nc-1),3))+max(t(chmat(:,2:nc),1));
end
if nr>1
    sheight(2:nr)=max(t(chmat(1:nr-1,:),4))+max(t(chmat(2:nr,:),2));  
end

%Total width and height of labels and colorbars and optional margins
totwd=sum(swidth)+sum(om([1,3]))+im(1)*(nc-1);
totht=sum(sheight)+sum(om([2,4]))+im(2)*(nr-1);

%Let excess be used to increase height and width of the plots
p3new=(1-totwd)/nc;  %new plot width
p4new=(1-totht)/nr;  %new plot height

p2new=sheight(1)+om(2); %Starting base height of axis position
for r=1:nr
     p1new=swidth(1)+om(1); %Starting distance of axis position from left side
    for c=1:nc
        set(ch(chmat(r,c)),'position',[p1new,p2new,p3new,p4new])
        if c<nc
            p1new=p1new+p3new+swidth(c+1)+im(1); 
        end
    end
    if r<nr
        p2new=p2new+p4new+sheight(r+1)+im(2);
    end
end

set(fig,'units','pixel')




