function ret = energies(runname,nodes)
% Written by Marco F. Duarte 08/13/02
% Extracts energy values and performs CFAR detection
% ret: Return value (0 indicates normal, -1 indicates error)
% runname: Name of the run to be processed (i.e. '' runname '')
% nodes: Node list

% CFAR Parameters
ret = -1;
t_en = 3720;
for i=1:length(nodes),
    % load raw data files
    eval(['load output\sensit' num2str(nodes(i)) '-1-' runname '.txt']);
    eval(['acts = sensit' num2str(nodes(i)) '_1_' runname ';']);
    eval(['clear sensit' num2str(nodes(i)) '_1_' runname '']);    eval(['load output\sensit' num2str(nodes(i)) '-2-' runname '.txt']);
    eval(['sets = sensit' num2str(nodes(i)) '_2_' runname ';']);
    eval(['clear sensit' num2str(nodes(i)) '_2_' runname '']);
    eval(['load output\sensit' num2str(nodes(i)) '-3-' runname '.txt']);
    eval(['irts = sensit' num2str(nodes(i)) '_3_' runname ';']);
    eval(['clear sensit' num2str(nodes(i)) '_3_' runname '']);    aclen = length(acts);
    accpa = [];
    % normalize files
    acts = acts/32768;
    sets = sets/32768;
    irts = irts/32768;
    % calculate energy for 75 ms intervals
    for j=1:floor(aclen/t_en),
        acseg = acts(((j-1)*t_en)+1:min([j*t_en aclen]));
        acsege = sum((acseg-mean(acseg)).^2);
        accpa = [accpa acsege/t_en];
    end
    selen = length(sets);
    secpa = [];
    for j=1:floor(selen/t_en),
        seseg = sets(((j-1)*t_en)+1:min([j*t_en selen]));
        sesege = sum((seseg-mean(seseg)).^2);
        secpa = [secpa sesege/t_en];
    end
    irlen = length(irts);
    ircpa = [];
    for j=1:floor(irlen/t_en),
        irseg = irts(((j-1)*t_en)+1:min([j*t_en irlen]));
        irsege = sum((irseg-mean(irseg)).^2);
        ircpa = [ircpa irsege/t_en];
    end
    % save calculations for future use
    eval(['save output\' runname 'cpa' num2str(nodes(i)) '_1.txt accpa -ascii']);
    eval(['save output\' runname 'cpa' num2str(nodes(i)) '_2.txt secpa -ascii']);
    eval(['save output\' runname 'cpa' num2str(nodes(i)) '_3.txt ircpa -ascii']);
end
ret = 0;
