% Modified 02/18/10 by Bill Ussler
clear all

Fs = 48000;
dT = 1/Fs;
Vref = 1.5;
LSB = Vref / (2^15 - 1);
segLength = 2^12;
overlapPercent = 50;
minutesPerRecord =1;
samplesPerRecord = minutesPerRecord * 60 * Fs;

dirName = '/Volumes/Larry/Deployment_Nov2409/R2009-328-08-01-49/R00000/';
startFileNum = 1;
numFilesToProcess = 43400;
recordsToAvg = 5;
endFileNum = startFileNum + numFilesToProcess - 1;

hSpectrum = spectrum.welch('Blackman-Harris', segLength, overlapPercent);

numHistBins = 21;
binSpacing = (2^16) / numHistBins;
histX = (-(numHistBins - 1) *  binSpacing / 2):binSpacing:((numHistBins - 1) * binSpacing ) / 2;

recordNum = 1;
avgNum = 1;
iAvg = 1;
sum = zeros(samplesPerRecord, 1, 'int16');
tStart = tic;
for fileNum=startFileNum:endFileNum
    fileName = strcat(dirName, 'D',  sprintf('%06d', fileNum));
    fid = fopen(fileName);
    
    if(recordNum == 1)
        D = dir(fileName);
        lastDate = D.date;
    end
    
    fprintf(1, 'Reading file number %d \n', fileNum);
  
    ADCData(:,iAvg) = fread(fid, 'int16=>int16');
    fclose(fid);

    rms(recordNum) = sqrt(mean(single(ADCData(:,iAvg)).^2));
    sum = sum + ADCData(:,iAvg);
    if(iAvg == recordsToAvg)
        avgADCData = sum ./ recordsToAvg;
        histY(avgNum,:) = hist(single(avgADCData), histX);
        avgNum = avgNum + 1;
        iAvg = 1;
        sum = zeros(samplesPerRecord, 1, 'int16'); 
        
        D = dir(fileName);
        if( str2num(D.date(1:2)) > str2num(lastDate(1:2)) )
            s = strcat('processedData', lastDate);
            s2 = strrep(s, ' ', '-');
            s3 = strrep(s2, ':', '');
            s4 = strcat(dirName, s3);
            fprintf(1, 'Writing Matlab data file %s\n', s4);
            save(s4);
            lastDate = D.date;
        end       
 
        clear ADCData avgADCData
    else
        iAvg = iAvg + 1;
    end
    recordNum = recordNum + 1;
end
tElapsed = toc(tStart)
clear sum
%waterfall(histX,1:avgNum-1,histY)


