%
% PARSENOTE
% 
% [natural, accidentals, success, errormessage] = parsenote(note, {verbose})
% 
% Parse a note to a natural character value and a number of accidentals
% if accidentals is positive it denotes number of sharps,
% if it is negative it denotes number of flats.
%
% Success = 1 if symbols parsed correctly, 0 otherwise.
%
% If optional argument 'verbose' is 1, function prints any errormessage to 
% the screen.
% 
% returns:  natural     (char)
%           accidentals (integer) 
%           success     (boolean)
%           errormessage (string)
%
% Author: Christopher Harte, March 2009
% 
% Copyright: Centre for Digital Music, Queen Mary University of London 2005 
%
% This file is part of the C4DM Chord Toolkit V2.0  
%
% The C4DM Chord Toolkit 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 2 of the License, or
% (at your option) any later version.
%
% The C4DM Chord Toolkit 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 the C4DM Toolkit; if not, write to the Free Software
% Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

%
function [natural,accidentals,success, errormessage] = parsenote(note, verbose)

if nargin < 2
    verbose = 0;
end

errormessage = '';

ilength = length(note);

accidentals = 0;
natural = [];
success=1;

index = 1;

if (isempty(note))  % if we have been passed an empty string
    success=0;

else  % parse the note string
  
    switch(note(index))

        case {'A','B','C','D','E','F','G'}

            %first character should be a natural
            natural = note(index);
            index= index+1;

            %remaining characters should be sharps or flats
            while index <= ilength

                switch note(index)

                    case 'b' % FLAT
                        accidentals = accidentals - 1; %decrement accidental count
                        index = index + 1;

                    case '#' % SHARP
                        accidentals = accidentals + 1; %increment accidental count
                        index = index + 1;

                    otherwise
                        % if neither of the above then the note is incorrect
                        success=0;
                        index = ilength+1;
                end
            end

        otherwise
            success=0;        
    end
end
    
if(success==0) % correct note therefore return success = 1 
    % if not an integer then the note string is incorrect
    errormessage = sprintf(['Error in parsenote: Unrecognised note "' note '"\n']); 
    
    if verbose ==1
        fprintf(1,errormessage);
    end
end
