close all
clear h
%-------------------------------------------------------
% Create a figure
%-------------------------------------------------------
	figure('NumberTitle','off', ...   % don't show the figure and number
				 'Resize','off', ...
				 'NumberTitle','off', ...
				 'Name','GUI Design with Octave Example', ... % 
			     'Resize','on', ...
				 'toolbar', 'none', ...
                 'Color',get(0,'DefaultUIControlBackgroundColor'));
h.ax = axes ('position', [0.05 0.42 0.5 0.5]);
h.fcn = @(x) polyval([-0.1 0.5 3 0], x);

function update_plot (obj, init = false)
  % gcbo holds the handle of the control
  h = guidata (obj);
  replot = false;
  recalc = false;
  switch (gcbo)
    case {h.print_pushbutton}
		% [filename, pathname] =  uiputfile ({'*.png';'*.jpg';'*.pdf'}) ;
      [filename, pathname] =  uiputfile ('*.png') ;
	  if isequal(filename,0) || isequal(pathname,0) % check valid path or file name
		errordlg('No Print!','File Error: No valid path/filename');
	  else
		 print ([ pathname,filename ]); % print plot in chosen path
	 end ;
    case {h.grid_checkbox}
      v = get (gcbo, 'value');
      grid (merge (v, 'on', 'off'));
    case {h.minor_grid_toggle}
      v = get (gcbo, 'value');
      grid ('minor', merge (v, 'on', 'off'));
    case {h.plot_title_edit}
      v = get (gcbo, 'string');
      set (get (h.ax, 'title'), 'string', v);
	 
    case {h.linecolor_radio_blue }
		if (~strncmpi(version, '4.2.0',4)) % with which Octave Version this m file runs	
		set (h.linecolor_radio_red, 'value', 0);
		replot = true;
		end;
    case {h.linecolor_radio_red }
		if (~strncmpi(version, '4.2.0',4)) % with which Octave Version this m file runs	
			set (h.linecolor_radio_blue, 'value', 0);
			replot = true;
	   end;
    case {h.bg }
      replot = true;
    case {h.linestyle_popup, h.markerstyle_list}
      replot = true;
    case {h.noise_slider}
      recalc = true;
	case {h.contextmenu_forplot, h.m1}
		setMaker1(h);
		replot = true;
	case {h.contextmenu_forplot, h.m2}
		setMaker2(h) ;
		replot = true;
	case {h.contextmenu_deleteMaker, h.m3}
         deleteMaker(h);
		 replot = true;
  end;

  if (recalc || init)
    x = linspace (-4, 9);
    noise = get (h.noise_slider, 'value');
    set (h.noise_label, 'string', sprintf ('Noise: %.1f%%', noise * 100));
    y = h.fcn (x) + 5 * noise * randn (size (x));
    if (init)
      h.plot = plot (x, y, 'b');
	  ypos = get(h.ax,'YLim');  %# Get the range of the y axis
	  textinplot.maker1 = 0 ;
	  textinplot.maker2 = 0 ;
	  textinplot.text_in_plt = 'Press left MouseButton to set Maker at the plot!';
	  textinplot.texthandel = text( -4, ypos(2)-2, textinplot.text_in_plt , 'Parent', h.ax);	  
      guidata (obj, h);
	  set (h.plot, 'uicontextmenu', h.contextmenu_forplot) ; % connect the contextmenu m1, m2 to the plot data line
	  set (h.ax  , 'uicontextmenu', h.contextmenu_deleteMaker) ; % connect the contextmenu m3 to the axis 
    else
      set (h.plot, 'ydata', y);
	  textinplot = get(gcf,'UserData');
	  delete(textinplot.texthandel);
	  ypos = get(h.ax,'YLim');  %# Get the range of the y axis
	  textinplot.texthandel = text( -4, ypos(2)-2, textinplot.text_in_plt, 'Parent', h.ax);	  
    end;
	set(gcf,'UserData',textinplot);
  end;

  if (replot)
    cb_red = get (h.linecolor_radio_red, 'value');
    lstyle = get (h.linestyle_popup, 'string'){get (h.linestyle_popup, 'value')};
	lstyle = strtrim (lstyle(1:2));
    mstyle = get (h.markerstyle_list, 'string'){get (h.markerstyle_list, 'value')};
    if (strfind (mstyle, 'none'))
      mstyle = 'none';
    else
      mstyle = mstyle(2);
    endif
  
    set (h.plot, 'color', merge (cb_red, [1 0 0 ], [0 0 1]),
                 'linestyle', lstyle,
                 'marker', mstyle);	
	textinplot = get(gcf,'UserData'); % load from figures UserData
    delete(textinplot.texthandel); % delete the text to replace
	ypos = get(h.ax,'YLim');  %# Get the range of the y axis
	textinplot.texthandel = text( -4, ypos(2)-2, textinplot.text_in_plt, 'Parent', h.ax);	
	set(gcf,'UserData',textinplot);	% save in figures UserData
  end;
