clear
clc
w = wavread( 'A4_R2.wav' );
w1 = w(1:22050);
initialFreq = 40;
points = 100;
thisFreq = 0;

thresh = 0.005;
start = 0;
cluster = [];
segment = [];
clear criticalInfo;
criticalInfo = {};
hotSpots     = {};
oldClusters = 1;
newClusters = 1;
OUT_OF_COMMISSION = 9999;

for i=1:points
    thisFreq = initialFreq+i;
    v = fastconv(w1,4096*2,thisFreq,14.7);
    [av1,fv1] = desa(v);
    timeAbove = find( av1>thresh );
    cluster = [];
    if timeAbove
        diffAbove = diff( timeAbove );
        transitions = find( diffAbove ~= 1 );
        start   = 1;
        if transitions
            for k=1:length(transitions)
                segment = timeAbove( [(start) transitions(k)] );
                if diff(segment)>100
                    cluster( :,size( cluster, 2 ) + 1 ) = segment;
                end
                start = transitions(k) + 1;
            end
        end
        segment = timeAbove( [start length(timeAbove) ] );     
        if diff(segment)>100
            cluster( :,size( cluster, 2 ) + 1 ) = segment;
        end
        if cluster
            fileNumStr = [48*ones( 1,4-length( num2str(thisFreq) ) ), num2str(thisFreq) ];
            fileName   = ['data/amplitude_band_' fileNumStr ];
            save( fileName, 'av1' );
        end    
    end
    criticalInfo{i} = struct( 'Frequency', thisFreq, 'Clusters', cluster );
    
    numClusters = size( criticalInfo{i}.Clusters,2 );
    for l=numClusters:-1:1
        oldClusters = size( criticalInfo{i}.Clusters,2 );
        for m=1:size( hotSpots, 2 )
            if ( find( abs(hotSpots{m}.FreqBand-thisFreq)==1 ) )
                if is_overlap( hotSpots{m}.SampBand, criticalInfo{i}.Clusters(:,l) )
                    hotSpots{m}.SampBand(1) = ...
                        min( hotSpots{m}.SampBand(1), criticalInfo{i}.Clusters(1,l) );
                    hotSpots{m}.SampBand(2) = ...
                        max( hotSpots{m}.SampBand(2), criticalInfo{i}.Clusters(2,l) );
                    if not( sum( not( hotSpots{m}.FreqBand - criticalInfo{i}.Frequency ) ) )
                        hotSpots{m}.FreqBand = ...
                            [hotSpots{m}.FreqBand criticalInfo{i}.Frequency];
                    end
                    criticalInfo{i}.Clusters(:,l) = [];
                    break;
                end
            end
        end
        newClusters = size( criticalInfo{i}.Clusters,2 );
        if oldClusters==newClusters
            hotSpots{ length(hotSpots) + 1 } = ...
                struct( 'FreqBand',thisFreq,'SampBand',criticalInfo{i}.Clusters(:,l) );
            criticalInfo{i}.Clusters(:,l) = [];
        end    
    end
    for n=1:size( hotSpots, 2 )
        if (thisFreq > max( hotSpots{n}.FreqBand )
            for 
        end
    end    
end