% hdrResize
%
% Takes in an arbitrary-sized image and scales/crops it to fit on the
% Brightside HDR display.  Used by hdrEnc, and useful for creating 'ideal'
% comparison images to the images produced by the hdrEnc->hdrSimulate
% chain.
%
% Usage:
%
% result_image = hdrResize(image,[magnification factor]);
%

function result_image = hdrResize(image,varargin);

    dstsiz = [1024 1280];
    sca=1;
    
    if (length(varargin) == 1)
        sca = varargin{1};
    end

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

    if siz ~= dstsiz
        newsiz = sca*dstsiz;

        % 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) > dstsiz(2)
            cropwidthl = floor( (newsiz(2) - dstsiz(2))/2 );
            cropwidthr = ceil( (newsiz(2) - dstsiz(2))/2 );
            resized = resized(:,cropwidthl:end-cropwidthr,:);
        elseif newsiz(2) < dstsiz(2)
            padwidthl = ceil( (dstsiz(2) - newsiz(2))/2 );
            padwidthr = floor( (dstsiz(2) - newsiz(2))/2 );
            resized = [zeros(newsiz(1),padwidthl,3), resized, zeros(newsiz(1),padwidthr,3)];
        end
        if newsiz(1) > dstsiz(1)
            cropwidtht = floor( (newsiz(1) - dstsiz(1))/2 );
            cropwidthb = ceil( (newsiz(1) - dstsiz(1))/2 );
            resized = resized(cropwidtht:end-cropwidthb,:,:);
        elseif newsiz(1) < dstsiz(1)
            padwidtht = floor( (dstsiz(1) - newsiz(1))/2 );
            padwidthb = ceil( (dstsiz(1) - newsiz(1))/2 );
            resized = [zeros(padwidtht, dstsiz(2),3); resized; zeros(padwidthb, dstsiz(2),3)];
        end
    end

    result_image = resized;

end