global T

%valLambda = 0.5;

cd('database_closed');
D = dir;

reference = {'87_cw_ccw_mid.mat' '010_top_right.mat' 'heart6.mat'...
        'heart5.mat' 'D5_top.mat' 'B9_top.mat' 'D9_bottom.mat'};
    
for i=1:size(reference,2),

	name1 = char(reference(i));
	load(name1);
	curve1 = curve;

    length1 = size(name1,2);
    outFileName = sprintf('%stxt',name1(1:length1-3));
    FID = fopen(outFileName, 'wt');
	% filenames start at 3
	for j=3:size(D,1),
        name2 = D(j).name;
        length = size(name2,2);
        % check file type
        if(strcmp(name2(length-3:length), '.mat')==0)
            continue;
        end
        load(name2);
        curve2 = curve;
        disp(sprintf('processing %s and %s...', name1, name2));
        % get T values
        processClosedShapeContexts;
%        processClosedCurvature;
%        processClosedCurvature;
%        processShapeContNonSquareGrid;
%        processCurvNonSquareGrid;
%        processCurvature;
        [m, n] = size(T); 
		m_ = m/3;   % closed curve length
		n_ = n/2;   % closed curve length
		x = zeros(m,1); x(1,1) = 1;
        % closed curve locations
        y = zeros(n,1); y(1,1) = 1;
		for i = 2:m,
            x(i) = x(i-1) + spacing1(i);
		end
		for j = 2:n,
            y(j) = y(j-1) + spacing2(j);
		end
        % offset the y-axis tickmarks - solve for optimal path in middle band
        % comment out to solve for optimal path in lower band
        x = x - m_;
        c = backtrack(T, 0.1, x(m), y(n), y, x);
        disp('Reparametrizing curve 2...'); 
        c_endpoint = round(c(end, 2));
        curve2_match_point = mod(c_endpoint-1, n_)+1;
        curve2new = [curve2(curve2_match_point:end, :); curve2(1:curve2_match_point-1, :)];
        curve2 = curve2new;
        % re-run	
        processShapeContexts;
        % score
        curve_distance = T(end, end);
        diag_integral = valLambda*sqrt(m*m + n*n);
		distance = curve_distance - diag_integral + abs(1 - min(m,n)/max(m,n))
        fprintf(FID, '%s \t %s \t %f \n', name1, name2, distance);
	end
	%end
	fclose(FID);

end

cd ..
