% generateQueryFeatures.m
% Extracts SURF features from all query images.

printTitle('Generating query features ...');

% Loop over all input images
overwrite = 0;
queryFilenames = listDir(queryDir, '*.jpg');
numImages = length(queryFilenames);
queryImagesGray = cell(1, numImages);
queryFrames = cell(1, numImages);
queryDescriptors = cell(1, numImages);
queryFramesFilter = cell(1, numImages);
queryDescriptorsFilter = cell(1, numImages);
queryToDatabaseNumbers = zeros(1, numImages);
queryToDatabaseFilenames = readGroundTruthData(queryGroundTruth);
databaseFilenames = listDir(databaseDir, '*.jpg');
for nImage = 1:numImages
    
    disp(sprintf('\nProcessing image %d ... \n', nImage));
    
    % Parse root name
    jpgName = queryFilenames{nImage};
    indExt = strfind(jpgName, '.jpg');
    rootName = jpgName(1:indExt-1);
    
    % Make sure downsampled grayscale version exists
    pgmName = [rootName '.pgm'];
    if ~exist(pgmName, 'file') || overwrite
        imgColor = imread(jpgName);
        imgGray = rgb2gray(imgColor);
        imgGray = imresize(imgGray, [SURFInputHeight SURFInputWidth], 'bicubic');
        imwrite(imgGray, pgmName);
        queryImagesGray{nImage} = imgGray;
        clear imgColor imgGray;
    end % if
    
    % Make sure SURF file exists
    if SURFEnhanced
        SURFExtension = '.surfe';
    else
        SURFExtension = '.surf';
    end
    SURFName = [rootName SURFExtension];
    if ~exist(SURFName, 'file') || overwrite
        createSURFFile(SURFEnhanced, SURFProg, pgmName, SURFName, SURFExtension);
    end % if
    
    % Load SURF data
    [queryFrames{nImage}, queryDescriptors{nImage}] = loadSURFFile(SURFName);

    % Finding corresponding database number
    str1 = [databaseDir queryToDatabaseFilenames{nImage}];
    for nDatabase = 1:length(databaseFilenames)
        str2 = databaseFilenames{nDatabase};
        if strcmp(str1, str2)
           queryToDatabaseNumbers(nImage) = nDatabase;
           break;
        end
    end % nDatabase
    
end % nImage

% Save MAT file
save(SURFQueryMAT, 'query*');
