function ABadjust_svm(iRun)
% Adjusting feature weights by SVM.
% <iRun>: the No. of the random run
% <Totalsketch>: allowed number of selected Gabors   

templateSize = [100 150]; % template size is 100 (height) * 150 (width)
subsampleStep = 2;

trainfile = sprintf( 'svmadjust_train_run%d.txt', iRun ); % training examples
testfile = sprintf( 'svmadjust_test_run%d.txt', iRun ); % testing examples
modelfile = sprintf('svmadjust_model_run%d.txt', iRun);
outfile = sprintf('svmadjust_out_run%d.txt',iRun); % testing results

% load natural statistics
load(sprintf('naturalStat_run%d',iRun));

% load model
load( sprintf('model_run%d.mat', iRun) );

% load the positive images
load(sprintf('../RandomSplits/split%d.mat',iRun),'posTrainImages');

% CONSTANTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Totalsketch = 80;  % allowed number of selected Gabors
Lrange = 3; % allowed shifting in location (times sub pixels)
Orange = 1; % allowed shifting in orientation
%%% Note: Lrange*sub is the pixels allowed to shift along normal
%%%       Lrange*sub should be the same in learning and testing

% special case: single example
if length(posTrainImages) == 1
    storedLrange = Lrange;
    storedOrange = Orange;
    Lrange = 0;
    Orange = 0;
end

% TRAINING EXAMPLES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fid = fopen( trainfile, 'w' );
% ==================================================================
%  input images from a folder
% ==================================================================
load(sprintf('../RandomSplits/split%d.mat',iRun),'posTrainImages');
nimage = length(posTrainImages);
posTrainImagePaths = cell(1,length(posTrainImages));
for i = 1:length(posTrainImages)
    posTrainImagePaths{i} = sprintf('../posAll/%s',posTrainImages{i});
end

% FILTERING IMAGES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
tic
disp('start filtering');
addpath('../');
[allfilter] = makefilter(scale, norient);  % generate Gabor filters
allfiltered = getGaborMaps(posTrainImagePaths,templateSize,allfilter); % compute Sum1 maps
Ctransform(nimage, norient, allfiltered, ones(1,nimage)*templateSize(1)...
    , ones(1,nimage)*templateSize(2), Upperbound); % sigmoid transform
Cmax(nimage, norient, allfiltered, templateSize(1), templateSize(2), Lrange, Orange, subsampleStep); % compute Max1 maps
disp(['filtering time: ' num2str(toc) ' seconds']);


% extract selected feature responses for all positive examples
for i = 1:nimage
	fprintf(fid, '%d ', 1); % positive example
	for j = 1:Totalsketch
		val = allfiltered{i,Mi(j)+1}(Mx(j),My(j));
		fprintf(fid, '%d:%.5f ', j, val );
	end
	fprintf(fid, '\r\n' );
end



% ==================================================================
%  input images from a folder
% ==================================================================
load(sprintf('../RandomSplits/split%d.mat',iRun),'negTrainImages');
nimage = length(negTrainImages);
negTrainImagePaths = cell(1,length(negTrainImages));
for i = 1:length(negTrainImages)
    negTrainImagePaths{i} = sprintf('../negAll/%s',negTrainImages{i});
end

% FILTERING IMAGES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
tic
disp('start filtering');
addpath('../');
[allfilter] = makefilter(scale, norient);  % generate Gabor filters
allfiltered = getGaborMaps(negTrainImagePaths,templateSize,allfilter); % compute Sum1 maps
Ctransform(nimage, norient, allfiltered, ones(1,nimage)*templateSize(1)...
    , ones(1,nimage)*templateSize(2), Upperbound); % sigmoid transform
Cmax(nimage, norient, allfiltered, templateSize(1), templateSize(2), Lrange, Orange, subsampleStep); % compute Max1 maps
disp(['filtering time: ' num2str(toc) ' seconds']);

for i = 1:nimage
		fprintf(fid, '%d ', -1); % neagive example
		for j = 1:Totalsketch
			val = allfiltered{i,Mi(j)+1}(Mx(j),My(j));
			fprintf(fid, '%d:%.5f ', j, val );
		end
		fprintf(fid, '\r\n' );
end
fclose(fid);

% ========== adjust by svm ==============
system( sprintf('../svm_learn -c 1 %s %s',trainfile,modelfile) );


%% testing stage
fid = fopen( testfile, 'w' );
% ==================================================================
%  input positive testing images
% ==================================================================
load(sprintf('../RandomSplits/split%d.mat',iRun),'posTestImages');
nimage = length(posTestImages);
posTestImagePaths = cell(1,length(posTestImages));
for i = 1:length(posTestImages)
    posTestImagePaths{i} = sprintf('../posAll/%s',posTestImages{i});
end

% FILTERING IMAGES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
tic
disp('start filtering');
addpath('../');
[allfilter] = makefilter(scale, norient);  % generate Gabor filters
allfiltered = getGaborMaps(posTestImagePaths,templateSize,allfilter); % compute Sum1 maps
Ctransform(nimage, norient, allfiltered, ones(1,nimage)*templateSize(1)...
    , ones(1,nimage)*templateSize(2), Upperbound); % sigmoid transform
Cmax(nimage, norient, allfiltered, templateSize(1), templateSize(2), Lrange, Orange, subsampleStep); % compute Max1 maps
disp(['filtering time: ' num2str(toc) ' seconds']);


% extract selected feature responses for the above examples
for i = 1:nimage
		fprintf(fid, '%d ', 1); % positive example
		for j = 1:Totalsketch
			val = allfiltered{i,Mi(j)+1}(Mx(j),My(j));
			fprintf(fid, '%d:%.5f ', j, val );
		end
		fprintf(fid, '\r\n' );
end

nPosTest = nimage;


% ==================================================================
%  input negative testing images
% ==================================================================
load(sprintf('../RandomSplits/split%d.mat',iRun),'negTestImages');
nimage = length(negTestImages);
negTestImagePaths = cell(1,length(negTestImages));
for i = 1:length(negTestImages)
    negTestImagePaths{i} = sprintf('../negAll/%s',negTestImages{i});
end

% FILTERING IMAGES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
tic
disp('start filtering');
addpath('../');
[allfilter] = makefilter(scale, norient);  % generate Gabor filters
allfiltered = getGaborMaps(negTestImagePaths,templateSize,allfilter); % compute Sum1 maps
Ctransform(nimage, norient, allfiltered, ones(1,nimage)*templateSize(1)...
    , ones(1,nimage)*templateSize(2), Upperbound); % sigmoid transform
Cmax(nimage, norient, allfiltered, templateSize(1), templateSize(2), Lrange, Orange, subsampleStep); % compute Max1 maps
disp(['filtering time: ' num2str(toc) ' seconds']);


% extract selected feature responses for the above examples
for i = 1:nimage
		fprintf(fid, '%d ', -1); % negative example
		for j = 1:Totalsketch
			val = allfiltered{i,Mi(j)+1}(Mx(j),My(j));
			fprintf(fid, '%d:%.5f ', j, val );
		end
		fprintf(fid, '\r\n' );
end


% svm classification
system( sprintf('../svm_classify %s %s %s',testfile,modelfile,outfile) );

% read svm testing result
fid = fopen(outfile,'r');
predicted = textscan(fid,'%.6f %*[^\n]');
fclose(fid);
predicted = predicted{1};
posScores = predicted(1:nPosTest);
negScores = predicted(1+nPosTest:end);

addpath('../');
[ap testAUC] = evaluate(posScores,negScores);
save( sprintf('adjusted_svm_run%d.mat', iRun), 'ap', 'testAUC' );





