% ==================================================================================================
% Module:   alphamean.m
%
% Usage:    Alpha-trimmed mean filter
%
% Purpose: 
%     Performs the alpa-trimmed mean filter on an image using a specified
%     window size and alpha ("trim")
%
%     
% Input Variables:
%     fxy     input image (binary data)
%     alpha   "trim"
%     n       window length
%     
% Returned Results:
%     The image, alpha-trimmed mean filtered.
%     
% Restrictions/Notes:
%      
%
% See Also:
% 
% References:
% 
% Author:       Justin Ford
% Date:         3/22/04
% Revisions:    none
% ==================================================================================================


function result = med(fxy, alpha, n)

	result=zeros(size(fxy,1),size(fxy,2));
	
	n_row_dim = size(n,1);
	n_col_dim = size(n,2);
	
	if (n_row_dim > 1)
        row_diff = (n_row_dim - 1)/2;
	else
        row_diff = 0;
	end
	
	if (n_col_dim > 1)
        col_diff = (n_col_dim - 1)/2;
	else
        col_diff = 0;
	end

    fxy = double(fxy);
    
	for i=1:1:size(fxy,1)
        for j=1:1:size(fxy,2)
            if ( (i > row_diff) & (i < ( size(fxy,1) - row_diff )) & (j > col_diff) & (j < ( size(fxy,1) - col_diff )) )         
                result(i,j) = trim_mean( fxy((i-row_diff):(i+row_diff),(j-col_diff):(j+col_diff)), alpha );
            end
        end
	end
    
    result = uint8(result);

function tm = trim_mean(x, alpha)
	
	x_row_dim = size(x,1);
	x_col_dim = size(x,2);
	
	% If x is a matrix use rowcat() to make it a vector
	if ( (x_row_dim>1) & (x_col_dim>1) )
        x = rowcat(x);
        x_row_dim = 1;
        x_col_dim = size(x,2);
	end
	
	if (x_row_dim>1)
%         sorted = zeros(x_row_dim,1);
        x_dim = x_row_dim;
	else
%         sorted = zeros(1,x_col_dim);
        x_dim = x_col_dim;
	end
	
	sorted = sort(x);
    n = size(sorted,2);
    fan = floor(alpha * n);

%    bluh = 1;
    tm = 0;
    for i = (fan + 1):(n - fan)
%         if bluh == 1
%             bluh = 0;
%             disp(sprintf('Size = %d   Start = %d   End = %d',size(sorted,2),floor(alpha * size(sorted,2)) + 1,size(sorted,2) - floor(alpha * size(sorted,2))))
%         end
%         disp(sprintf('\ti = %d',i))
        tm = tm + sorted(i);
    end
    
    tm = 1/(n - fan) * tm;
    
function row_vector = rowcat( M )

	M_row_dim = size(M,1);
	M_col_dim = size(M,2);
	
	row_vector = M(1,:);
	
	for i = (2:M_row_dim)
        row_vector = [row_vector M(i,:)];
	end