% AINS meas residuals with standard deviation envelopes

function generic_plot_kf_meas_env( action,      ...
                                   path,        ...
                                   kernel,      ...
                                   start_time,  ...
                                   fignum,      ...
                                   prefix1,     ...
                                   prefix2,     ...
                                   fig_title)

persistent figure_params %an array holding a structure for each instance call of this routine

thismfile=mfilename;

switch action
    
    case 'start'
        
        figure_params(fignum).h_fig_listbox = -1;

        %------------------------------------------------------------------
        % Load the display index data
        
        display_index = load_display_index(path, kernel); % External function
        
        %------------------------------------------------------------------
        % Load the data
        
        % Data is stored with rows of measurements and columns for each parameter
        % Time is the first column follow by a variable number of columns as 
        % given in display_index.N
        
        suffix = '.out';
        filename1 = [path prefix1 kernel suffix];
        filename2 = [path prefix2 kernel suffix];
        
        if test_file(filename1) == 0                   	% External function
            return;
        end

        if test_file(filename2) == 0                 	% External function
            return;
        end
        
        data = load_data(filename1,display_index.M);  	% External function
        data_sd = load_data(filename2,display_index.M);	% External function
        
        if isscalar(data) || isscalar(data_sd)
          return
        end
        
        %------------------------------------------------------------------
        % get Figure and Y-axis label captions
        
        figure_caption = get_kf_meas_figure_captions; 	% External function
        
        % Bring up new figure window and set its properties
        
        new_plot_figure(fignum,fig_title,kernel);       % External function
        
        %------------------------------------------------------------------
        % plot the data
        
        figure_params(fignum).num_plots = 0;
        figure_params(fignum).current_plot_num = 1;
        figure_params(fignum).used_fig_captions ={'test'} ;  % allocate value as cell type

        for i=1:display_index.M
            figure_params(fignum).num_plots = figure_params(fignum).num_plots + 1;
            data_index = i+1;
            label_index = display_index.selected_measurements(i);
            
            %keep track of labels actually used for list box
            meas_caption = sprintf('Meas(%i): %s',label_index,figure_caption{label_index});
            figure_params(fignum).used_fig_captions(figure_params(fignum).num_plots) = {meas_caption};

            %bring up new axis
            figure_params(fignum).axis_handle(figure_params(fignum).num_plots) = axes;        
            
            %plot the data
            figure_params(fignum).plot_handle(figure_params(fignum).num_plots,:) = plot_data(data, data_sd, start_time, data_index,...
                char(figure_params(fignum).used_fig_captions(figure_params(fignum).num_plots)));     %internal function
        
            %if not first plot hide the new plot
            if figure_params(fignum).num_plots > 1
                set(figure_params(fignum).axis_handle(figure_params(fignum).num_plots),'visible','off')
                for j=1:3
                    set(figure_params(fignum).plot_handle(figure_params(fignum).num_plots,j),'visible','off')
                end
            end
        end

        %set active axis
        axes(figure_params(fignum).axis_handle(figure_params(fignum).current_plot_num))
        
        %create buttons
        
        hleft = uicontrol('style','push','pos',[10 50 20 20],'TooltipString','Cycle left',...
            'callback',[ thismfile '(''left'');' ],'fontname','symbol','string',char(172));
        hright = uicontrol('style','push','pos',[10 30 20 20],'TooltipString','Cycle right',...
            'callback',[ thismfile '(''right'');' ],'fontname','symbol','string',char(174));
        hlist = uicontrol('style','push','pos',[10 10 40 20],'TooltipString','Plot selection list',...
            'callback',[ thismfile '(''list'');' ],'string','List');

        % only need the one zoom -need to be after buttons for Matlab 7
        zoom on

    case 'left'

        fignum = str2num(get(gcf,'Tag'));
        figure_params(fignum).current_plot_num = figure_params(fignum).current_plot_num - 1;
        if figure_params(fignum).current_plot_num < 1
            % Wrap to last plot
            figure_params(fignum).current_plot_num = figure_params(fignum).num_plots;
        end
        
        for i=1:figure_params(fignum).num_plots
            set(figure_params(fignum).axis_handle(i),'visible','off')
            for j=1:3
                set(figure_params(fignum).plot_handle(i,j),'visible','off')
            end
        end
        set(figure_params(fignum).axis_handle(figure_params(fignum).current_plot_num),'visible','on')
        for j=1:3
            set(figure_params(fignum).plot_handle(figure_params(fignum).current_plot_num,j),'visible','on')
        end
        axes(figure_params(fignum).axis_handle(figure_params(fignum).current_plot_num))

    case 'right'

        fignum = str2num(get(gcf,'Tag'));
        figure_params(fignum).current_plot_num = figure_params(fignum).current_plot_num + 1;
        if figure_params(fignum).current_plot_num > figure_params(fignum).num_plots
            % Wrap to first plot
            figure_params(fignum).current_plot_num = 1;
        end
        
        for i=1:figure_params(fignum).num_plots
            set(figure_params(fignum).axis_handle(i),'visible','off')
            for j=1:3
                set(figure_params(fignum).plot_handle(i,j),'visible','off')
            end
        end
        set(figure_params(fignum).axis_handle(figure_params(fignum).current_plot_num),'visible','on')
        for j=1:3
            set(figure_params(fignum).plot_handle(figure_params(fignum).current_plot_num,j),'visible','on')
        end
        axes(figure_params(fignum).axis_handle(figure_params(fignum).current_plot_num))
         
    case 'list'

       fignum = str2num(get(gcf,'Tag'));
       h_fig = gcf;
       if ishandle(figure_params(fignum).h_fig_listbox) == 0
            figure_params(fignum).h_fig_listbox = figure('name',['Plot Selection List'],'NumberTitle', 'off','Menu','none');     % ' char(figure_caption(i))]);
            set(figure_params(fignum).h_fig_listbox,'units','characters');
            set(gcf,'Tag',num2str(fignum));
    
