function pan5output(varargin)

% ========================================================================
% ====================== Panel for the outputs ===========================
% ========================================================================
% This is the GUI m-file to show that the panel relative to the outputs
%
%  $Id: pan5output.m,v 1.17 2008/12/16 19:30:26 nicola Exp $

global LTPDAoutvar

InputObjList=''; OutputObjList='';
UpdateListbox();
set(gcf,'NextPlot','new');

currPanel   = varargin{1};
panelDimens = get(currPanel, 'Position');
backColor   = get(currPanel, 'BackgroundColor');

    DataPanPos   = [20 panelDimens(4)-320 panelDimens(3)-40 285];
  hDataPanel    =  uipanel(...
                      'Title','Data Control Panel',...
                      'BackgroundColor',[1,1,1],...
                      'FontSize',7,...
                      'Units','pixels',...
                      'Position',DataPanPos);
    nbuttons    = 5;
    buttonWidth = (DataPanPos(3)-10*(nbuttons+1))/nbuttons;
    buttonPos   = [10 DataPanPos(4)-45 buttonWidth 25];
    % 'Export to workspace' button:
  uicontrol('Parent',hDataPanel,'Units','pixels','HorizontalAlignment','center','Position',buttonPos,'String','Export to workspace','FontSize',8,'Visible','on','Callback',@hExportButtonCallback,'Style','pushbutton','enable','on');
    buttonPos(1) = buttonPos(1)+buttonWidth+10;
    % 'Remove' button:
  uicontrol('Parent',hDataPanel,'Units','pixels','HorizontalAlignment','center','Position',buttonPos,'String','Remove','FontSize',8,'Visible','on','Callback',@hRemoveButtonCallback,'Style','pushbutton','enable','on');
    buttonPos(1) = buttonPos(1)+buttonWidth+10;
    % 'Send to repository' button:
  uicontrol('Parent',hDataPanel,'Units','pixels','HorizontalAlignment','center','Position',buttonPos,'String','Send to repository','FontSize',8,'Visible','on','Callback',@hClearButtonCallback,'Style','pushbutton','enable','off');
    buttonPos(1) = buttonPos(1)+buttonWidth+10;
    % 'Explore' button:
  uicontrol('Parent',hDataPanel,'Units','pixels','HorizontalAlignment','center','Position',buttonPos,'String','Explore','FontSize',8,'Visible','on','UserData',InputObjList,'Callback',@hExploreButtonCallback,'Style','pushbutton','enable','on');
%     buttonPos(1) = buttonPos(1)+buttonWidth+10;
%   hSaveOutButton =  uicontrol('Parent',hDataPanel,'Units','pixels','HorizontalAlignment','center','Position',buttonPos,'String','Save workspace','FontSize',8,'Visible','on','Enable','on','Callback',@SaveWorkspaceCallback,'Style','pushbutton');
    buttonPos(1) = buttonPos(1)+buttonWidth+10;
    % 'Clear all output' button:
  uicontrol('Parent',hDataPanel,'Units','pixels','HorizontalAlignment','center','Position',buttonPos,'String','Clear output','FontSize',8,'Visible','on','Enable','on','Callback',{@AskConfirm,'clear'},'Style','pushbutton');
    clear nbuttons buttonWidth buttonPos


    ntexts    = 2;
    textWidth = (DataPanPos(3)-10*(ntexts+1))/ntexts;
    textPos   = [10 DataPanPos(4)-80 textWidth 25];
  % hListAOText   =   uicontrol('Parent',hDataPanel,'BackgroundColor',get(hDataPanel,'BackgroundColor'),'HorizontalAlignment','center','Position',textPos,'String','Input:','FontName','Times New Roman','FontSize',8,'FontWeight','normal','Visible','on','Style','text');
    textPos(1) = textPos(1)+textWidth+10;
  hResultAOText   =   uicontrol('Parent',hDataPanel,'BackgroundColor',get(hDataPanel,'BackgroundColor'),'HorizontalAlignment','center','Position',textPos,'String','Output:','FontName','Times New Roman','FontSize',8,'FontWeight','normal','Visible','on','Style','text');
    clear ntexts textWidth textPos


    nlists    = 2;
    listWidth = (DataPanPos(3)-10*(nlists+1))/nlists;
    listPos   = [10 DataPanPos(4)-275 listWidth 200];
  % Info panel:
  uicontrol('Parent',hDataPanel,'BackgroundColor',[0.94,0.94,1],'Style','listbox','HorizontalAlignment', 'left','Fontsize', 8,'Units','pixels','Position',listPos,'Tag','infoPanel');
    listPos(1) = listPos(1)+listWidth+10;
  OutputObjList   =   uicontrol('Parent',hDataPanel,'BackgroundColor',[0.95,0.95,0.95],'HorizontalAlignment','center','Position',listPos,'String',listResults,'Value',[],'Max',10,'Min',1,'FontSize',8,'FontWeight','normal','Visible','on','Callback',@hResultListCallback,'Tag','OutputObjList','Style','listbox');
    hResultListCallback(OutputObjList,1)
    clear DataPanPos nlists listWidth listPos
    
    
