function rootspelling = chordroot_spelling(key, root, degrees)

temp = strsplit(':', key);
keyroot = temp{1};
if length(temp) > 1
    keymode = temp{2};
else
    keymode = 'major';
end



% major scale
scale{1} = [0 2 4 5 7 9 11];
% harmonic minor scale
scale{2} = [0 2 3 5 7 8 11];

diatonic = {'C','D','E','F','G','A','B'};
keymode_number = find(strcmp({'major','minor'},keymode));

if ischar(root)
    rootdegree = find(strcmp(diatonic,root(1)));
    rootpc = scale{1}(strcmp(diatonic,root(1))) + length(strfind(root,'#')) - length(strfind(root,'b'));
else
    [rootdegree, rootdegree]= min(abs(scale{1}-root));
    rootpc = root;
end


deg = [];
pcs = [];
for ii = 1:length(degrees)
    deg = [deg mod(rootdegree + str2num(degrees{ii}(end)) - 2,7)+1];
    pcs = [pcs mod(rootpc + degree2semitone(degrees{ii}),12)];
end

keyrootpc = scale{1}(strcmp(diatonic,keyroot(1))) + length(strfind(keyroot,'#')) - length(strfind(keyroot,'b'));
keydegree = find(strcmp(diatonic,keyroot(1)));

scalesemitone = circshift(mod(scale{keymode_number} + keyrootpc,12),[0 keydegree-1]);

fit = [0 0 0];

for deviation = -1:1 % test if the best degree is lower, just right or higher
    currdeg = mod(deg+deviation-1,7) + 1;
    chordaccidentals = mod(scalesemitone(currdeg) - pcs + 12 + 6,12) - 6;
    fit(deviation+2) = sum(abs(chordaccidentals));
end
[bestfitval, bestfit] = min(fit);
bestrootdegree = mod(rootdegree + bestfit - 2 - 1,7) + 1;
bestrootaccidentals = mod(rootpc - scale{1}(bestrootdegree)+6,12)-6;
switch bestrootaccidentals
    case -2 
        suff = 'bb';
    case -1
        suff = 'b';
    case 0
        suff = '';
    case 2 
        suff = '##';
    case 1
        suff = '#';
end
rootspelling = [diatonic{bestrootdegree}, suff];