% brsResize
%
% Takes in an arbitrary-sized image and scales/crops it to fit on the
% Brightside HDR display.  Used by brsEnc.
%
% Usage:
%
% result_image = hdrResize(image,[output size]);
%

function result_image = hdrResize(image,output_size);

    siz(1) = size(image,1);
    siz(2) = size(image,2);
    image = double(image);

    if siz ~= output_size
        newsiz = output_size;
        % Adjust size so that the image proportion is maintained
        if (newsiz(1)/newsiz(2) > siz(1)/siz(2))
            newsiz(1) = round(siz(1)/siz(2) * newsiz(2));
        elseif (newsiz(1)/newsiz(2) < siz(1)/siz(2))
            newsiz(2) = round(siz(2)/siz(1) * newsiz(1));
        end

        % Do a resize with a gaussian filter of radius 0.6 (relative to
        % output resolution) when downsampling
        if (newsiz(1) < siz(1))
            gausswidth = 0.6 / newsiz(1) * siz(1);
            resized = imresize(image, newsiz, 'bilinear', fspecial('gaussian',floor(gausswidth*5)*2+1,gausswidth));
        else
            resized = imresize(image, newsiz, 'bilinear');
        end
        % Crop/pad result to match output resolution
        if newsiz(2) > output_size(2)
            cropwidthl = floor( (newsiz(2) - output_size(2))/2 );
            cropwidthr = ceil( (newsiz(2) - output_size(2))/2 );
            resized = resized(:,cropwidthl:end-cropwidthr,:);
        elseif newsiz(2) < output_size(2)
            padwidthl = ceil( (output_size(2) - newsiz(2))/2 );
            padwidthr = floor( (output_size(2) - newsiz(2))/2 );
            resized = [zeros(newsiz(1),padwidthl,3), resized, zeros(newsiz(1),padwidthr,3)];
        end
        if newsiz(1) > output_size(1)
            cropwidtht = floor( (newsiz(1) - output_size(1))/2 );
            cropwidthb = ceil( (newsiz(1) - output_size(1))/2 );
            resized = resized(cropwidtht:end-cropwidthb,:,:);
        elseif newsiz(1) < output_size(1)
            padwidtht = floor( (output_size(1) - newsiz(1))/2 );
            padwidthb = ceil( (output_size(1) - newsiz(1))/2 );
            resized = [zeros(padwidtht, output_size(2),3); resized; zeros(padwidthb, output_size(2),3)];
        end
    else
        resized = image;
    end

    result_image = resized;
end