%% dgPositions
% row_col = number of elements columns rows (just to be confusing)
% xy_gap = x y gap between elements and also from outside of parent pos
% [xy_pos] = xy points and xy portions for elements to fit within
function pos=positions(row_col,xy_gap,varargin)
% finfo=dbstack;
order='standard'; % left to right, bottom to top
direction='down';
xy_size=(1-(row_col([2 1])+1).*xy_gap)./row_col([2 1]); % gap spacing 1./row_col([2 1])-xy_gap;%
xy_pos=[0 0 1 1]; % full
if ~isempty(varargin)
    for i=1:numel(varargin)
        if isnumeric(varargin{i})
            % make sure the position is okay
            %             if sum(varargin{i}(1:2)<0)
            %                 varargin{i}(varargin{i}(1:2)<0)=0;
            %             end
            if varargin{i}(1)+varargin{i}(3)>1
                varargin{i}(1)=1-varargin{i}(3);
            end
            if varargin{i}(2)+varargin{i}(4)>1
                varargin{i}(2)=1-varargin{i}(4);
            end
            xy_pos=varargin{i};
            
        else
            switch varargin{i}
                case {'standard','opposite'}
                    order=varargin{i};
                case {'down','across'}
                    direction=varargin{i};
            end
        end
    end
end
% if numel(xy_size)==4
%     xy_pos=xy_size(3:4);
%     xy_size=xy_size(1:2);
% end
pos=zeros(row_col(1)*row_col(2),4);
k=0;
rows=row_col(1); % number of y (rows)
cols=row_col(2); % number of x (columns)
% if strcmp(direction,'across')
%     % switch these
%     cols=row_col(1); % number of x (columns)
%     rows=row_col(2); % number of y (rows)
% end
for i=1:cols 
    for j=1:rows 
        k=k+1;
        pos(k,:)=[xy_gap(1)*i+xy_size(1)*(i-1) xy_gap(2)*j+xy_size(2)*(j-1) ...
            xy_size];
%         pos
    end
end
switch order
    case 'opposite'
        if sum(row_col>1)==2
            % flip in parts
            tmp=pos; pos=[];
%             switch direction
%                 case 'down'
                    for i=1:row_col(2) % for each column
                        pos=vertcat(pos,tmp(flipdim(row_col(1)*(i-1)+1:row_col(1)*i,2),:));
                    end
%                 case 'across'
%                     for i=1:row_col(1) % for each row
%                         pos=vertcat(pos,tmp(flipdim(row_col(2)*(i-1)+1:row_col(2)*i,2),:));
%                     end
%             end
        else
            pos=pos(flipdim(1:size(pos,1),2),:);
        end
end

for i=1:size(pos,1)
    pos(i,:)=(pos(i,:).*[xy_pos(3:4) xy_pos(3:4)])+[xy_pos(1:2) 0 0];
end
tmp=pos; pos=[]; k=0;
switch direction
    case 'across'
        for i=1:rows
            for j=1:cols
                k=k+1;
                pos(k,:)=tmp(i+rows*(j-1),:);
            end
        end
end
clear tmp order direction xy_pos xy_size row_col i j k
end