function F = wordfactor(varargin)
% WORDFACTOR Create a factor for a word
%
% F = WORDFACTOR(N,L,M,W) where N is the list of (numeric) variable
% names for the characters, L is the number of values they may
% take on, M is the name for the word variable, W is
% a matrix where the rows contain the valid lexicon values. Factor
% value is constant for any lexicon value.
%
% F = WORDFACTOR(N,L,M,W,U) where U is an (optional) list of factor values.
%
% F = WORDFACTOR creats an empty wordfactor
%
% F = WORDFACTOR(A) where A is a wordfactor object will return a copy of A
  
% Fields
%  wordnode
%  words
%  wordtable
%  numLabels

% Jerod Weinman
% jerod@acm.org
  
% $Id: wordfactor.m 50 2011-07-29 16:01:00Z weinman $
 
% Jerod Weinman
% jerod@acm.org
% Copyright 2006, 2008, 2009, 2011
 
%    This file is part of VIDI.
%
%    VIDI is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    VIDI is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with VIDI.  If not, see <http://www.gnu.org/licenses/>.

  if nargin == 0
    
    F.wordnode = [];
    F.words = [];
    F.wordtable = [];
    F.numLabels = 0;
    
    F = class(F,'wordfactor',factor());
    
  elseif nargin == 1 isa(varargin{1},'wordfactor')
    
    F = varargin{1};
    
  else
    
    N = varargin{1};
    L = varargin{2};
    M = varargin{3};
    W = varargin{4};
    
    if nargin>4
      U = varargin{5};
      if size(U,1)==1
        U = U'; % make a column vector
      end;
    else
      U = zeros(size(W,1),1);
    end;
    
    if any(W(:)<1)
      error('Word list indices must be greater than zero');
    end;
    
    if any(W(:)>L)
      error('Word list contains out of bound label');
    end;
    
    if size(W,1)~=length(U)
      error('Dimensions of lexicon do not match factor values');
    end;
    
    if size(W,2) ~= length(N)
      error('Dimensions of lexicon do not match character variable list');
    end;
    
    % Create the parent factor (with an empty table)
    F0 = factor([N ; M],zeros(zeros(1,length(N)+1)));
    
    F.wordnode = M;
    F.words = W;
    F.wordtable = U;
    F.numLabels = L;
    
    F = class(F,'wordfactor',F0);
    
  end;
  
