%**************************************************************************
%This function reads temperature log data files.  It plots the history
%of the temperature.
%
%Zachary Wolf, 1/5/09

function [] = temp_hist()

%Clear the workspace
clear

%Set parameter values by executing the parameter file
temp_hist_param

%Output files
dat_file = [OUTPUT_DIR, 'temp_hist.dat'];
plt_file = [OUTPUT_DIR, 'temp_hist.ps'];
mat_file = [OUTPUT_DIR, 'temp_hist.mat'];
fig_file = [OUTPUT_DIR, 'temp_hist.fig'];

%Initialize the data file
util_dat_init(dat_file);
util_dat_msg(dat_file, cellstr(' '));
util_dat_msg(dat_file, cellstr('Temperature History:'));
util_dat_msg(dat_file, cellstr(HIST_NAME));

%Initialize the plots
temp_hist_plot_init(plt_file, HIST_NAME);

%Loop over data files, get data
[r, c] = size(INPUT_FILE);
for ii = 1 : c
    
    %Get the input file
    file_name = INPUT_FILE{ii};

    %Get the measurement data
	[header, month, day, year, hour, minute, second, pressure, humidity, temp] = temp_hist_read_meas(file_name);
    
    %Store the data
    data(ii).header = header;
    data(ii).month = month;
    data(ii).day = day;
    data(ii).year = year;
    data(ii).hour = hour;
    data(ii).minute = minute;
    data(ii).second = second;
    data(ii).pressure = pressure;
    data(ii).humidity = humidity;
    data(ii).temp = temp;
    
%End loop over data files
end

%Make single arrays by appending run data
meas_datenum = [];
meas_temp = [];
for ii = 1 : c
    meas_datenum = [meas_datenum, datenum(data(ii).year, data(ii).month, data(ii).day, data(ii).hour, data(ii).minute, data(ii).second)];
    meas_temp = [meas_temp, data(ii).temp];
end

%Plot the history of the temperatures
temp_hist_plot_temphist(plt_file, HIST_NAME, meas_datenum, meas_temp);

%Find temperature excursions
peak_num = 0;
for ii = 126 : length(meas_temp) - 125
    found_peak = 1;
    if ((meas_temp(ii) < 22) || (meas_temp(ii) > 100))
        found_peak = 0;
    end
    for jj = -125 : 125  % 1 day
        if meas_temp(ii) < meas_temp(ii + jj)
            found_peak = 0;
        end
    end
    if found_peak == 1
        peak_num = peak_num + 1;
        peak_temp(peak_num) = meas_temp(ii);
        peak_datenum(peak_num) = meas_datenum(ii);
    end
end

%Write the excursions to the data file
temp_hist_dat_results(dat_file, peak_datenum, peak_temp);

%Save the results
save(mat_file, 'data', 'meas_datenum', 'meas_temp', 'peak_datenum', 'peak_temp');

%Save the temperature history figure
hgsave(fig_file);

%Done
