function sel = selectFromList(list, zopt)
% selectFromList(list) is called with a cell list (list) of strings. It
% generates a propper output of items to select and calls for a user input
% of a number to select an entry.
%
% sel = selectFromList(list, zero_option) returns the user input or '-1',
% if an error occured.
%
% selectFromList(list, zero_option) provides an additional string for an
% option assigned to the user input '0'. This is usually a 'back' or 'exit'
% action.

% find maximum stringlength in list
strlen(1:length(list)) = 0;
for i = 1:length(list)
    strlen(i) = length(list{i});
end
maxlen = max(strlen);
items = length(list);

% calculate dimension
x_dim = ceil(75/(2+5+maxlen)) - 1;
if items <= 9
    x_dim = 1;
end
y_dim = ceil(items/x_dim);

% reshape list
if y_dim*x_dim > items
    for i = (items+1):(y_dim*x_dim)
        list{i} = '';
    end
end
list = reshape(list, [y_dim, x_dim]);

% display loop
for row = 1:y_dim
    outline = '';
    for col = 1:x_dim
        index = row + (col-1)*y_dim;
        if index <= items
            if index <= 9
                outline = [outline '  ( '];
            else
                outline = [outline '  ('];
            end
            outline = [outline num2str(index) ') ' list{row,col}];
            if strlen(index) < maxlen
                addspace = [];
                addspace(1:(maxlen-strlen(index))) = ' ';
                outline = [outline addspace];
            end
        end
    end
    disp(outline);
end
if exist('zopt', 'var');
    disp(['  ( 0) ' zopt]);
end

%% get input and ensure it is a proper input
sel = [];
while isempty(sel) || ~isnumeric(sel) || max(size(sel)) ~= 1 || ...
    mod(sel, 1) ~= 0 || sel < ~exist('zopt', 'var') || sel > items
    try
      sel = input('  Input: ');
    catch thisError
        warning(thisError.message)
        sel = [];
    end
end
