%
%PAL_Contrasts  Linear, orthogonal set of contrasts
%
%   syntax: contrasts = PAL_Contrasts(N, {optional arguments} )
%
%   contrasts = PAL_Contrasts(N) where N is a scalar, returns an N x N 
%   matrix containing an orthogonal set of polynomial contrasts.
%
%   Other sets of contrasts may be generated by passing the type of the
%   contrasts as an optional argument. Supported: 'Helmert', 'Periodic',
%   'Polynomial' and 'Identity'. The latter returns an identity matrix.
%
%   Example: PAL_Contrasts(3,'Helmert') returns:
%
%    1.0000    1.0000    1.0000
%    0.6667   -0.3333   -0.3333
%         0    0.5000   -0.5000
%
%Introduced: Palamedes version 1.0.0 (NP)

function contrasts = PAL_Contrasts(N, varargin)

option = 'polynomial';

if ~isempty(varargin)
    valid = 0;
    if strncmpi(varargin{1}, 'polynomial',4)
        option = 'polynomial';
        valid = 1;
    end
    if strncmpi(varargin{1}, 'periodic',4)
        option = 'periodic';
        valid = 1;
    end
    if strncmpi(varargin{1}, 'helmert',4)
        option = 'helmert';
        valid = 1;
    end
    if strncmpi(varargin{1}, 'identity',4)
        option = 'identity';
        valid = 1;
    end
    if valid == 0
        message = ['Warning: ' varargin{1} ' is not a valid option. Ignored.'];
        warning(message);
    end        
end            

if strncmpi(option,'iden',4)
    contrasts = eye(N);
else
    contrasts = zeros(N,N);
    contrasts(1,:) = 1;

    for index = 2:N
        switch lower(option(1:4))
            case{'poly'}
                x = (1:N).^(index-1);
            case{'peri'}
                f = (index-1)/2;
                x = [0:2*pi/N:2*pi-2*pi/N] + pi/N;
                x = cos(f.*x);
            case{'helm'}
                x = zeros(1,N);
                x(index-1) = 1;
        end
        contrasts(index,:) = x;
        if ~strncmpi(option,'peri',4)
            for w = 1:index-1
                b = sum(x.*contrasts(w,:))./sum(contrasts(w,:).^2);
                contrasts(index,:) = contrasts(index,:) - b*contrasts(w,:);
            end
        end
    end
end