function outparts = makeparts(beattimes,segtimes,seglevel)

parts = struct('n',[], 'indices',[], 'letter', [],'level',[]);
nPart = 0;
nSeg = size(segtimes,1);

for iSeg = 1:nSeg
    newpart = true;
%     tempbeat = struct([]);
    segbeats = find(mean(beattimes,2) >= segtimes(iSeg,1) & mean(beattimes,2) < segtimes(iSeg,2));
    lenSegbeats = length(segbeats);
    for iPart = 1:nPart
        if seglevel(iSeg) == parts(iPart).level && lenSegbeats == parts(iPart).n
            parts(iPart).indices = [parts(iPart).indices segbeats(1)];
%             parts(iPart).beat = [parts(iPart).beat tempbeat];
            newpart = false;
            break;
        else
            newpart = true;
        end
    end
    if newpart && ~isempty(segbeats)
        nPart = nPart + 1;
        parts(nPart).indices = segbeats(1);
        parts(nPart).n = lenSegbeats;
        parts(nPart).level = seglevel(iSeg);
%         parts(nPart).beat = tempbeat;
    end
    
end
partnind = zeros(nPart,1);
partlen = zeros(nPart,1);
for iPart = 1:nPart
    partnind(iPart) = length(parts(iPart).indices);
    partlen(iPart) = parts(iPart).n;
end
[partind,partind] = sort(partnind.*partlen,'descend');
letters = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U'};
outparts = parts;
for iPart = 1:nPart
    kPart = partind(iPart);
    parts(kPart).letter = letters{iPart};
    outparts(iPart) = parts(kPart);
end