function resvec = get_dnnres(stimuli,network)

% resvec = get_dnnres(stimuli,network)
%
% stimuli: cell_array of images
% net: the following options are currently available: 'vgg16','alexnet','resnet50'
%
% n.b.: input stimuli as cell array of images (uint8 or uint16)
% by Martin Hebart 2017


addpath(genpath('/Users/hebartmn/Documents/MATLAB/practical-cnn-2017a/'))

dag = 0;
switch lower(network)
    
    case 'vgg16'
        net = load('/Users/hebartmn/Documents/MATLAB/practical-cnn-2017a/data/imagenet-vgg-verydeep-16.mat');
        % for VGG we want to use the pooling layers
        layers = [5 10 17 24 31 32 34 36]; % pooling layers and fully connected layers
    case 'resnet50'
        net = dagnn.DagNN.loadobj(load('/Users/hebartmn/Documents/MATLAB/practical-cnn-2017a/data/imagenet-resnet-50-dag.mat'));
        net.mode = 'test';
        net.conserveMemory = 0;
        dag = 1;
        layers = [1 15 25 35 47 57 67 77 89 99 109 119 129 139 151 161 171 174]; % these are the convolutional layer 1, the summing layers and the fully connected
    case 'alexnet'    
        net = load('/Users/hebartmn/Documents/MATLAB/practical-cnn-2017a/data/imagenet-caffe-alex.mat');
        layers = [1 5 9 11 13 16 18 20]; % convolutional layers and fully connected layers
    case 'object-dnn'
        net = load('/Users/hebartmn/Documents/MATLAB/practical-cnn-2017a/data/test_simplenn.mat');
        layers = [1 5 9 11 13 16 19 22];
    otherwise
        error('Network not implemented.')
        
end
    



fprintf('\n   ')
for i_image = length(stimuli):-1:1
    
    fprintf('\b\b\b\b%04i',i_image)
    
    im = stimuli{i_image};
    
    im_ = single(im2uint8(im));
    im_ = imresize(im_, net.meta.normalization.imageSize(1:2));
    try
    im_ = bsxfun(@minus,im_,net.meta.normalization.averageImage);
    catch
%         im_ = bsxfun(@minus,im_,128*ones(net.meta.normalization.imageSize(1:3)));
        if i_image == length(stimuli)
            net2 = load('/Users/hebartmn/Documents/MATLAB/practical-cnn-2017a/data/imagenet-caffe-alex.mat');
            warning('could not normalize image - no mean image in network')
        end
        im_ = bsxfun(@minus,im_,net2.meta.normalization.averageImage);
    end
    
    if dag == 0
        res = vl_simplenn(net, im_);
    else
        net.eval({'data', im_});
        res = net.vars;
    end
    
    % to look at structure, we can use vl_simplenn_display(net)
    
    % the first output of res will be the image itself, so we add 1
    res = res(1 + layers);
    
    for i_layer = 1:length(layers)
        if dag == 0
            resvec{i_layer}(:,i_image) = res(i_layer).x(:);
        else
           resvec{i_layer}(:,i_image) = res(i_layer).value(:); 
        end
    end
    
end

fprintf('\ndone.\n')