%%
    %----------------------------------------------------------------------
    function UpdateListbox(varargin)
    % Updates the LTPDAoutvar listbox

         %==================================
         % Update the list of results AOs
         xx = size(LTPDAoutvar,1);
         listResults = cell(xx,1);
         if xx>0
             for j=1:xx
                 listResults{j,1} = num2str(j);
                 [rows,columns] = size(LTPDAoutvar{j,1});
                 if (rows>1 && columns==1) || (rows==1 && columns>1), listResults{j,1} = [listResults{j,1}, ' .(Vector ',num2str(rows),'x',num2str(columns),') '];
                 elseif rows>1 && columns>1, listResults{j,1} = [listResults{j,1}, ' .(Matrix ',num2str(rows),'x',num2str(columns),') '];
                 end
                 switch class(LTPDAoutvar{j,1})
                    case 'ao'
                       anobject  = LTPDAoutvar{j,1};
                       aoname    = anobject.name;
                       aocreated = char(anobject.created);
                       listResults{j,1} = [listResults{j,1}, ' . AO .' , aoname , '__' , aocreated];
                    case 'plist'
                       paramNumb = nparams(LTPDAoutvar{j,1});
                       objcreated = char(LTPDAoutvar{j,1}.created);
                       listResults{j,1}=[listResults{j,1}, ' . PLIST .',num2str(paramNumb),' params','__',objcreated];
                    case {'pzmodel','miir','mfir'}
                       objcreated = char(LTPDAoutvar{j,1}.created);
                       listResults{j,1}=[listResults{j,1}, ' . ',upper(class(LTPDAoutvar{j,1})),' .__',objcreated];
                    case 'double'
                       if numel(LTPDAoutvar{j,1})==1, objclass  = ' . Scalar .__ ';
                       elseif size(LTPDAoutvar{j,1},1)==1 || size(LTPDAoutvar{j,1},2)==1, objclass = ' . Vector .__ ';
                       else objclass = ' . Matrix .__ ';
                       end
                       listResults{j,1}=[listResults{j,1}, objclass, mat2str(LTPDAoutvar{j,1})];
                    otherwise
                       listResults{j,1}=[listResults{j,1}, ' . ',class(LTPDAoutvar{j,1})];
                 end
             end
             for j=xx:-1:1, if isempty(listResults{j,1}), listResults(j,:)=[]; end; end
         else
             listResults{1,1}='The workspace is empty';
         end
         
         OutputObjList = findobj('Tag','OutputObjList');
         if ~isempty(OutputObjList)
             set(OutputObjList,'Value',1)
             set(OutputObjList,'String',listResults)
         end
         
         %==================================

    end
    %----------------------------------------------------------------------

    %----------------------------------------------------------------------
    function hResultListCallback(hObject, varargin)
    % This callback is called whenever the user double click upon one of
    % the AOs in use.
        if ~isempty(varargin{1}) && varargin{1}==1 && size(LTPDAoutvar,1)>0
                val = get(hObject, 'Value');
                if length(val) == 1
                    objLines = get(hObject, 'String');
                    if isempty(objLines)
                        objtxt = '';
                    else
                        objnumb = str2double(deblank(strtok(objLines{val})));
                        objtxt = display(LTPDAoutvar{objnumb});
                    end
                else
                    objtxt = '';
                end
                set(findobj('Tag', 'infoPanel'), 'String', objtxt)
        elseif size(LTPDAoutvar,1)>0
            if strcmp(get(gcf,'SelectionType'),'normal')
                val = get(hObject, 'Value');
                if length(val) == 1
                    objLines = get(hObject, 'String');
                    objnumb = str2double(deblank(strtok(objLines{val})));
                    objtxt = display(LTPDAoutvar{objnumb});
                else
                    objtxt = '';
                end
                set(findobj('Tag', 'infoPanel'), 'String', objtxt)
            end
            if strcmp(get(gcf,'SelectionType'),'open') && ~isempty(get(hObject, 'String'))
                try %#ok<ALIGN>
                    currIndex = get(hObject,'Value');
                    figure
                    plot(LTPDAoutvar{currIndex,1});
                catch
                    close(gcf)
                end
            end
        end
         
    end
    %----------------------------------------------------------------------

