function n = pschannelnames(a)
%PSCHANNELNAMES    Return the channel names of the current document.
%   [N] = PSCHANNELNAMES() returns the active channels as a cell array.
%   [N] = PSCHANNELNAMES(0) is the same as above.
%
%   [N] = PSCHANNELNAMES(1) returns all the channel names as a cell array.
%
%   Example:
%   activechannelnames = pschannelnames
%   allchannelnames = pschannelnames(1)
%
%   See also PSGETPIXELS, PSSETPIXELS, PSCONFIG, PSSETACTIVECHANNELS,
%   PSNUMCHANNELS

%   Thomas Ruark, 01/22/2007
%   Copyright 2007 Adobe Systems Incorporated

if exist('a', 'var')
    if a
        cs = 'channels';
    else
        cs = 'activeChannels';
    end
else
    cs = 'activeChannels';
end

pssep = '8F6AFB7E-EC1F-4b6f-AD15-C1AF34221EED';

% Build up the JavaScript
pstext = ['var channelNames = "";' ...
    'try {' ...
    '    if (app.documents.length) {' ...
    '        var doc = app.activeDocument;' ...
    '        if (doc.activeLayer.kind == LayerKind.NORMAL) {' ...
    '            for (var i = 0; i < doc.' cs '.length; i++) {' ...
    '                channelNames += doc.' cs '[i].name;' ...
    '                if ((i + 1) != doc.' cs '.length) {' ...
    '                    channelNames += "' pssep '";'...
    '                }' ...
    '            }' ...
    '        } else {'...
    '            if ($.os.search(/windows/i) != -1) {'...
    '                throw(localize("$$$/JavaScripts/MATLAB/WrongLayerKind=Can only get channel names on normal layers."));' ...
    '            } else {'...
    '                throw(localize("$$$/private/JavaScripts/MATLAB/WrongLayerKind/mac=Can only get channel names on normal layers."));' ...
    '            }'...
    '        }' ...
    '    }' ...
    '}' ...
    'catch(e) {' ...
    '    channelNames = "' pssep '" + e.toString();' ...
    '}' ...
    'channelNames;'];

t = psjavascriptu(pstext);
l = strfind(t, pssep);
n = {};
if l == 1
        error(t(length('8F6AFB7E-EC1F-4b6f-AD15-C1AF34221EED') + 1:end));
end
if ~isempty(l)
    le = length(t);
    c = 1;
    for ii = 1:length(l)
        n{ii} = t(c:l(ii)-1);
        c = c + length(n{ii}) + length(pssep);
    end
    n{length(l)+1} = t(c:le);
else
    n{1} = t;
end