end;

% plot title
h.plot_title_label = uicontrol ('style', 'text',
                                'units', 'normalized',
                                'string', 'plot title: (text)',
                                'horizontalalignment', 'left',
                                'position', [0.6 0.85 0.35 0.08]);

h.plot_title_edit = uicontrol ('style', 'edit',
                               'units', 'normalized',
                               'string', 'Please fill me! (edit)',
                               'callback', @update_plot,
                               'position', [0.6 0.80 0.35 0.06]);

% grid
h.grid_checkbox = uicontrol ('style', 'checkbox',
                             'units', 'normalized',
                             'string', 'show grid\n(checkbox)',
                             'value', 0,
                             'callback', @update_plot,
                             'position', [0.6 0.65 0.35 0.09]);

h.minor_grid_toggle = uicontrol ('style', 'togglebutton',
                                 'units', 'normalized',
                                 'string', 'minor\n(togglebutton)',
                                 'callback', @update_plot,
                                 'value', 0,
                                 'position', [0.77 0.65 0.18 0.09]);

% print figure
h.print_pushbutton = uicontrol ('style', 'pushbutton',
                                'units', 'normalized',
                                'string', 'print plot\n(pushbutton)',
                                'callback', @update_plot,
                                'position', [0.6 0.45 0.35 0.09]);
% noise
h.noise_label = uicontrol ('style', 'text',
                           'units', 'normalized',
                           'string', 'Noise:',
                           'horizontalalignment', 'left',
                           'position', [0.05 0.3 0.35 0.08]);

h.noise_slider = uicontrol ('style', 'slider',
                            'units', 'normalized',
                            'string', 'slider',
                            'callback', @update_plot,
                            'value', 0.4,
                            'position', [0.05 0.25 0.35 0.06]);



if (strncmpi(version, '4.2.0',4)) % with which Octave Version this m file runs							   
h.bg = uibuttongroup('Visible','on',...
                     'Title','Linecolor:',...
                     'Position',[0.04 0.01 0.18 0.22], ... % [0.58 0.04 0.38 0.26]
                     'SelectionChangedFcn', @update_plot
				     );
% connect the radiobuttons with the uibuttongroup's handle  h.bg						   
h.linecolor_radio_blue = uicontrol (h.bg,'style', 'radiobutton',
                                    'units', 'normalized',
                                    'string', 'blue',
                                    'callback', @update_plot,
                                    'position', [0.05 0.08 1 1.1]);

h.linecolor_radio_red = uicontrol (h.bg, 'style', 'radiobutton',
                                   'units', 'normalized',
                                   'string', 'red',
                                   'callback', @update_plot,
                                   'value', 0,
                                   'position', [0.05 0.02 1 0.4]);					 
else
% linecolor
h.linecolor_label = uicontrol ('style', 'text',
                               'units', 'normalized',
                               'string', 'Linecolor:',
                               'horizontalalignment', 'left',
                               'position', [0.05 0.12 0.35 0.08]);

h.linecolor_radio_blue = uicontrol ('style', 'radiobutton',
                                    'units', 'normalized',
                                    'string', 'blue',
                                    'callback', @update_plot,
                                    'position', [0.05 0.08 0.15 0.04]);

h.linecolor_radio_red = uicontrol ('style', 'radiobutton',
                                   'units', 'normalized',
                                   'string', 'red',
                                   'callback', @update_plot,
                                   'value', 0,
                                   'position', [0.05 0.02 0.15 0.04]);
h.bg = []; % empty handle to prevent error message in 4.03, so m file runs in both
end;							   


% linestyle
h.linestyle_label = uicontrol ('style', 'text',
                               'units', 'normalized',
                               'string', 'Linestyle:',
                               'horizontalalignment', 'left',
                               'position', [0.25 0.12 0.35 0.08]);