%%
%     %----------------------------------------------------------------------
%     function SaveWorkspaceCallback(varargin)
%     % Callback function: run when the user click the "Clear all data"
%     % button
% 
%          try
%              [FileName,PathName,FilterIndex] = uiputfile('*.mat','Save Workspace As');
%              if ~isa(FileName,'double'), save(strcat(PathName,FileName),'LTPDAoutvar'); disp('Workspace saved'); end
%              disp('Output saved')
%          catch
%          end
%     end
%     %----------------------------------------------------------------------

    %----------------------------------------------------------------------
    function AskConfirm(varargin)
    % Whenever the user click the Reset Parameters button
    
         if strcmp(varargin{3},'close'), set(gcf,'Visible','off'); end
         
       % Ask for confirmation:
         screenSize = get(0,'ScreenSize');
         backColor   = [1 1 1];
         position   = [(screenSize(3)-250)/2,(screenSize(4)-160)/2,250,160];
         confirmFig = figure('Position',position,'Name','Please confirm','Tag','ConfirmReset','Resize','off','NumberTitle','off','Toolbar','none','Menubar','none');
       % Text
         uicontrol('Parent',confirmFig,'BackgroundColor',backColor,'HorizontalAlignment','center','Position',[0 position(4)-40 position(3) 20],'String','Are you sure?','FontName','Times New Roman','FontSize',13,'FontWeight','normal','Visible','on','Style','text');
       % Button Yes
         dimension = position;
         logosize = [77 95];
         dimension = [50 , dimension(4)-logosize(2)-50 , logosize];
         yesbut = axes('Parent',confirmFig,'Units','pixels','Position',dimension,'Tag','Yes');
         image(imread('buttonyes2.jpg'),'Parent',yesbut,'ButtonDownFcn','set(findobj(''Tag'',''ConfirmReset''),''UserData'',0); uiresume;','Tag','YesButton');
         axis(yesbut,'off');
       % Button No
         dimension = position;
         logosize = [77 95];
         dimension = [127 , dimension(4)-logosize(2)-50 , logosize];
         nobut = axes('Parent',confirmFig,'Units','pixels','Position',dimension,'Tag','No');
         image(imread('buttonno2.jpg'),'Parent',nobut,'ButtonDownFcn','set(findobj(''Tag'',''ConfirmReset''),''UserData'',1); uiresume;','Tag','NoButton');
         axis(nobut,'off');

         uiwait;
         
         if get(confirmFig,'UserData'), delete(confirmFig); set(findobj('Tag','LTPDAGUI'),'Visible','on'); return; end
         
         if strcmp(varargin{3},'close')
            delete(confirmFig);
            disp('Closing LTPDA GUI...');
            delete(timerfindall);
            clear global LTPDAinvar LTPDAoutvar;
            setappdata(0,'ltpda_repo_user',''); setappdata(0,'ltpda_repo_pass','');
            closereq
         elseif strcmp(varargin{3},'clear')
            delete(confirmFig);
            LTPDAoutvar={};
            set(OutputObjList,'Value',1)
            set(findobj('Tag', 'infoPanel'), 'String', '')
            set_param(find_system(bdroot,'FindAll','on','Type','Annotation','Tag','ltpda model'),'UserData','');
            UpdateListbox();
         end
         
    end
    %----------------------------------------------------------------------
    
    %----------------------------------------------------------------------
    function hRemoveButtonCallback(varargin)   
    % Callback function: run when the user click the "Remove data" button

           index_selected = get(OutputObjList,'Value');
           listObjs = get(OutputObjList,'String');
           if ~strcmp(listObjs,'The memory is empty')
               for i=1:numel(index_selected)
                   objSelect = str2double(strtok(listObjs{index_selected(i),1},'.'));
                   LTPDAoutvar(objSelect,:) = [];
               end
               UpdateListbox();
           end
           set(findobj('Tag', 'infoPanel'), 'String', '')

    end
    %----------------------------------------------------------------------

    %----------------------------------------------------------------------
    function hExportButtonCallback(varargin)   
    % Callback function: run when the user click the "Remove data" button

         currSelObjs   = get(OutputObjList,'Value');
         listObjs = get(OutputObjList,'String');
         if ~strcmp(listObjs,'The memory is empty')
             selectedObjs  = {};
             for i=1:numel(currSelObjs)
                 objSelect = str2double(strtok(listObjs{currSelObjs(i),1},'.'));
                 selectedObjs = [selectedObjs,LTPDAoutvar(objSelect,1)];
             end
             if ~isempty(selectedObjs)
                 for i=1:numel(selectedObjs)
                     objName = [class(selectedObjs{i}),'_',selectedObjs{i}.name];
                     objName = genvarname(objName,evalin('base','who'));
                     assignin('base', objName, selectedObjs{i});
                     disp(['Saved to workspace with name ',objName])
                 end
             end
         end
         
    end
    %----------------------------------------------------------------------

    %----------------------------------------------------------------------
    function hExploreButtonCallback(varargin)   
    % Callback function: run when the user click the "Update list" button

         currSelObjs   = get(OutputObjList,'Value');
         listObjs = get(OutputObjList,'String');
         if ~strcmp(listObjs,'The memory is empty')
             selectedObjs  = {};
             for i=1:numel(currSelObjs)
                 objSelect = str2double(strtok(listObjs{currSelObjs(i),1},'.'));
                 selectedObjs = [selectedObjs,LTPDAoutvar(objSelect,1)];
             end

             if ~isempty(selectedObjs)
                 ltpda_explorer(selectedObjs);
             else
                 ltpda_explorer(LTPDAoutvar);
             end

             UpdateListbox();
         end

    end
    %----------------------------------------------------------------------


%%
end