function jobsTable = jobsReader(filename, varargin)
%JOBSREADER Read jobs list from XML file
%
%   jobsReader(FILENAME) reads and parses jobs from the XML file, FILENAME.
%   jobsTable is a table array.
%
%   jobsReader(FILENAME,LOCATION) selects jobs that match the location
%   denoted by the string, LOCATION. The string 'all' may be used to denote
%   all locations. 
%
%   jobsReader(FILENAME,LOCATION,DEPARTMENT) selects only jobs that match
%   the location and department denoted by the string, DEPARTMENT. The
%   string 'all' may be used to denote all departments.
%
%   Example
%       jobsReader('rss.xml','US-MA-Natick')
%       jobsReader('rss.xml','all','all')
%
%   See also XMLREAD

% Author: Kelly Luetkemeyer

myLocation = 'US-MA-Natick';
myDepartment = 'software development';
switch length(varargin)
    case 1
        myLocation = varargin{1};
    case 2
        myLocation = varargin{1};
        myDepartment = varargin{2};
end

% Read the data from the xml file.
dom = xmlread(filename);

% Retrieve all the items from the DOM that are tagged |'item'|.
items = dom.getElementsByTagName('item');
itemsLength = items.getLength;

% Create a table to
% contain the information from the RSS feed. Map the XML tag names to the
% table variable names by using two cell arrays. Initialize the table
% using cell2table
tagNames = {'id', 'location', 'title', 'job_function', 'job_type'};
tableVariableNames = {'Reference', 'Location', 'Title', 'Department', 'Type'};
emptyItems = cell(itemsLength,length(tableVariableNames));
jobsTable = cell2table(emptyItems,'VariableNames',tableVariableNames);

% Loop through each item and add the information to the table. Use
% zero-based indexing to obtain the node since the data is contained in a
% Java object. Use one-based indexing for the table array.
for k=0:itemsLength-1
    item = items.item(k);
    for n = 1:length(tagNames)
        node = item.getElementsByTagName(tagNames{n});
        jobsTable{k+1,n} = {char(node.item(0).getTextContent)};
    end
end

% Select your desired location.
if ~strcmp(myLocation, 'all')
    rows = strcmpi(jobsTable.Location, myLocation);
    jobsTable = jobsTable(rows,:);
    jobsTable.Location = [];
end

% Select your desired department.
if ~strcmp(myDepartment,'all')
    rows = strcmpi(jobsTable.Department, myDepartment);
    jobsTable = jobsTable(rows,:);
    jobsTable.Department = [];
end