h.linestyle_popup = uicontrol ('style', 'popupmenu',
                               'units', 'normalized',
                               'string', {'-  solid lines',
                                          '-- dashed lines',
                                          ':  dotted lines',
                                          '-. dash-dotted lines'},
                               'callback', @update_plot,
                               'position', [0.25 0.05 0.3 0.06]);

% markerstyle
h.markerstyle_label = uicontrol ('style', 'text',
                                 'units', 'normalized',
                                 'string', 'Marker style:',
                                 'horizontalalignment', 'left',
                                 'position', [0.58 0.3 0.35 0.08]);

h.markerstyle_list = uicontrol ('style', 'listbox',
                                'units', 'normalized',
                                'string', {'none',
                                           '+  crosshair',
                                           'o  circle',
                                           '*  star',
                                           '.  point',
                                           'x  cross',
                                           's  square',
                                           'd  diamond',
                                           '^  upward-facing triangle',
                                           'v  downward-facing triangle',
                                           '>  right-facing triangle',
                                           '<  left-facing triangle',
                                           'p  pentagram',
                                           'h  hexagram'},
                                'callback', @update_plot,
                                'position', [0.58 0.04 0.38 0.26]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% generate a cotexmenu with 2 entries m1 and m2,
% above in init connect this context menu with the plottet data line
h.contextmenu_forplot   = uicontextmenu(gcf);
h.m1 = uimenu('parent', h.contextmenu_forplot, 'label', 'Maker 1' , 'callback', @update_plot);
h.m2 = uimenu('parent', h.contextmenu_forplot, 'label', 'Maker 2' , 'callback', @update_plot);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% generate a cotexmenu with one entry m3
% above in init connect this context menu with the plottet data line
h.contextmenu_deleteMaker   = uicontextmenu(gcf);
h.m3 = uimenu('parent', h.contextmenu_deleteMaker, 'label', 'Delete all Maker' , 'callback', @update_plot);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% create a toolbar to put some Buttons there...
h.tb = uitoolbar(gcf);
% create a 19x19x3 black and white square as mini pictures
img_black =zeros(19,19,3);
img_white =ones(19,19,3);
img_random =rand(19,19,3);
% Create a uipushtool in the toolbar -> with tooltip Use Callback
h.tb_pushbutton = uipushtool(h.tb,'TooltipString','simply black pushbutton in toolbar',...
							 'ClickedCallback', 'TBPushFunc', 'cdata', img_black);
% another one
h.tb_pushbutton2 = uipushtool(h.tb,'TooltipString','simply white pushbutton in toolbar',...
                              'ClickedCallback', 'TBPushFunc2', 'cdata', img_random);
% read a icon or a picture to fill the next togglebutton							  
imgoctv = imread(fullfile(matlabroot,...
            'share','icons', 'hicolor', '16x16', 'apps','octave.png'));
imgoctv = double(imgoctv); % convert to double neccessary
							  
% add uitoggletool button to toolbar, with small icon inside
h.tb_togglebutton = uitoggletool (h.tb,'TooltipString','Toggle Button, see in command window',...
                                  'ClickedCallback', 'TBTOGGLEFunc', 'cdata', imgoctv);

% set (gcf, 'color', get(0, 'defaultuicontrolbackgroundcolor'));
guidata (gcf, h);
update_plot (gcf, true);






%%================================================================
%%=====================  nested functions   ======================
%%================================================================
    % set a maker 1 on mouse position
	function setMaker1(h)
        mouse = get(gca,'currentpoint'); % get the mouse position in the plot
		if ~isfield( h, 'maker1')
            h.maker1 = text( mouse(1,1),mouse(1,2), 'M1', 'Parent', h.ax); % set a text on the current mouse position, parent is current axis
	    else
            set(h.maker1,'Position', [ mouse(1,1)  mouse(1,2)] ,'String', 'M1'); % change the positon of the Maker whe nexists already
        end ;
		textinplot = get(gcf,'UserData'); % load from figures UserData
		textinplot.mouse1pos = mouse ;
		if(textinplot.maker2 == 0)
			textinplot.text_in_plt = sprintf('Maker1 : x = %d y= %d', mouse(1,1) , mouse(1,2)) ;
		else
			textinplot.text_in_plt = sprintf('Maker1 : x = %d y= %d\nMaker2 : x = %d y= %d', textinplot.mouse1pos(1,1), textinplot.mouse1pos(1,2), ...
																                             textinplot.mouse2pos(1,1), textinplot.mouse2pos(1,2)) ;
		end;
		textinplot.maker1 = 1 ;
		set(gcf,'UserData',textinplot);
		% next save handler changes, otherwise maker handles not deleted, trouble later
		guidata (gcf, h) ;
	end;  % end of function setMaker1(h)
%%================================================================
    % set a maker 2 on mouse position  
 	function setMaker2(h)
        mouse = get(gca,'currentpoint'); % get the mouse position in the plot
        if ~isfield( h, 'maker2') % maker text exsiting already?
		    % generate a text on the current mouse position, parent is current axis
            h.maker2 = text( mouse(1,1),mouse(1,2), 'M2', 'Parent', h.ax); 
	    else
			% change the positon of the Maker whe nexists already
            set(h.maker2,'Position', [ mouse(1,1)  mouse(1,2)] ,'String', 'M2'); 
        end ;
		textinplot = get(gcf,'UserData');
		textinplot.mouse2pos = mouse ;
		if(textinplot.maker1 == 0)
			textinplot.text_in_plt = sprintf('Maker2 : x = %d y= %d', mouse(1,1) , mouse(1,2)) ;
		else
			textinplot.text_in_plt = sprintf('Maker1 : x = %d y= %d\nMaker2 : x = %d y= %d', textinplot.mouse1pos(1,1), textinplot.mouse1pos(1,2), ...
																                             textinplot.mouse2pos(1,1), textinplot.mouse2pos(1,2)) ;
		end;
		textinplot.maker2 = 1 ;
		set(gcf,'UserData',textinplot);
		% next save handler changes, otherwise maker handles not deleted, trouble later
		guidata (gcf, h) ;% save changes to h
	end;  % end of function setMaker2(h)
%%================================================================
    % delete  maker
 	function deleteMaker(h)
			if (isfield(h, 'maker1'))    % maker text exsiting at all?
                delete( h.maker1);       % delete maker from plot
				h = rmfield(h,'maker1'); % delete text handle from h
            end;
		    if (isfield(h, 'maker2'))    % maker text exsiting at all?
                delete( h.maker2);       % delete maker from plot
				h = rmfield(h,'maker2'); % delete text handle from h
            end;
		textinplot.maker1 = 0 ;
		textinplot.maker2 = 0 ;
		textinplot = get(gcf,'UserData');
		textinplot.text_in_plt = 'Press left MouseButton to set Maker at the plot!';
		set(gcf,'UserData',textinplot);
		guidata (gcf, h) ; % save changes to h, otherwise maker handles not deleted inside
	end;  % end of function setMaker2(h)
%%================================================================
    % When on Toolbarr the pushbutton
 	function TBPushFunc()
		% Construct a questdlg with three options
		choice = questdlg('Sure, the white Button?', ...
					'Your Question Dialogue!', ...
					'Yeah..','Rather Black','No One','No One');
		% Handle response
		switch choice
			case 'Yeah..'
				disp([choice ' ...so boring']);
			case 'Rather Black'
				disp([choice ' good choise']);
			case 'No One'
				disp('Ok, maybe next time.');
		end
	
	end;  % end of function TBPushFunc()	
%%================================================================
    % When on Toolbarr the white pushbutton
 	function TBPushFunc2()
		if (strncmpi(version, '4.2.0',4)) % with which Octave Version this m file runs
			d = dialog('Position',[300 300 400 150],'Name','Dialogue GUI in Nested Function TBPushFunc2');
			txt = uicontrol('Parent',d,...
						'Style','text',...
						'Position',[20 80 340 40],...
						'String','You can create another GUI here');
			
			btn = uicontrol('Parent',d,...
						'Position',[85 20 150 25],...
						'String','Close',...
						'Callback','delete(gcf)');
		else  % because dialog doesnt work on Octave Versions lower 4.2
			msgbox(['This is Octave Version ', version], 'Button2pushed');
		
		end;
	end;  % end of function TBPushFunc2()
%%================================================================
    % Callback for the uitoggletool
 	function TBTOGGLEFunc()
		h= guidata (gcf) ; % get the all the handles
		toggleState = get(h.tb_togglebutton,'State') ; % state of the uitoggletool
		if (strcmp(toggleState, 'off')) % if not pressed
			disp('ToggleButton released')
	    else
			disp('ToggleButton pressed')
		end;
	end;  % end of function TBTOGGLEFunc()
%%================================================================
%%=====================  END OF FILE        ======================
%%================================================================