function outStruct = probesetlookup(affyStruct,theID)
% PROBESETLOOKUP looks up the gene name for a probe set
%
%   PROBESETLOOKUP(affyStruct,ID) returns the probe set information for
%   probe set or gene ID from CHP or CDF structure affyStruct.
%
%   Example:
%       cdfStruct = affyread('DrosGenome1.cdf',...
%                                  'D:\Affymetrix\LibFiles\DrosGenome1')
%       % Look up based on the probe set ID
%       probesetlookup(cdfStruct,'142176_at')
%       % Or look up based on the gene name
%       probesetlookup(cdfStruct,'FBgn0032123')
%
%   See also AFFYREAD, PROBELIBRARYINFO, PROBESETLINK, PROBESETPLOT, PROBESETVALUES.

%   Affymetrix is a registered trademarks of Affymetrix, Inc.

% Copyright 2003-2004 The MathWorks, Inc.
% $Revision: 1.1.12.1 $   $Date: 2004/12/24 20:44:59 $

persistent ginStruct

libPath = affyStruct.LibPath;
chipType = affyStruct.ChipType;

if isempty(ginStruct) ||~isfield(ginStruct,'Name') ||...
        ~isequal(ginStruct.Name, chipType)
    try
        ginStruct = affyread([chipType '.GIN'],libPath);
    catch
        error('Bioinfo:UnknownProbeName',...
            'Unknown probe set name: %s.',theID);
    end
end

% see if this is a probe name
geneID = strmatch(theID,ginStruct.ProbeSetName);%#ok
if isempty(geneID)
    geneID = strmatch(theID,ginStruct.ID);%#ok
end

try

    geneName = ginStruct.ID{geneID};

    probeSetName = ginStruct.ProbeSetName{geneID};
    cIndex = strmatch(probeSetName,{affyStruct.ProbeSets.Name}); %#ok
    
    description = ginStruct.Description{geneID};
    if numel(ginStruct.SourceID) > 1
        sourceID = ginStruct.SourceID(geneID);
    else
        sourceID = 1;
    end
    source = ginStruct.SourceNames{sourceID};
    sourceUrl = sprintf(ginStruct.SourceURL{sourceID},geneName);
catch
    if isempty(geneID)
        error('Bioinfo:UnknownProbeName',...
            'Could not fing probe set: %s.',theID);
    elseif numel(geneID) > 1
        error('Bioinfo:AmbiguousProbeName',...
            'Ambiguous probe set: %s.',theID);
    end
end
outStruct.Identifier = geneName;
outStruct.ProbeSetName = probeSetName;
outStruct.CDFIndex = cIndex;
outStruct.GINIndex = geneID;
outStruct.Description = description;
outStruct.Source = source;
outStruct.SourceURL = sourceUrl;