%            apos=get(figure_params(fignum).h_fig_listbox,'pos');

            %get location of parent window
            set(h_fig,'units','characters');
            apos=get(h_fig,'pos');
            %set vertical position of list box
            top = apos(2) + apos(4);  % bottom+ height
            temp_num_plot = figure_params(fignum).num_plots;
            if temp_num_plot > 30
                temp_num_plot = 30;  %limit length of window and list box so that it doesnt extend beyond bottom of screen
            end
            new_height = temp_num_plot + 7;
            new_bottom = top - new_height;
            apos(2) = new_bottom;
            apos(4) = new_height;
            %set horiz position
            new_left = apos(1) + 0.25*apos(3); % left +25% of width
            new_width = 44;
            apos(1) = new_left;
            apos(3) = new_width;
            set(figure_params(fignum).h_fig_listbox,'pos',apos);
    
            figure_params(fignum).h_listbox = uicontrol('style','listbox','units','characters','pos',[1 1 new_width-3 new_height-6 ],...
                'TooltipString','List box','callback',[ thismfile '(''listbox'');' ]);
            set(figure_params(fignum).h_listbox,'units','normalized');
            set(figure_params(fignum).h_listbox,'value',figure_params(fignum).current_plot_num);
            set(figure_params(fignum).h_listbox,'string',figure_params(fignum).used_fig_captions);
            
            h_OK = uicontrol('style','push','units','characters','pos',[5 new_height - 4 10 3],'TooltipString','OK',...
                'callback',[ thismfile '(''ListBox_OK'');' ],'string','OK');
            set(h_OK,'units','normalized');
            
            h_Cancel = uicontrol('style','push','units','characters','pos',[(new_width/2)+5 new_height - 4 10 3],'TooltipString','Cancel',...
                'callback',[ thismfile '(''ListBox_Cancel'');' ],'string','Cancel');
            set(h_Cancel,'units','normalized');
            figure_params(fignum).new_plot_num = 0;
        end
        
    case 'listbox'

        fignum = str2num(get(gcf,'Tag'));

        selectiontype = get(gcbf,'SelectionType');
        if selectiontype(1)=='o'
            figure_params(fignum).new_plot_num = get(figure_params(fignum).h_listbox,'value');
            figure_params(fignum).current_plot_num = update_plot(figure_params(fignum).new_plot_num,figure_params(fignum).plot_handle,...
                figure_params(fignum).axis_handle , figure_params(fignum).num_plots);
            close(figure_params(fignum).h_fig_listbox);
            figure_params(fignum).h_fig_listbox = -1;
        end    
        
        if selectiontype(1)=='n'
            figure_params(fignum).new_plot_num = get(figure_params(fignum).h_listbox,'value');
        end    

    case 'ListBox_OK'
 
        fignum = str2num(get(gcf,'Tag'));
        if figure_params(fignum).new_plot_num ~= 0
            figure_params(fignum).current_plot_num = update_plot(figure_params(fignum).new_plot_num,figure_params(fignum).plot_handle,...
                figure_params(fignum).axis_handle , figure_params(fignum).num_plots);
        end
        close(figure_params(fignum).h_fig_listbox);
        figure_params(fignum).h_fig_listbox = -1;
            
    case 'ListBox_Cancel'

        fignum = str2num(get(gcf,'Tag'));
        close(figure_params(fignum).h_fig_listbox);
        figure_params(fignum).h_fig_listbox = -1;
        
end %switch


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%function update_plot(new_plot_num)

%global plot_handle axis_handle current_plot_num num_plots

function current_plot_num = update_plot(new_plot_num,plot_handle, axis_handle , num_plots)

    if (new_plot_num > 0) && (new_plot_num <= num_plots)
    
        current_plot_num = new_plot_num;
        for i=1:num_plots
            set(axis_handle(i),'visible','off')
            for j=1:3
                set(plot_handle(i,j),'visible','off')
            end
        end
        set(axis_handle(current_plot_num),'visible','on')
        for j=1:3
            set(plot_handle(current_plot_num,j),'visible','on')
        end
        axes(axis_handle(current_plot_num))
        
    end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function plot_handle = plot_data(data,data_sd,start_time,data_index,used_fig_captions)
    
%    count = count + 1;
%    fig(count)=figure;

time = data(:,1);
if start_time < 0.0
    start_time = time(1); 
end;

%figure

plot_handle(1,1) = plot(time-start_time,data(:,data_index),'k');
hold on
plot_handle(1,2) = plot(time-start_time, data_sd(:,data_index),'r--');
plot_handle(1,3) = plot(time-start_time,-data_sd(:,data_index),'r--');
hold off

%ylabel(used_fig_captions );
x_label_caption = sprintf('Time in seconds starting at %i',start_time);
xlabel(x_label_caption);
title(used_fig_captions);
%axis('tight')
