function classification = classifyLR(type, data)
% classifyLR - logistic regression classifier
%
%   classification = classifyLR(type, data)
%   This classifies the data using logistic regression.
%   
%   The inputs are as follows.
%       type :  This input detemines which metric to use in classifying the
%               data.
%
%       data :  An NxL or NxL-1 matrix containing the data. L is the length
%               of the "theta" vector. L-1 is the number of dimensions the 
%               data has. For example, if the data contains three 
%               dimensions (say, of distance, frequency, and orientation) 
%               then L-1 is 3. The data has one less dimension than "theta"
%               because "theta" contains an intercept term. For more 
%               information, one can find articles on logistic regression 
%               online.
%
%   The outputs are as follows.
%       classification : returns a column vector of length N (where N is
%                        the number of "data points") that classifies each
%                        point as 1 (positive sample) or 0 (negative
%                        sample).
%
%   See also LOGISTICREGRESSION, PREPAREDATA
%

%% Check number arguments
if (nargin ~= 2), error('Too few input parameters. Need a type and a data matrix.'); end
if (~ischar(type)), error('Data ''type'' must be a string: ''sCIELAB'', ''CIELAB'', or ''hasler'''); end
if (strcmp(upper(type),'SCIELAB') == 0 & strcmp(upper(type),'CIELAB') == 0 & strcmp(upper(type), 'HASLER') == 0)
    error('You must specify the metric to use: ''sCIELAB'', ''CIELAB'', or ''hasler''');
end

%% Load appropriate model
load LRmodels.mat
if (strcmp(upper(type),'SCIELAB') == 1)
    theta = LRmodels.sCIELAB_theta; % use sCIELAB model
elseif (strcmp(upper(type),'CIELAB') == 1)
    theta = LRmodels.CIELAB_theta;
elseif (strcmp(upper(type),'HASLER') == 1)
    theta = LRmodels.hasler_theta;
end

norm_dat = [];
for M = 1:size(data,1),
    norm_dat = [norm_dat; norm(data(M,:))];
end
data = data./repmat(norm_dat, 1,size(data,2));

%% Check data size
l = length(theta);
[m n] = size(data);
if(m == l-1)
    dat = data';
    % Pad data with 1's (note the dimension)
    dat = [ones(n,1) dat];
    s=0;
elseif(n == l-1)
    dat = data;
    % Pad data with 1's (note the dimension)
    dat = [ones(m,1) dat];
    s=0;
elseif (m == l)
    dat = data';
    % check to make sure first "column" is all ones
    s = sum(ones(n,1) - dat(:,1));
elseif (n == l)
    dat = data;
    % check to make sure first "column" is all ones
    s = sum(ones(m,1) - dat(:,1));
else
    error('Input ''data'' is not of the right size.');
end

if (s~=0)
    error('Input ''data'' does not contain a column of ones (needed for logistic regression).');
end

%% Classify
classification = 1./(1 + exp(-(theta * dat')')); % sigmoid function
classification(find(classification <= 0.5)) = 0;
classification(find(classification >= 0.5)) = 1;


