% Frist run 02_21_10 - Bill Ussler
% 5 minute data interval between files

clear all
close all

%Input actual files size used on deployment
samplesPerFile = 5.0 * 60 * 48000.0;   %5 minutes/file * 60 sec/min * 48000 samp/sec

Fs = 48000; %samples per second
dT = 1/Fs;
Vref = 1.5;
LSB = Vref / (2^15 - 1);

dirName = 'N:\DeploymentJan22-10\R2010-021-16-28-19\R00000\'; % windows - format only
%dirName = '/Volumes/Larry/Deployment_Jan_22_10/R2010-021-16-28-19/R00000/'; % Bill Mac
startFileNum = 4305;
numFilesToProcess = 10;

endFileNum = startFileNum + numFilesToProcess - 1;

tStart = tic;

RMSIndex = 1;
histIndex = 1;
PSDIndex = 1;
fileIndex = 1;
for fileNum=startFileNum:endFileNum
    fileName = strcat(dirName, 'D',  sprintf('%06d', fileNum));
    fid = fopen(fileName);
    fprintf(1, '\nReading file number: %d   name: %s\n', (fileNum - startFileNum + 1), fileName);
    ADCData(fileIndex,:) = fread(fid, 'int16=>int16');
    fclose(fid);
    if(fileNum == startFileNum)
        fileData = dir(fileName);
        startDatenum = fileData.datenum + (1/3);    % add 8 hours to the time stamp to correct for OS misinterpretation
    end
    
    RMSRecordTime = 60.0; % seconds
    RMSRecordLength = RMSRecordTime * Fs;    % samples
    processRMS = 1;
    if( processRMS == 1)
        RMSRecordNum = 1;
        startSample = ((RMSRecordNum - 1) * RMSRecordLength) + 1;
        lastSample = startSample + RMSRecordLength - 1;
        while( lastSample <= samplesPerFile)
            RMS(RMSIndex) = sqrt(mean(single(ADCData(fileIndex,startSample:lastSample)).^2));
            %fprintf('RMS index %d  RMS Value: %f\n', RMSIndex, RMS(RMSIndex));
            RMSRecordNum = RMSRecordNum + 1;
            RMSIndex = RMSIndex + 1;
            startSample = ((RMSRecordNum - 1) * RMSRecordLength) + 1;
            lastSample = startSample + RMSRecordLength - 1;
        end
    end
    fileIndex = fileIndex + 1;
 end

if(processRMS == 1)
    RMSTimeIndex = startDatenum + (((0:RMSIndex-2)*RMSRecordTime) / 86400.0); % time index in seconds
    figure
    plot(RMSTimeIndex,RMS);
    datetick('x')
    xlabel('Clock Time')
    ylabel('RMS Amplitude')
    title('January 22, 2010 Deployment')
end

tElapsed = toc(tStart)


