function el = export_contour_image_sequence(args)
%Subfunction to handle contour_image sequences within the
%structure_set module.  Uses the same layout and principle as the parent
%function.
%
%   This function takes a scanInfo object.
%
%JRA 06/23/06
%NAV 07/19/16 updated to dcm4che3
%   replaced ml2dcm_Element to data2dcmElement
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

%Init output element to empty.
el = [];

%Unpack input data.
tag                 = args.tag;
%scanInfo            = args.data{1};
contourS            = args.data{1};
template            = args.template;

switch tag
    case 528720     %0008,1150  Referenced SOP Class UID
        data = contourS.SOP_Class_UID;
        el = data2dcmElement(data, tag);

    case 528725     %0008,1155  Referenced SOP Instance UID
        data = contourS.SOP_Instance_UID;
        el = data2dcmElement(data, tag);

    case 528736     %0008,1160  Referenced Frame Number
        %Currently not implemented.

    otherwise
        warning(['No methods exist to populate DICOM structure_set module''s contour_image_sequence field ' dec2hex(tag,8) '.']);
end


function count = cprintf(style,format,varargin)
% CPRINTF displays styled formatted text in the Command Window
%
% Syntax:
%    count = cprintf(style,format,...)
%
% Description:
%    CPRINTF processes the specified text using the exact same FORMAT
%    arguments accepted by the built-in SPRINTF and FPRINTF functions.
%
%    CPRINTF then displays the text in the Command Window using the
%    specified STYLE argument. The accepted styles are those used for
%    Matlab's syntax highlighting (see: File / Preferences / Colors /
%    M-file Syntax Highlighting Colors), and also user-defined colors.
%
%    The possible pre-defined STYLE names are:
%
%       'Text'                 - default: black
%       'Keywords'             - default: blue
%       'Comments'             - default: green
%       'Strings'              - default: purple
%       'UnterminatedStrings'  - default: dark red
%       'SystemCommands'       - default: orange
%       'Errors'               - default: light red
%       'Hyperlinks'           - default: underlined blue
%
%       'Black','Cyan','Magenta','Blue','Green','Red','Yellow','White'
%
%    STYLE beginning with '-' or '_' will be underlined. For example:
%          '-Blue' is underlined blue, like 'Hyperlinks';
%          '_Comments' is underlined green etc.
%
%    STYLE beginning with '*' will be bold (R2011b+ only). For example:
%          '*Blue' is bold blue;
%          '*Comments' is bold green etc.
%    Note: Matlab does not currently support both bold and underline,
%          only one of them can be used in a single cprintf command. But of
%          course bold and underline can be mixed by using separate commands.
%
%    STYLE also accepts a regular Matlab RGB vector, that can be underlined
%    and bolded: -[0,1,1] means underlined cyan, '*[1,0,0]' is bold red.
%
%    STYLE is case-insensitive and accepts unique partial strings just
%    like handle property names.
%
%    CPRINTF by itself, without any input parameters, displays a demo
%
% Example:
%    cprintf;   % displays the demo
%    cprintf('text',   'regular black text');
%    cprintf('hyper',  'followed %s','by');
%    cprintf('key',    '%d colored', 4);
%    cprintf('-comment','& underlined');
%    cprintf('err',    'elements\n');
%    cprintf('cyan',   'cyan');
%    cprintf('_green', 'underlined green');
%    cprintf(-[1,0,1], 'underlined magenta');
%    cprintf([1,0.5,0],'and multi-\nline orange\n');
%    cprintf('*blue',  'and *bold* (R2011b+ only)\n');
%    cprintf('string');  % same as fprintf('string') and cprintf('text','string')
%
% Bugs and suggestions:
%    Please send to Yair Altman (altmany at gmail dot com)
%
% Warning:
%    This code heavily relies on undocumented and unsupported Matlab
%    functionality. It works on Matlab 7+, but use at your own risk!
%
%    A technical description of the implementation can be found at:
%    http://UndocumentedMatlab.com/blog/cprintf/
%
% Limitations:
%    1. In R2011a and earlier, a single space char is inserted at the
%       beginning of each CPRINTF text segment (this is ok in R2011b+).
%
%    2. In R2011a and earlier, consecutive differently-colored multi-line
%       CPRINTFs sometimes display incorrectly on the bottom line.
%       As far as I could tell this is due to a Matlab bug. Examples:
%         >> cprintf('-str','under\nline'); cprintf('err','red\n'); % hidden 'red', unhidden '_'
%         >> cprintf('str','regu\nlar'); cprintf('err','red\n'); % underline red (not purple) 'lar'
%
%    3. Sometimes, non newline ('\n')-terminated segments display unstyled
%       (black) when the command prompt chevron ('>>') regains focus on the
%       continuation of that line (I can't pinpoint when this happens).
%       To fix this, simply newline-terminate all command-prompt messages.
%
%    4. In R2011b and later, the above errors appear to be fixed. However,
%       the last character of an underlined segment is not underlined for
%       some unknown reason (add an extra space character to make it look better)
%
%    5. In old Matlab versions (e.g., Matlab 7.1 R14), multi-line styles
%       only affect the first line. Single-line styles work as expected.
%       R14 also appends a single space after underlined segments.
%
%    6. Bold style is only supported on R2011b+, and cannot also be underlined.
%
% Change log:
%    2015-06-24: Fixed a few discoloration issues (some other issues still remain)
%    2015-03-20: Fix: if command window isn't defined yet (startup) use standard fprintf as suggested by John Marozas
%    2012-08-09: Graceful degradation support for deployed (compiled) and non-desktop applications; minor bug fixes
%    2012-08-06: Fixes for R2012b; added bold style; accept RGB string (non-numeric) style
%    2011-11-27: Fixes for R2011b
%    2011-08-29: Fix by Danilo (FEX comment) for non-default text colors
%    2011-03-04: Performance improvement
%    2010-06-27: Fix for R2010a/b; fixed edge case reported by Sharron; CPRINTF with no args runs the demo
%    2009-09-28: Fixed edge-case problem reported by Swagat K
%    2009-05-28: corrected nargout behavior suggested by Andreas G?b
%    2009-05-13: First version posted on MathWorks File Exchange
%
% See also:
%    sprintf, fprintf

% License to use and modify this code is granted freely to all interested, as long as the original author is
% referenced and attributed as such. The original author maintains the right to be solely associated with this work.

% Programmed and Copyright by Yair M. Altman: altmany(at)gmail.com
% $Revision: 1.10 $  $Date: 2015/06/24 01:29:18 $

  persistent majorVersion minorVersion
  if isempty(majorVersion)
      %v = version; if str2double(v(1:3)) <= 7.1
      %majorVersion = str2double(regexprep(version,'^(\d+).*','$1'));
      %minorVersion = str2double(regexprep(version,'^\d+\.(\d+).*','$1'));
      %[a,b,c,d,versionIdStrs]=regexp(version,'^(\d+)\.(\d+).*');  %#ok unused
      v = sscanf(version, '%d.', 2);
      majorVersion = v(1); %str2double(versionIdStrs{1}{1});
      minorVersion = v(2); %str2double(versionIdStrs{1}{2});
  end

  % The following is for debug use only:
  %global docElement txt el
  if ~exist('el','var') || isempty(el),  el=handle([]);  end  %#ok mlint short-circuit error ("used before defined")
  if nargin<1, showDemo(majorVersion,minorVersion); return;  end
  if isempty(style),  return;  end
  if all(ishandle(style)) && length(style)~=3
      dumpElement(style);
      return;
  end

  % Process the text string
  if nargin<2, format = style; style='text';  end
  %error(nargchk(2, inf, nargin, 'struct'));
  %str = sprintf(format,varargin{:});

  % In compiled mode
  try useDesktop = usejava('desktop'); catch, useDesktop = false; end
  if isdeployed | ~useDesktop %#ok<OR2> - for Matlab 6 compatibility
      % do not display any formatting - use simple fprintf()
      % See: http://undocumentedmatlab.com/blog/bold-color-text-in-the-command-window/#comment-103035
      % Also see: https://mail.google.com/mail/u/0/?ui=2&shva=1#all/1390a26e7ef4aa4d
      % Also see: https://mail.google.com/mail/u/0/?ui=2&shva=1#all/13a6ed3223333b21
      count1 = fprintf(format,varargin{:});
  else
      % Else (Matlab desktop mode)
      % Get the normalized style name and underlining flag
      [underlineFlag, boldFlag, style, debugFlag] = processStyleInfo(style);

      % Set hyperlinking, if so requested
      if underlineFlag
          format = ['' format ''];

          % Matlab 7.1 R14 (possibly a few newer versions as well?)
          % have a bug in rendering consecutive hyperlinks
          % This is fixed by appending a single non-linked space
          if majorVersion < 7 || (majorVersion==7 && minorVersion <= 1)
              format(end+1) = ' ';
          end
      end

      % Set bold, if requested and supported (R2011b+)
      if boldFlag
          if (majorVersion > 7 || minorVersion >= 13)
              format = ['' format ''];
          else
              boldFlag = 0;
          end
      end

      % Get the current CW position
      cmdWinDoc = com.mathworks.mde.cmdwin.CmdWinDocument.getInstance;
      lastPos = cmdWinDoc.getLength;

      % If not beginning of line
      bolFlag = 0;  %#ok
      %if docElement.getEndOffset - docElement.getStartOffset > 1
          % Display a hyperlink element in order to force element separation
          % (otherwise adjacent elements on the same line will be merged)
          if majorVersion<7 || (majorVersion==7 && minorVersion<13)
              if ~underlineFlag
                  fprintf(' ');  %fprintf(' \b');
              elseif format(end)~=10  % if no newline at end
                  fprintf(' ');  %fprintf(' \b');
              end
          end
          %drawnow;
          bolFlag = 1;
      %end

      % Get a handle to the Command Window component
      mde = com.mathworks.mde.desk.MLDesktop.getInstance;
      cw = mde.getClient('Command Window');

      % Fix: if command window isn't defined yet (startup), use standard fprintf()
      if (isempty(cw))
         count1 = fprintf(format,varargin{:});
         if nargout
             count = count1;
         end
         return;
      end

      xCmdWndView = cw.getComponent(0).getViewport.getComponent(0);

      % Store the CW background color as a special color pref
      % This way, if the CW bg color changes (via File/Preferences),
      % it will also affect existing rendered strs
      com.mathworks.services.Prefs.setColorPref('CW_BG_Color',xCmdWndView.getBackground);

      % Display the text in the Command Window
      % Note: fprintf(2,...) is required in order to add formatting tokens, which
      % ^^^^  can then be updated below (no such tokens when outputting to stdout)
      count1 = fprintf(2,format,varargin{:});

      % Repaint the command window
      % awtinvoke(cmdWinDoc,'remove',lastPos,1);   % TODO: find out how to remove the extra '_'
      drawnow  % this is necessary for the following to work properly (refer to Evgeny Pr in FEX comment 16/1/2011)
      xCmdWndView.repaint;
      %hListeners = cmdWinDoc.getDocumentListeners; for idx=1:numel(hListeners), try hListeners(idx).repaint; catch, end, end

      docElement = cmdWinDoc.getParagraphElement(lastPos+1);
      if majorVersion<7 || (majorVersion==7 && minorVersion<13)
          if bolFlag && ~underlineFlag
              % Set the leading hyperlink space character ('_') to the bg color, effectively hiding it
              % Note: old Matlab versions have a bug in hyperlinks that need to be accounted for...
              %disp(' '); dumpElement(docElement)
              setElementStyle(docElement,'CW_BG_Color',1+underlineFlag,majorVersion,minorVersion); %+getUrlsFix(docElement));
              %disp(' '); dumpElement(docElement)
              el(end+1) = handle(docElement);  % #ok used in debug only
          end

          % Fix a problem with some hidden hyperlinks becoming unhidden...
          fixHyperlink(docElement);
          %dumpElement(docElement);
      end

      % Get the Document Element(s) corresponding to the latest fprintf operation
      while docElement.getStartOffset < cmdWinDoc.getLength
          % Set the element style according to the current style
          if debugFlag, dumpElement(docElement); end
          specialFlag = underlineFlag | boldFlag;
          setElementStyle(docElement,style,specialFlag,majorVersion,minorVersion);
          if debugFlag, dumpElement(docElement); end
          docElement2 = cmdWinDoc.getParagraphElement(docElement.getEndOffset+1);
          if isequal(docElement,docElement2),  break;  end
          docElement = docElement2;
      end
      if debugFlag, dumpElement(docElement); end

      % Force a Command-Window repaint
      % Note: this is important in case the rendered str was not '\n'-terminated
      xCmdWndView.repaint;

      % The following is for debug use only:
      el(end+1) = handle(docElement);  %#ok used in debug only
      %elementStart  = docElement.getStartOffset;
      %elementLength = docElement.getEndOffset - elementStart;
      %txt = cmdWinDoc.getText(elementStart,elementLength);
  end

  if nargout
      count = count1;
  end
  return;  % debug breakpoint

% Process the requested style information
function [underlineFlag,boldFlag,style,debugFlag] = processStyleInfo(style)
  underlineFlag = 0;
  boldFlag = 0;
  debugFlag = 0;

  % First, strip out the underline/bold markers
  if ischar(style)
      % Styles containing '-' or '_' should be underlined (using a no-target hyperlink hack)
      %if style(1)=='-'
      underlineIdx = (style=='-') | (style=='_');
      if any(underlineIdx)
          underlineFlag = 1;
          %style = style(2:end);
          style = style(~underlineIdx);
      end

      % Check for bold style (only if not underlined)
      boldIdx = (style=='*');
      if any(boldIdx)
          boldFlag = 1;
          style = style(~boldIdx);
      end
      if underlineFlag && boldFlag
          warning('YMA:cprintf:BoldUnderline','Matlab does not support both bold & underline')
      end

      % Check for debug mode (style contains '!')
      debugIdx = (style=='!');
      if any(debugIdx)
          debugFlag = 1;
          style = style(~debugIdx);
      end

      % Check if the remaining style sting is a numeric vector
      %styleNum = str2num(style); %#ok<ST2NM>  % not good because style='text' is evaled!
      %if ~isempty(styleNum)
      if any(style==' ' | style==',' | style==';')
          style = str2num(style); %#ok<ST2NM>
      end
  end

  % Style = valid matlab RGB vector
  if isnumeric(style) && length(style)==3 && all(style<=1) && all(abs(style)>=0)
      if any(style<0)
          underlineFlag = 1;
          style = abs(style);
      end
      style = getColorStyle(style);

  elseif ~ischar(style)
      error('YMA:cprintf:InvalidStyle','Invalid style - see help section for a list of valid style values')

  % Style name
  else
      % Try case-insensitive partial/full match with the accepted style names
      matlabStyles = {'Text','Keywords','Comments','Strings','UnterminatedStrings','SystemCommands','Errors'};
      validStyles  = [matlabStyles, ...
                      'Black','Cyan','Magenta','Blue','Green','Red','Yellow','White', ...
                      'Hyperlinks'];
      matches = find(strncmpi(style,validStyles,length(style)));

      % No match - error
      if isempty(matches)
          error('YMA:cprintf:InvalidStyle','Invalid style - see help section for a list of valid style values')

      % Too many matches (ambiguous) - error
      elseif length(matches) > 1
          error('YMA:cprintf:AmbigStyle','Ambiguous style name - supply extra characters for uniqueness')

      % Regular text
      elseif matches == 1
          style = 'ColorsText';  % fixed by Danilo, 29/8/2011

      % Highlight preference style name
      elseif matches <= length(matlabStyles)
          style = ['Colors_M_' validStyles{matches}];

      % Color name
      elseif matches < length(validStyles)
          colors = [0,0,0; 0,1,1; 1,0,1; 0,0,1; 0,1,0; 1,0,0; 1,1,0; 1,1,1];
          requestedColor = colors(matches-length(matlabStyles),:);
          style = getColorStyle(requestedColor);

      % Hyperlink
      else
          style = 'Colors_HTML_HTMLLinks';  % CWLink
          underlineFlag = 1;
      end
  end

% Convert a Matlab RGB vector into a known style name (e.g., '[255,37,0]')
function styleName = getColorStyle(rgb)
  intColor = int32(rgb*255);
  javaColor = java.awt.Color(intColor(1), intColor(2), intColor(3));
  styleName = sprintf('[%d,%d,%d]',intColor);
  com.mathworks.services.Prefs.setColorPref(styleName,javaColor);

% Fix a bug in some Matlab versions, where the number of URL segments
% is larger than the number of style segments in a doc element
function delta = getUrlsFix(docElement)  %#ok currently unused
  tokens = docElement.getAttribute('SyntaxTokens');
  links  = docElement.getAttribute('LinkStartTokens');
  if length(links) > length(tokens(1))
      delta = length(links) > length(tokens(1));
  else
      delta = 0;
  end

% fprintf(2,str) causes all previous '_'s in the line to become red - fix this
function fixHyperlink(docElement)
  try
      tokens = docElement.getAttribute('SyntaxTokens');
      urls   = docElement.getAttribute('HtmlLink');
      urls   = urls(2);
      links  = docElement.getAttribute('LinkStartTokens');
      offsets = tokens(1);
      styles  = tokens(2);
      doc = docElement.getDocument;

      % Loop over all segments in this docElement
      for idx = 1 : length(offsets)-1
          % If this is a hyperlink with no URL target and starts with ' ' and is collored as an error (red)...
          if strcmp(styles(idx).char,'Colors_M_Errors')
              character = char(doc.getText(offsets(idx)+docElement.getStartOffset,1));
              if strcmp(character,' ')
                  if isempty(urls(idx)) && links(idx)==0
                      % Revert the style color to the CW background color (i.e., hide it!)
                      styles(idx) = java.lang.String('CW_BG_Color');
                  end
              end
          end
      end
  catch
      % never mind...
  end

% Set an element to a particular style (color)
function setElementStyle(docElement,style,specialFlag, majorVersion,minorVersion)
  %global tokens links urls urlTargets  % for debug only
  global oldStyles
  if nargin<3,  specialFlag=0;  end
  % Set the last Element token to the requested style:
  % Colors:
  tokens = docElement.getAttribute('SyntaxTokens');
  try
      styles = tokens(2);
      oldStyles{end+1} = cell(styles);

      % Correct edge case problem
      extraInd = double(majorVersion>7 || (majorVersion==7 && minorVersion>=13));  % =0 for R2011a-, =1 for R2011b+
      %{
      if ~strcmp('CWLink',char(styles(end-hyperlinkFlag))) && ...
          strcmp('CWLink',char(styles(end-hyperlinkFlag-1)))
         extraInd = 0;%1;
      end
      hyperlinkFlag = ~isempty(strmatch('CWLink',tokens(2)));
      hyperlinkFlag = 0 + any(cellfun(@(c)(~isempty(c)&&strcmp(c,'CWLink')),cell(tokens(2))));
      %}

      jStyle = java.lang.String(style);
      if numel(styles)==4 && isempty(char(styles(2)))
          % Attempt to fix discoloration issues - NOT SURE THAT THIS IS OK! - 24/6/2015
          styles(1) = jStyle;
      end
      styles(end-extraInd) = java.lang.String('');
      styles(end-extraInd-specialFlag) = jStyle;  % #ok apparently unused but in reality used by Java
      if extraInd
          styles(end-specialFlag) = jStyle;
      end

      oldStyles{end} = [oldStyles{end} cell(styles)];
  catch
      % never mind for now
  end

  % Underlines (hyperlinks):
  %{
  links = docElement.getAttribute('LinkStartTokens');
  if isempty(links)
      %docElement.addAttribute('LinkStartTokens',repmat(int32(-1),length(tokens(2)),1));
  else
      %TODO: remove hyperlink by setting the value to -1
  end
  %}

  % Correct empty URLs to be un-hyperlinkable (only underlined)
  %{
  urls = docElement.getAttribute('HtmlLink');
  if ~isempty(urls)
      urlTargets = urls(2);
      for urlIdx = 1 : length(urlTargets)
          try
              if urlTargets(urlIdx).length < 1
                  urlTargets(urlIdx) = [];  % '' => []
              end
          catch
              % never mind...
              a=1;  %#ok used for debug breakpoint...
          end
      end
  end
  %}
  % Bold: (currently unused because we cannot modify this immutable int32 numeric array)
  %{
  try
      %hasBold = docElement.isDefined('BoldStartTokens');
      bolds = docElement.getAttribute('BoldStartTokens');
      if ~isempty(bolds)
          %docElement.addAttribute('BoldStartTokens',repmat(int32(1),length(bolds),1));
      end
  catch
      % never mind - ignore...
      a=1;  %#ok used for debug breakpoint...
  end
  %}

  return;  % debug breakpoint

% Display information about element(s)
function dumpElement(docElements)
  %return;
  disp(' ');
  numElements = length(docElements);
  cmdWinDoc = docElements(1).getDocument;
  for elementIdx = 1 : numElements
      if numElements > 1,  fprintf('Element #%d:\n',elementIdx);  end
      docElement = docElements(elementIdx);
      if ~isjava(docElement),  docElement = docElement.java;  end
      %docElement.dump(java.lang.System.out,1)
      disp(docElement)
      tokens = docElement.getAttribute('SyntaxTokens');
      if isempty(tokens),  continue;  end
      links = docElement.getAttribute('LinkStartTokens');
      urls  = docElement.getAttribute('HtmlLink');
      try bolds = docElement.getAttribute('BoldStartTokens'); catch, bolds = []; end
      txt = {};
      tokenLengths = tokens(1);
      for tokenIdx = 1 : length(tokenLengths)-1
          tokenLength = diff(tokenLengths(tokenIdx+[0,1]));
          if (tokenLength < 0)
              tokenLength = docElement.getEndOffset - docElement.getStartOffset - tokenLengths(tokenIdx);
          end
          txt{tokenIdx} = cmdWinDoc.getText(docElement.getStartOffset+tokenLengths(tokenIdx),tokenLength).char;  %#ok
      end
      lastTokenStartOffset = docElement.getStartOffset + tokenLengths(end);
      try
          txt{end+1} = cmdWinDoc.getText(lastTokenStartOffset, docElement.getEndOffset-lastTokenStartOffset).char; %#ok
      catch
          txt{end+1} = ''; %#ok<AGROW>
      end
      %cmdWinDoc.uiinspect
      %docElement.uiinspect
      txt = strrep(txt',sprintf('\n'),'\n');
      try
          data = [cell(tokens(2)) m2c(tokens(1)) m2c(links) m2c(urls(1)) cell(urls(2)) m2c(bolds) txt];
          if elementIdx==1
              disp('    SyntaxTokens(2,1) - LinkStartTokens - HtmlLink(1,2) - BoldStartTokens - txt');
              disp('    ==============================================================================');
          end
      catch
          try
              data = [cell(tokens(2)) m2c(tokens(1)) m2c(links) txt];
          catch
              disp([cell(tokens(2)) m2c(tokens(1)) txt]);
              try
                  data = [m2c(links) m2c(urls(1)) cell(urls(2))];
              catch
                  % Matlab 7.1 only has urls(1)...
                  data = [m2c(links) cell(urls)];
              end
          end
      end
      disp(data)
  end

% Utility function to convert matrix => cell
function cells = m2c(data)
  %datasize = size(data);  cells = mat2cell(data,ones(1,datasize(1)),ones(1,datasize(2)));
  cells = num2cell(data);

% Display the help and demo
function showDemo(majorVersion,minorVersion)
  fprintf('cprintf displays formatted text in the Command Window.\n\n');
  fprintf('Syntax: count = cprintf(style,format,...);  click here for details.\n\n');
  url = 'http://UndocumentedMatlab.com/blog/cprintf/';
  fprintf(['Technical description: ' url '\n\n']);
  fprintf('Demo:\n\n');
  boldFlag = majorVersion>7 || (majorVersion==7 && minorVersion>=13);
  s = ['cprintf(''text'',    ''regular black text'');' 10 ...
       'cprintf(''hyper'',   ''followed %s'',''by'');' 10 ...
       'cprintf(''key'',     ''%d colored'',' num2str(4+boldFlag) ');' 10 ...
       'cprintf(''-comment'',''& underlined'');' 10 ...
       'cprintf(''err'',     ''elements:\n'');' 10 ...
       'cprintf(''cyan'',    ''cyan'');' 10 ...
       'cprintf(''_green'',  ''underlined green'');' 10 ...
       'cprintf(-[1,0,1],  ''underlined magenta'');' 10 ...
       'cprintf([1,0.5,0], ''and multi-\nline orange\n'');' 10];
   if boldFlag
       % In R2011b+ the internal bug that causes the need for an extra space
       % is apparently fixed, so we must insert the sparator spaces manually...
       % On the other hand, 2011b enables *bold* format
       s = [s 'cprintf(''*blue'',   ''and *bold* (R2011b+ only)\n'');' 10];
       s = strrep(s, ''')',' '')');
       s = strrep(s, ''',5)',' '',5)');
       s = strrep(s, '\n ','\n');
   end
   disp(s);
   eval(s);

%%%%%%%%%%%%%%%%%%%%%%%%%% TODO %%%%%%%%%%%%%%%%%%%%%%%%%
% - Fix: Remove leading space char (hidden underline '_')
% - Fix: Find workaround for multi-line quirks/limitations
% - Fix: Non-\n-terminated segments are displayed as black
% - Fix: Check whether the hyperlink fix for 7.1 is also needed on 7.2 etc.
% - Enh: Add font support


% FT_POSTAMBLE_SAVEVAR is a helper script that optionally saves the output
% FieldTrip data structures to a *.mat file on disk. This is useful for
% batching and for distributed processing. This makes use of the
% cfg.outputfile variable.
%
% Use as
%   ft_postamble savevar data
%   ft_postamble savevar source mri
%
% See also FT_PREAMBLE, FT_POSTAMBLE, FT_POSTAMBLE_SAVEFIG

% Copyright (C) 2011-2019, Robert Oostenveld, DCCN
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

% the output data should be saved to a MATLAB file
if (isfield(cfg, 'outputfile') && ~isempty(cfg.outputfile)) || exist('Fief7bee_reproducescript', 'var')

  if isfield(cfg, 'outputlock') && ~isempty(cfg.outputlock)
    mutexlock(cfg.outputlock);
  end

  if exist('Fief7bee_reproducescript', 'var')
    % write the output variable(s) to a MATLAB file
    iW1aenge_now = datestr(now, 30);
    cfg.outputfile = {};
    for i=1:numel(iW1aenge_postamble)
      cfg.outputfile{i} = fullfile(Fief7bee_reproducescript, sprintf('%s_%s_output_%s.mat', ...
        iW1aenge_now, FjmoT6aA_highest_ft, iW1aenge_postamble{i}));
    end

    % write the large configuration fields to a MATLAB file
    % this applies to layout, event, sourcemodel, headmodel, grad, etc.
    % note that this is here, rather than in the (seemingly more logical)
    % ft_preamble_loadvar, because this code depends on cfg.callinfo (which
    % is only present at postamble stage)
    cfg = save_large_cfg_fields(cfg, FjmoT6aA_highest_ft, Fief7bee_reproducescript, iW1aenge_now);

    % write a snippet of MATLAB code with the user-specified configuration and function call
    reproducescript(Fief7bee_reproducescript, fullfile(Fief7bee_reproducescript, 'script.m'),...
      FjmoT6aA_highest_ft, cfg, isempty(iW1aenge_postamble));

    % instruct savevar() to also write hashes of output files to the
    % hashfile
    Fief7bee_hashfile = fullfile(Fief7bee_reproducescript, 'hashes.mat');

  elseif (isfield(cfg, 'outputfile') && ~isempty(cfg.outputfile))
    % keep the output file as it is
    Fief7bee_hashfile = [];
  else
    % don't write to an output file
    cfg.outputfile = {};
    Fief7bee_hashfile = [];
  end

  if isequal(iW1aenge_postamble, {'varargout'}) && ~iscell(cfg.outputfile)
    % this should be a cell-array, oterwise it cannot be matched with varargout
    cfg.outputfile = {cfg.outputfile};
  end

  % save the output data structures to a MATLAB .mat file
  if iscell(cfg.outputfile)
    % iW1aenge_postamble is a cell-array containing the variable names
    if isequal(iW1aenge_postamble, {'varargout'})
      % the output is in varargout
      for tmpindx=1:length(cfg.outputfile)
        savevar(cfg.outputfile{tmpindx}, 'data', varargout{tmpindx}, Fief7bee_hashfile);
      end % for
      clear tmpindx
    else
      % the output is in explicitly named variables
      for tmpindx=1:length(cfg.outputfile)
        savevar(cfg.outputfile{tmpindx}, iW1aenge_postamble{tmpindx}, eval(iW1aenge_postamble{tmpindx}), Fief7bee_hashfile);
      end % for
      clear tmpindx
    end
  else
    % iW1aenge_postamble{1} contains the name of the only variable
    savevar(cfg.outputfile, iW1aenge_postamble{1}, eval(iW1aenge_postamble{1}), Fief7bee_hashfile);
  end

  if isfield(cfg, 'outputlock') && ~isempty(cfg.outputlock)
    mutexunlock(cfg.outputlock);
  end

  if ~ft_nargout
    % do not return the output variable "ans"
    clear(iW1aenge_postamble{1});
  end
end


function out = saveobj(obj)
%SAVEOBJ (overloaded)
warning('YALMIP objects cannot be saved in binary format. You will run into troubles if you try to load this file later. You should clear all YALMIP objects first, or avoid having any YALMIP objects in the list of variables which you save.');
out = [];


function dbmute
%dbmute disables all breakpoints currently set in MATLAB.
% Copyright 2009 The MathWorks, Inc.

    % iterate over each entry in the result of dbstatus,
    % and disable each of the breakpoints.
    breakpoints = dbstatus('-completenames');
    for i=1 : length(breakpoints)
        muteDbStatusEntry(breakpoints(i));
    end

end

function muteDbStatusEntry(dbstatusEntry)
%muteDbStatusEntry disables each breapoint in the given entry.
    for i=1 : length(dbstatusEntry.line)
        file = dbstatusEntry.file;
        line = dbstatusEntry.line(i);
        anonymousIndex = dbstatusEntry.anonymous(i);
        expression = dbstatusEntry.expression{i};

        lineNumberString = [num2str(line) '@' num2str(anonymousIndex)];
        newExpression = createDisabledExpression(expression);

        dbstop(file, lineNumberString, 'if', newExpression);
    end
end

function newExpression = createDisabledExpression(expression)
%createDisabledExpression wraps the given expression in a disabling
%  expression if necessary.
    if (isDisabled(expression))
        newExpression = expression;
    elseif strcmp(expression, '')
        newExpression = 'false';
    else
        newExpression = ['false&&(' expression ')'];
    end
end


function printStack(ME)
global logger %#ok<NUSED>

if ~exist('ME','var')
    ME = [];
end

stdoutFuncName = getStandardOutputFuncName();

if isempty(ME)
    s = dbstack;
else
    s = ME.stack;
end

eval( sprintf('%s(''----------------------------------------------\\n'')', stdoutFuncName) );
if ~isempty(ME)
    eval( sprintf('%s(''ERROR:    %%s\\n'', ME.message)', stdoutFuncName) );
    eval( sprintf('%s(''Current Folder :  %%s\\n'', filesepStandard(pwd))', stdoutFuncName) );
end
eval( sprintf('%s(''Call stack:\\n'')', stdoutFuncName) );
for ii = 1:length(s)
    [~,f,e] = fileparts(s(ii).file); %#ok<*ASGLU>
    eval( sprintf('%s(''    Error in %%s > %%s (line %%d)\\n'', [f, e], s(ii).name, s(ii).line)', stdoutFuncName) );
end
eval( sprintf('%s(''----------------------------------------------\\n\\n'')', stdoutFuncName) );


%LDIVIDE Mapping overload


%--- help for read_identification_restrictions ---
%
%  INTERNAL FUNCTION: Formats identification restrictions
%
%  See also:
%     :func:`rfvar.identification`
%
%


% eeg_global() - declare global EEGLAB variables. These variables are
%                used only as global by the main function eeglab(),
%                the function pop_rejmenu() and the history eegh() function.
%
% Global variables:
%  EEG        - structure containing the current dataset
%  ALLEEG     - array of structures containing all the loaded datasets
%  CURRENTSET - index of the current dataset in the ALLEEG array
%  LASTCOM    - most recent command run by EEGLAB
%  ALLCOM     - cell array containing the EEGLAB session command history
%               See the history (h) function for more details.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eeglab()

% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

% global variables
% ----------------
global EEG;		% current dataset
global ALLEEG;		% all datasets
global CURRENTSET;	% current set index

%global W_MAIN;		% main window
%global H_MAIN;		% main window
%global EEGMENU;		% main menu
global ALLCOM;		% all commands (history)
global LASTCOM;		% last command
global STUDY;
global CURRENTSTUDY;


function tf = isTearDownString(str)
%isTearDownString True if string looks like the name of a teardown function
%   tf = isTearDownString(str) returns true if the string str looks like the
%   name of a teardown function.  If str is a cell array of strings, then
%   isTearDownString tests each string in the cell array, returning the results
%   in a logical array with the same size as str.

%   Steven L. Eddins
%   Copyright 2008-2009 The MathWorks, Inc.

setup_exp = '^[tT]ear[dD]own';
tf = mtest.utils.containsRegexp(str, setup_exp);


function [eegPath] = eeg_toolbox_path

% eeg_toolbox_path - locate the eeg_toolbox installation path
%
% [eegPath] = eeg_toolbox_path
%
% This function looks for the installation path of
% eeg_toolbox.m in the matlab path.  If not
% found, update the matlab path (try addpath).
%

% $Revision: 1.1 $ $Date: 2009-04-28 22:13:53 $

% Licence:  GNU GPL, no implied or express warranties
% History:  12/2003, Darren.Weber_at_radiology.ucsf.edu
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

eegPath = fileparts(which('eeg_toolbox'));
if isempty(eegPath),
    msg = sprintf('Cannot find eeg_toolbox on the matlab path.\nPlease use the addpath command.\n\n');
    error(msg);
else
    eegPath = strcat(eegPath,filesep);
end

return


function obj=prepare(obj)
% prepare for collecting coverage information
%
% obj=prepare(obj)
%
% Input:
%   obj                 MOcovMFileCollection instance
%
% Output:
%   obj                 MOcovMFileCollection instance with, if
%                       method=='file', the original path restored as well
%                       as mfiles rewritten to collect coverage
%                       information.

    monitor=obj.monitor;

    fns=mocov_find_files(obj.root_dir,'*.m',monitor,obj.exclude_pat);
    n=numel(fns);

    mfiles=cell(n,1);
    for k=1:n
        fn=fns{k};
        mfiles{k}=MOcovMFile(fn);
    end

    obj.mfiles=mfiles;

    if ~ischar(obj.method)
        error('method must be char, found %s', class(obj.method));
    end

    switch obj.method
        case 'profile'
            profile on
            notify(monitor,'','Enabling profiler');

        case 'file'
            % store original path
            obj.orig_path=path();
            notify(monitor,sprintf('Preserving original path\n'));

            temp_dir=tempname();
            notify(monitor,sprintf('Rewriting m-files\n'));
            obj=rewrite_mfiles(obj,temp_dir);

            addpath(genpath(temp_dir));
            notify(monitor,'',sprintf('Path is: %s\n', path()));

        otherwise
            error('illegal method %s', obj.method);
    end

    notify(monitor,sprintf('Coverage preparation complete\n'));


function files = findAllFiles(subdir, pattern)
files = {};
if ~exist('subdir','var')
    subdir = pwd;
end
if ~exist('pattern','var')
    pattern = '*';
end

if ~ispathvalid_startup(subdir, 'dir')
    fprintf('Warning: folder %s doesn''t exist under %s\n', subdir, pwd);
    return;
end
if subdir(1) == '.'
    return
end

% If current subjdir is in the exclList then go back to curr dir and exit
subdirFullpath = filesepStandard_startup(subdir,'full');
f = dir([subdirFullpath, '*']);
for ii = 1:length(f)
    if f(ii).name(1)=='.'
        continue
    end

    if ~f(ii).isdir
        if strcmp(pattern,'*') || strcmp(f(ii).name, pattern)
        	files{end+1,1} = filesepStandard_startup(sprintf('%s%s%s', subdirFullpath, f(ii).name), 'nameonly');         %#ok<*AGROW>
        end
    else
        files = [files; findAllFiles([subdirFullpath, f(ii).name], pattern)];
    end
end


function [metabolite_structure,IDAdded] = addInfoFromMolFiles(metabolite_structure,folderName,startSearch,endSearch)
% This function creates inchiStrings, smiles, and inchiKeys from provided mol files,
% in the case that these fields are empty (NaN) in the structure.
%
% INPUT
% metabolite_structure  metabolite structure
% folderName            name of folder that contains the mol structures
% startSearch           specify where the search should start in the
%                       metabolite structure. Must be numeric (optional, default: all metabolites
%                       in the structure will be search for)
% endSearch             specify where the search should end in the
%                       metabolite structure. Must be numeric (optional, default: all metabolites
%                       in the structure will be search for)
%
% OUTPUT
% metabolite_structure  Updated metabolite structure
%
%
% Ines Thiele, 09/2021

F = fieldnames(metabolite_structure);
if ~exist('startSearch','var')
    startSearch = 1;
end
if ~exist('endSearch','var')
    endSearch = length(F);
end

if ~exist('folderName','var')
    folderName= 'ctf-main/mets/molFiles';
end
files = dir(folderName);
for i = 1 : length(files)
    fileNames{i,1} = files(i).name;
end
cnt =1;

if exist('fileNames','var')
    for i = startSearch : endSearch
        VMHId = metabolite_structure.(F{i}).VMHId ;

        if isempty(metabolite_structure.(F{i}).inchiString) || length(find(isnan(metabolite_structure.(F{i}).inchiString))) >0 % no inchistring exists

            if strmatch([metabolite_structure.(F{i}).VMHId '.mol'],fileNames,'exact') % but mol file
                % generate inchistring from mol file
                [~,tmp] = system(['obabel ' folderName filesep VMHId  '.mol -o inchi']);
                tmp2=split(tmp,'==');
                inchiString = strtrim(tmp2{1});
                inchiString = regexprep(inchiString,'1 molecule converted','');
                inchiString = regexprep(inchiString,'\n','');
                if ~isempty(inchiString)
                    metabolite_structure.(F{i}).inchiString = inchiString;
                    metabolite_structure.(F{i}).inchiString_source = ['Mol File in ' folderName];
                    IDAdded{cnt,1} = VMHId;
                    IDAdded{cnt,2} = inchiString;
                    IDAdded{cnt,3} = VMHId;cnt = cnt + 1;
                end
                metabolite_structure.(F{i}).hasmolfile =1;
                metabolite_structure.(F{i}).hasmolfile_source = ['Mol File in ' folderName];
            end
        end

        if ~isempty(metabolite_structure.(F{i}).inchiString) && length(find(isnan(metabolite_structure.(F{i}).inchiString))) ==0 % no inchistring exists
            if  isempty(metabolite_structure.(F{i}).inchiKey) || length(find(isnan(metabolite_structure.(F{i}).inchiKey))) >0 % no inchistring exists
                inchiString =metabolite_structure.(F{i}).inchiString;
                [result] = convertInchiString2format(inchiString,'inchiKey');

                if ~isnan(result)

                    metabolite_structure.(F{i}).inchiKey = (result);
                    metabolite_structure.(F{i}).inchiKey_source = ['Mol File in ' folderName];
                    IDAdded{cnt,1} = VMHId;
                    IDAdded{cnt,2} = metabolite_structure.(F{i}).inchiKey;
                    IDAdded{cnt,3} = VMHId;cnt = cnt + 1;
                end
            end
            if  isempty(metabolite_structure.(F{i}).smile) || length(find(isnan(metabolite_structure.(F{i}).smile))) >0 % no inchistring exists

                inchiString =metabolite_structure.(F{i}).inchiString;
                [result] = convertInchiString2format(inchiString,'smiles');

                if ~isnan(result)

                    metabolite_structure.(F{i}).smile_source = ['Mol File in ' folderName];
                    metabolite_structure.(F{i}).smile = (result);
                    IDAdded{cnt,1} = VMHId;
                    IDAdded{cnt,2} =    metabolite_structure.(F{i}).smile;
                    IDAdded{cnt,3} = VMHId;cnt = cnt + 1;
                end
            end
        end
    end
end


function varargout = ARMAX_close_dialog(varargin)
% ARMAX_CLOSE_DIALOG M-file for ARMAX_close_dialog.fig
%      ARMAX_CLOSE_DIALOG by itself, creates a new ARMAX_CLOSE_DIALOG or raises the
%      existing singleton*.
%
%      H = ARMAX_CLOSE_DIALOG returns the handle to a new ARMAX_CLOSE_DIALOG or the handle to
%      the existing singleton*.
%
%      ARMAX_CLOSE_DIALOG('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in ARMAX_CLOSE_DIALOG.M with the given input arguments.
%
%      ARMAX_CLOSE_DIALOG('Property','Value',...) creates a new ARMAX_CLOSE_DIALOG or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before ARMAX_close_dialog_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to ARMAX_close_dialog_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help ARMAX_close_dialog

% Last Modified by GUIDE v2.5 19-Aug-2006 01:03:58

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @ARMAX_close_dialog_OpeningFcn, ...
                   'gui_OutputFcn',  @ARMAX_close_dialog_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before ARMAX_close_dialog is made visible.
function ARMAX_close_dialog_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to ARMAX_close_dialog (see VARARGIN)

% Choose default command line output for ARMAX_close_dialog
handles.output = 'Yes';

% Update handles structure
guidata(hObject, handles);

% Insert custom Title and Text if specified by the user
% Hint: when choosing keywords, be sure they are not easily confused
% with existing figure properties.  See the output of set(figure) for
% a list of figure properties.
if(nargin > 3)
    for index = 1:2:(nargin-3),
        if nargin-3==index, break, end
        switch lower(varargin{index})
         case 'title'
          set(hObject, 'Name', varargin{index+1});
         case 'string'
          set(handles.text1, 'String', varargin{index+1});
        end
    end
end

% Determine the position of the dialog - centered on the callback figure
% if available, else, centered on the screen
FigPos=get(0,'DefaultFigurePosition');
OldUnits = get(hObject, 'Units');
set(hObject, 'Units', 'pixels');
OldPos = get(hObject,'Position');
FigWidth = OldPos(3);
FigHeight = OldPos(4);
if isempty(gcbf)
    ScreenUnits=get(0,'Units');
    set(0,'Units','pixels');
    ScreenSize=get(0,'ScreenSize');
    set(0,'Units',ScreenUnits);

    FigPos(1)=1/2*(ScreenSize(3)-FigWidth);
    FigPos(2)=2/3*(ScreenSize(4)-FigHeight);
else
    GCBFOldUnits = get(gcbf,'Units');
    set(gcbf,'Units','pixels');
    GCBFPos = get(gcbf,'Position');
    set(gcbf,'Units',GCBFOldUnits);
    FigPos(1:2) = [(GCBFPos(1) + GCBFPos(3) / 2) - FigWidth / 2, ...
                   (GCBFPos(2) + GCBFPos(4) / 2) - FigHeight / 2];
end
FigPos(3:4)=[FigWidth FigHeight];
set(hObject, 'Position', FigPos);
set(hObject, 'Units', OldUnits);

% Show a question icon from dialogicons.mat - variables questIconData
% and questIconMap
load dialogicons.mat

IconData=questIconData;
questIconMap(256,:) = get(handles.figure1, 'Color');
IconCMap=questIconMap;

Img=image(IconData, 'Parent', handles.axes1);
set(handles.figure1, 'Colormap', IconCMap);

set(handles.axes1, ...
    'Visible', 'off', ...
    'YDir'   , 'reverse'       , ...
    'XLim'   , get(Img,'XData'), ...
    'YLim'   , get(Img,'YData')  ...
    );

% Make the GUI modal
set(handles.figure1,'WindowStyle','modal')

% UIWAIT makes ARMAX_close_dialog wait for user response (see UIRESUME)
uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = ARMAX_close_dialog_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% The figure can be deleted now
delete(handles.figure1);

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

handles.output = get(hObject,'String');

% Update handles structure
guidata(hObject, handles);

% Use UIRESUME instead of delete because the OutputFcn needs
% to get the updated handles structure.
uiresume(handles.figure1);

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

handles.output = get(hObject,'String');

% Update handles structure
guidata(hObject, handles);

% Use UIRESUME instead of delete because the OutputFcn needs
% to get the updated handles structure.
uiresume(handles.figure1);

% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.output = 'No';
guidata(hObject, handles);
if isequal(get(handles.figure1, 'waitstatus'), 'waiting')
    % The GUI is still in UIWAIT, us UIRESUME
    uiresume(handles.figure1);
else
    % The GUI is no longer waiting, just close it
    delete(handles.figure1);
end

% --- Executes on key press over figure1 with no controls selected.
function figure1_KeyPressFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Check for "enter" or "escape"
if isequal(get(hObject,'CurrentKey'),'escape')
    % User said no by hitting escape
    handles.output = 'No'

    % Update handles structure
    guidata(hObject, handles);

    uiresume(handles.figure1);
end

if isequal(get(hObject,'CurrentKey'),'return')
    uiresume(handles.figure1);
end


function new()
%NEW Wrapper for GenerateFunctionMFile.
%
% NEW() Wrapper for GenerateFunctionMFile.
%
% See also: GenerateFunctionMFile

% $Author: rcotton $  $Date: 2010/04/09 15:41:27 $ $Revision: 0.1 $
% Copyright: Health and Safety Laboratory 2010

GenerateFunctionMFile(true);

end


function mc_install

    if ispc   % A windows version of Matlab
        mex -O -output bbmean winCSource\bbmean.c
        mex -O -output resampres winCsource\resampres.c winCsource\binsgeq.c
        mex -O -output resampsim winCsource\resampsim.c winCsource\binsgeq.c
        mex -O -output resampstr winCsource\resampstr.c winCsource\binsgeq.c
        mex -O -output resampdet winCsource\resampdet.c winCsource\binsgeq.c
    else
        mex -O -output bbmean linuxCsource/bbmean.c
        mex -O -output resampres linuxCsource/resampres.c linuxCsource/binsgeq.c
        mex -O -output resampsim linuxCsource/resampsim.c linuxCsource/binsgeq.c
        mex -O -output resampstr linuxCsource/resampstr.c linuxCsource/binsgeq.c
        mex -O -output resampdet linuxCsource/resampdet.c linuxCsource/binsgeq.c
    end


classdef PTKReporting < MimReporting
    % PTKReporting. Legacy support function. Replaced by MimReporting
    %
    %     Licence
    %     -------
    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit
    %     Author: Tom Doel, 2012.  www.tomdoel.com
    %     Distributed under the GNU GPL v3 licence. Please see website for details.
    %

    methods
        function obj = PTKReporting(progress_dialog, verbose_mode, log_file_name)
            obj = obj@MimReporting(progress_dialog, verbose_mode, log_file_name);
        end
    end
end


function funReset1(object_handle, event, start_button1, pause_button1, save_button1)

    global mode
    mode = 'Reset1';

    set(start_button1, 'BackGroundColor', 'g', 'Enable', 'on');
    set(object_handle, 'BackGroundColor', [0.4,0.4,0.4], 'Enable', 'off');
    set(pause_button1, 'BackGroundColor', [0.4,0.4,0.4], 'Enable', 'off');

    set(save_button1, 'BackGroundColor', [0.4,0.4,0.4], 'Enable', 'off');

end


function hStructMenu = putStructMenu(hParent)
%"putStructMenu"
%   Add structure menu to CERR slice viewer, or update the existing structure menu.
%   Uses a self-updating callback.
%
%LM:  5 Apr 02, JOD. Creation.
%    26 Mar 04, JRA, self-updating callback, added struct toggling.
%
%Usage:
%   function hStructMenu = putStructMenu()
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

global planC
global stateS

%Necessary for compiled version:
if ~exist('planC')
    planC = [];
end

structuresC = {};

IMRTPdir = fileparts(which('IMRTP'));
if ~isempty(IMRTPdir)
    pos = 7;  %position of menu
else
    pos = 6;  %position of menu
end

%Create new menu if necessary.
if isfield(stateS, 'handle') && isfield(stateS.handle, 'CERRStructMenu') && ishandle(stateS.handle.CERRStructMenu)
    hStructMenu = stateS.handle.CERRStructMenu;
else
    hStructMenu = uimenu(stateS.handle.CERRSliceViewer, 'label', '&Structures', 'callback', 'putStructMenu;', 'Interruptible', 'off');
    stateS.handle.CERRStructMenu = hStructMenu;

    %First time for menu, add permenant ui submenus.
    %Call up Mesh-representation GUI
    %uimenu(hStructMenu, 'label', 'Mesh Representation', 'callback','selectStructsToMeshGUI(''init'')','interruptible','on');

    %Call up editStructures
    uimenu(hStructMenu, 'label', 'Manual contouring', 'callback',['sliceCallBack(''contourMode'')'],'interruptible','on', 'separator', 'on');

    %Call up deepLearnSegGui
    uimenu(hStructMenu, 'label', 'Deep-learning auto-contouring', 'callback',['deepLearnSegGui'],'interruptible','on');

    %One element for Segment Labeler
    uimenu(hStructMenu, 'label', 'Segment Labeler', 'callback','segmentLabelerControl(''segmentLabeler'', ''init'');','interruptible','on');

    %Call up editStructures
    %     uimenu(hStructMenu, 'label', 'Add/Edit structures', 'callback',['editStructFields'],'interruptible','on');

    %One element for structure fusion.
    uimenu(hStructMenu, 'label', 'Derive new structure', 'callback',['sliceCallBack(''structurefusion'')'],'interruptible','on');

    %One element for copying structure from one scan to another
    uimenu(hStructMenu, 'label', 'Copy from one scan to other', 'callback',['sliceCallBack(''copyStr'')'],'interruptible','on');

    %One element for structure consensus
    uimenu(hStructMenu, 'label', 'Consensus', 'callback',['sliceCallBack(''structConsensus'')'],'interruptible','on');

    %Turn all structs on
    uimenu(hStructMenu, 'label', 'View all structures', 'callback', ['sliceCallBack(''ViewAllStructures'')'], 'interruptible', 'on', 'separator', 'on');

    uimenu(hStructMenu, 'label', 'View no structures', 'callback', ['sliceCallBack(''ViewNoStructures'')'], 'interruptible', 'on');
end

if isempty(planC)
    set(hStructMenu, 'visible', 'off');
    return;
else
    set(hStructMenu, 'visible', 'on');
end
indexS = planC{end};

numStructs = length(planC{indexS.structures});

%Init structure visible list.
if ~isfield(planC{indexS.structures}, 'visible') & length(planC{indexS.structures}) ~= 0
    [planC{indexS.structures}.visible] = deal(1);
end

%Build list of structure names.
if numStructs > 0
    [structuresC{1:numStructs}] = deal(planC{indexS.structures}.structureName);
end

%Find and remove old structure listings.
kids = get(hStructMenu, 'children');
numOldMenus = length(kids);
delete(kids(1:numOldMenus-8));

[assocScansV, relStructNum] = getStructureAssociatedScan(1:numStructs, planC);
allScans = unique(assocScansV);
for i = 1:length(allScans)
    strSep = 'off';
    if i == 1
        strSep = 'on';
    end

    scanType = planC{indexS.scan}(allScans(i)).scanType;
    if isempty(scanType)
        scanType = ['Scan ', num2str(allScans(i))];
    end
    hStrSetPannel(i)= uimenu(hStructMenu, 'label', [num2str(allScans(i)), '. ', scanType], 'callback','','interruptible','on', 'Separator', strSep);

    scanIndxV = find(assocScansV == allScans(i));

    uimenu(hStrSetPannel(i), 'label', ['Associated Scan Set: ' num2str(allScans(i))],'interruptible', 'off','Enable','off');

    %Reassign color
    uimenu(hStrSetPannel(i), 'label', 'Reassign Color', 'callback',['structColorGUI(''init'',''' num2str(allScans(i)) ''')'], 'interruptible', 'on','Separator','on');

    %Turn all structs on
    uimenu(hStrSetPannel(i), 'label', ['Turn ON Set ' num2str(allScans(i))], 'callback',['sliceCallBack(''ViewAllStructures'',''' num2str(allScans(i)) ''')'], 'interruptible', 'on','Separator','on');

    uimenu(hStrSetPannel(i), 'label', ['Turn OFF Set ' num2str(allScans(i))], 'callback',['sliceCallBack(''ViewNoStructures'',''' num2str(allScans(i)) ''')'], 'interruptible', 'on');

    maxStructToShow = 25;
    numStructs = length(scanIndxV);
    for j = 1:min(numStructs,maxStructToShow)
        %Populate with new structure menu items.

        sep = 'off';
        checked = 'off';

        str = [num2str(scanIndxV(j)) '.  ' structuresC{scanIndxV(j)}];

        %Seperator if 1st structure.
        if j == 1
            sep = 'on';
        end

        %Checkmark if visible.
        if planC{indexS.structures}(scanIndxV(j)).visible
            checked = 'on';
        end

        %Create actual menu element(s).
        uimenu(hStrSetPannel(i), 'label', str, 'callback',['sliceCallBack(''toggleSingleStruct'',''', num2str(scanIndxV(j)),''')'],...
            'interruptible','on','tag','struct menu', 'Separator', sep, 'Checked', checked);
    end

    if numStructs > maxStructToShow
        uimenu(hStrSetPannel(i), 'label', 'More Structures...', 'callback',['sliceCallBack(''selectStructMore'',',num2str(allScans(i)),')'],...
            'interruptible','on','tag','struct menu', 'Separator', sep, 'Checked', checked);
    end

end


function obj=MOcovMFileCollection(root_dir, method, monitor, exclude_pat)
% instantiate MOcovMFileCollection
%
% obj=MOcovMFileCollection(root_dir, method, monitor)
%
% Inputs:
%   root_dir                root directory containing m-files to be
%                           covered.
%   method                  Coverage method, one of:
%                           - 'file'    rewrite m-files after adding
%                                       statements that record which lines
%                                       are covered
%                           - 'profile' use Matlab profiler
%                           default: 'file'
%   monitor                 optional MOcovProgressMonitor instance
%   exclude_pat             Optional cell array of patterns to exclude.
%
% See also: mocov

    if nargin<4 || isempty(exclude_pat)
        exclude_pat={};
    end

    if nargin<3 || isempty(monitor)
        monitor=MOcovProgressMonitor();
    end

    if nargin<2 || isempty(method);
        method='file';
    end

    props=struct();
    props.root_dir=root_dir;
    props.monitor=monitor;
    props.exclude_pat=exclude_pat;
    props.mfiles=[];
    props.orig_path=[];
    props.temp_dir=[];
    props.method=method;
    obj=class(props,'MOcovMFileCollection');


function exportAndCropFigure(h,name,saveDir)
    if nargin < 3
        return;
    end
    [status,message,messageid] = mkdir(saveDir);
    [status,message,messageid] = mkdir(fullfile(saveDir,'png'));
    [status,message,messageid] = mkdir(fullfile(saveDir,'pdf'));
    [status,message,messageid] = mkdir(fullfile(saveDir,'fig'));

    saveas(h,fullfile(saveDir,name));
    saveas(h,fullfile(saveDir,'png',[name '.png']));
    saveas(h,fullfile(saveDir,'fig',[name '.fig']));
    saveas(h,fullfile(saveDir,'pdf',[name '.pdf']));

    %- auto crop pdf -%
    cmdStr = ['pdfcrop.pl' ' ' fullfile(saveDir,'pdf',name)  ...
    ' ' fullfile(saveDir,'pdf',name)];
    [status, result] = system(cmdStr);

end


function status = getKaleido()
status=0;
kDir = fullfile(fileparts(mfilename('fullpath')),'..','kaleido');
arch = computer('arch');
plotlyJS = 'https://cdn.plot.ly/plotly-latest.min.js';

if isunix()
    if ismac()
        if strcmp(arch,'maci64')
            url = 'https://github.com/plotly/Kaleido/releases/download/v0.2.1/kaleido_mac_x64.zip';
        else
            url = 'https://github.com/plotly/Kaleido/releases/download/v0.2.1/kaleido_mac_arm64.zip';
        end
    else
        if strcmp(arch,'glnxa64')
            url = 'https://github.com/plotly/Kaleido/releases/download/v0.2.1/kaleido_linux_x64.zip';
        else
            url = 'https://github.com/plotly/Kaleido/releases/download/v0.2.1/kaleido_linux_arm64.zip';
        end
    end
elseif ispc()
    if strcmp(arch,'win64')
        url = 'https://github.com/plotly/Kaleido/releases/download/v0.2.1/kaleido_win_x64.zip';
    else
        url = 'https://github.com/plotly/Kaleido/releases/download/v0.2.1/kaleido_win_x86.zip';
    end
else
    fprintf('\nCouldn''t find a suitable version of "Kaleido" required for exporting plots, for your system\n');
    fprintf('https://github.com/plotly/Kaleido/tags\n');
    fprintf('Please download a suitable Kaleido version for your system, and unzip the files in plotly/Kaleido folder.\n\n');
    return;
end

fprintf('\nTrying to download Kaleido executable and plotly javascript (one-time download)... please wait...');
try
    file = websave(fullfile(kDir,'kaleido.zip'),url);
    websave(fullfile(kDir,'plotly-latest.min.js'),plotlyJS);
catch
    fprintf('\nFailed to download Kaleido.\n');
    fprintf('https://github.com/plotly/Kaleido/tags\n');
    fprintf('Please download a suitable Kaleido version for your system, and unzip the files in plotly/Kaleido folder.\n\n');
    return;
end
unzip(file,kDir);
status=1;
fprintf(' Done\n\n');


% THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION IS RELEASED "AS IS."  THE U.S. GOVERNMENT MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, CONCERNING THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  IN NO EVENT WILL THE U.S. GOVERNMENT BE LIABLE FOR ANY DAMAGES, INCLUDING ANY LOST PROFITS, LOST SAVINGS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, OR INABILITY TO USE, THIS SOFTWARE OR ANY ACCOMPANYING DOCUMENTATION, EVEN IF INFORMED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.
%
% change log:
%   040204 smw stub file
%
% file: get_r_ci_na_1s.m
%
function varargout = get_r_ci_na_1s(varargin)
  error('get_r_ci_na_1s is not part of current release.');
return;


function c = history(d)

%tstoolbox/@description/history
%   description/history
%
% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt

c = char(d.history);


function ft_destroy_buffer

% FT_DESTROY_BUFFER stops the thread with the TCP server attached to
% the local MATLAB instance and removes all data from memory.
%
% Use as
%   ft_destroy_buffer
%
% See also FT_CREATE_BUFFER

% Copyright (C) 2010, Stefan Klanke
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

% clearing the mex file from memory will cause the function registered with
% mexAtExit to be executed. This function will then stop the threads and
% release all allocated memory to the operating system
clear buffer


path_to_scatnet = fileparts(mfilename('fullpath'));

addpath(fullfile(path_to_scatnet, 'classification'));
addpath(fullfile(path_to_scatnet, 'convolution'));
addpath(fullfile(path_to_scatnet, 'core'));
addpath(genpath(fullfile(path_to_scatnet, 'demo')));
addpath(fullfile(path_to_scatnet, 'display'));
addpath(fullfile(path_to_scatnet, 'filters'));
addpath(fullfile(path_to_scatnet, 'filters/selesnick'));
addpath(fullfile(path_to_scatnet, 'utils'));
addpath(genpath(fullfile(path_to_scatnet, 'papers')));
addpath(fullfile(path_to_scatnet, 'scatutils'));
addpath(genpath(fullfile(path_to_scatnet, 'unittest')));
addpath(fullfile(path_to_scatnet, 'utils'));
addpath(fullfile(path_to_scatnet, 'reconstruction'));

clear path_to_scatnet;


%--- help for embed ---
%
%  INTERNAL FUNCTION: Maps the data into proper lag/stacked form
%
%


classdef (Abstract) Attribute < matlabshared.libiio.base
    % Attribute IIO attribute function calls

    methods (Hidden)

        function setAttributeLongLong(obj,id,attr,value,isOutput,tol)
            phydev = getDev(obj, obj.phyDevName);
            chanPtr = iio_device_find_channel(obj,phydev,id,isOutput);%FIXME (INVERSION)
            status = cPtrCheck(obj,chanPtr);
            cstatus(obj,status,['Channel: ' id ' not found']);
            status = iio_channel_attr_write_longlong(obj,chanPtr,attr,value);
            cstatus(obj,status,['Attribute write failed for : ' attr ' with value ' num2str(value)]);
            % Check
            [status, rValue] = iio_channel_attr_read_longlong(obj,chanPtr,attr);
            cstatus(obj,status,['Error reading attribute: ' attr]);
            if nargin<6
                tol = sqrt(eps);
            end
            if abs(value - rValue) > tol
                status = -1;
                cstatus(obj,status,['Attribute ' attr ' return value ' num2str(rValue) ', expected ' num2str(value)]);
            end
        end

        function rValue = getAttributeLongLong(obj,id,attr,isOutput)
            phydev = getDev(obj, obj.phyDevName);
            chanPtr = iio_device_find_channel(obj,phydev,id,isOutput);%FIXME (INVERSION)
            status = cPtrCheck(obj,chanPtr);
            cstatus(obj,status,['Channel: ' id ' not found']);
            [status, rValue] = iio_channel_attr_read_longlong(obj,chanPtr,attr);
            cstatus(obj,status,['Error reading attribute: ' attr]);
        end

        function setAttributeBool(obj,id,attr,value,isOutput)
            phydev = getDev(obj, obj.phyDevName);
            chanPtr = iio_device_find_channel(obj,phydev,id,isOutput);%FIXME (INVERSION)
            status = cPtrCheck(obj,chanPtr);
            cstatus(obj,status,['Channel: ' id ' not found']);
            status = iio_channel_attr_write_bool(obj,chanPtr,attr,value);
            cstatus(obj,status,['Attribute write failed for : ' attr]);
            % Check
            [status, rValue] = iio_channel_attr_read_bool(obj,chanPtr,attr);
            cstatus(obj,status,['Error reading attribute: ' attr]);
            if value ~= rValue
                status = -1;
                cstatus(obj,status,['Attribute ' attr ' return value ' num2str(rValue) ', expected ' num2str(value)]);
            end
        end

        function rValue = getAttributeBool(obj,id,attr,isOutput)
            phydev = getDev(obj, obj.phyDevName);
            chanPtr = iio_device_find_channel(obj,phydev,id,isOutput);%FIXME (INVERSION)
            status = cPtrCheck(obj,chanPtr);
            cstatus(obj,status,['Channel: ' id ' not found']);
            [status, rValue] = iio_channel_attr_read_bool(obj,chanPtr,attr);
            cstatus(obj,status,['Error reading attribute: ' attr]);
        end

        function setAttributeRAW(obj,id,attr,value,isOutput)
            phydev = getDev(obj, obj.phyDevName);
            chanPtr = iio_device_find_channel(obj,phydev,id,isOutput);%FIXME (INVERSION)
            status = cPtrCheck(obj,chanPtr);
            cstatus(obj,status,['Channel: ' id ' not found']);
            bytes = iio_channel_attr_write(obj,chanPtr,attr,value);
            if bytes <= 0
                status = -1;
                cstatus(obj,status,['Attribute write failed for : ' attr ' with value ' value]);
            end
        end

        function rValue = getAttributeRAW(obj,id,attr,isOutput)
            phydev = getDev(obj, obj.phyDevName);
            chanPtr = iio_device_find_channel(obj,phydev,id,isOutput);%FIXME (INVERSION)
            status = cPtrCheck(obj,chanPtr);
            cstatus(obj,status,['Channel: ' id ' not found']);
            [status, rValue] = iio_channel_attr_read(obj,chanPtr,attr,1024);
            cstatus(obj,status,['Error reading attribute: ' attr]);
        end

        function setDeviceAttributeRAW(obj,attr,value)
            phydev = getDev(obj, obj.phyDevName);
            bytes = iio_device_attr_write(obj,phydev,attr,value);
            if bytes <= 0
                status = -1;
                cstatus(obj,status,['Attribute write failed for : ' attr ' with value ' value]);
            end
        end

        function rValue = getDeviceAttributeRAW(obj,attr)
            phydev = getDev(obj, obj.phyDevName);
            [status, rValue] = iio_device_attr_read(obj,phydev,attr);
            cstatus(obj,status,['Error reading attribute: ' attr]);
        end

    end
end


function cleanup(obj)
% remove temporary files created by prepare
%
% cleanup(obj)
%
% Inputs:
%   obj                 MOcovMFileCollection instance
%
% Notes:
% - this function should be called after coverage has been determined.
%
% See also: rewrite_mfiles, prepare

    notify(obj.monitor,'Cleanup');
    if ~isempty(obj.orig_path)
        notify(obj.monitor,'','Resetting path');
        path(obj.orig_path);
    end

    if ~isempty(obj.temp_dir)
        msg=sprintf('Removing temporary files in %s',obj.temp_dir);
        notify(obj.monitor,'',msg);

        if mocov_util_platform_is_octave()
            % GNU Octave requires, by default, confirmation when using
            % rmdir. The state of confirm_recursive_rmdir is stored,
            % and set back to its original value when leaving this
            % function.
            confirm_val=confirm_recursive_rmdir(false);
            cleaner=onCleanup(@()confirm_recursive_rmdir(confirm_val));
        end

        rmdir(obj.temp_dir,'s');
    end


classdef MimZoomPlugin < MimGuiPlugin
    % MimZoomPlugin. Gui Plugin for using a preset bone window/level
    %
    %     You should not use this class within your own code. It is intended to
    %     be used by the gui of the TD MIM Toolkit.
    %
    %     MimZoomPlugin is a Gui Plugin for the MIM Toolkit.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties
        ButtonText = 'Zoom'
        SelectedText = 'Zoom'
        ToolTip = 'Enables Matlab''s zoom tool'
        Category = 'Tools'
        Visibility = 'Dataset'
        Mode = 'Toolbar'

        HidePluginInDisplay = false
        PTKVersion = '1'
        ButtonWidth = 6
        ButtonHeight = 1
        Icon = 'zoom.png'
        Location = 15
    end

    methods (Static)
        function RunGuiPlugin(gui_app)
            gui_app.ImagePanel.SetControl('Zoom');
        end

        function enabled = IsEnabled(gui_app)
            enabled = gui_app.IsDatasetLoaded;
        end

        function is_selected = IsSelected(gui_app)
            is_selected = strcmp(gui_app.ImagePanel.SelectedControl, 'Zoom');
        end

    end
end


%By Manas ranjan Das%
function varargout = untitled(varargin)
% UNTITLED M-file for untitled.fig
%      UNTITLED, by itself, creates a new UNTITLED or raises the existing
%      singleton*.
%
%      H = UNTITLED returns the handle to a new UNTITLED or the handle to
%      the existing singleton*.
%
%      UNTITLED('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in UNTITLED.M with the given input arguments.
%
%      UNTITLED('Property','Value',...) creates a new UNTITLED or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before untitled_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to untitled_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help untitled

% Last Modified by GUIDE v7.5 01-Dec-2010 02:35:10

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @untitled_OpeningFcn, ...
                   'gui_OutputFcn',  @untitled_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before untitled is made visible.
function untitled_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to untitled (see VARARGIN)

% Choose default command line output for untitled
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes untitled wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = untitled_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function edit2_Callback(hObject, eventdata, handles)
% hObject    handle to edit2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit2 as text
%        str2double(get(hObject,'String')) returns contents of edit2 as a double

% --- Executes during object creation, after setting all properties.
function edit2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function edit3_Callback(hObject, eventdata, handles)
% hObject    handle to edit3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit3 as text
%        str2double(get(hObject,'String')) returns contents of edit3 as a double

% --- Executes during object creation, after setting all properties.
function edit3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
freq=str2double(get(handles.edit1,'String'));
er=str2double(get(handles.edit2,'String'));
h=str2double(get(handles.edit3,'String'));
height = h/1000*2.54;
Width=30.0/(2.0*freq)*sqrt(2.0/(er+1.0))*10;
ereff=(er+1.0)/2.0+(er-1)/(2.0*sqrt(1.0+12.0*height/Width));
dl=0.412*height*((ereff+0.3)*(Width/height+0.264))/((ereff-0.258)*(Width/...
    height+0.8));
lamda=30.0/(freq*sqrt(ereff));
lamda0=30.0/freq;
Leff=lamda/2;
L=Leff-2*dl;
Length = L*10;
k0=2*pi*freq/30;
phi1=0:360;
theta1=0:180;
phi=phi1./180.*pi;
theta=theta1./180.*pi;

Rr=120*lamda0/(1-k0^2*height^2/24);
Radiation_resistance = Rr;

set(handles.text4,'String',Length);
set(handles.text5,'String',Width);
set(handles.text11,'String',Radiation_resistance);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Radiation patterns
% Plotting of radiation patterns on polar and rectangular co-ordinate  system

% Calculating the normalized field values for polar plot
Etheta=sin(k0*height/2.*cos(theta)).*cos(k0*L/2.*cos(theta))/k0/height*...
    2./cos(theta);
Ethetamax=max(Etheta);
Ethetanor=Etheta./Ethetamax;

Ephi=sin(k0*Width/2.*cos(phi)).*sin(phi)/k0/Width*2./cos(phi);
Ephimax=max(Ephi);
Ephinor=Ephi./Ephimax;
axes(handles.axes1);
cla;

polar(theta,Ethetanor,'-r')
hold on;
polar(phi,Ephinor,'-b')
title('Radiation plot of E and H plane patterns');
% title('E- and H-plane Patterns of Rectangular Microstrip Antenna',...
%     'fontsize',[12]);
legend('E plane','H plane');

% Space wave, surface wave and gain calculations

k0d=k0*height;

%Space wave power
Psp = 377*k0^2*k0d^2/3/pi*(1-1/ereff+2/5/ereff^2);

%Surface wave power
s=sqrt(ereff-1);
k0ds=k0d*s;
alpha0=s*tan(k0ds);
alpha1=-[tan(k0ds)+k0ds/(cos(k0ds))^2];
x0d=ereff^2-alpha1^2;
x0n=-ereff^2+alpha0*alpha1+ereff*sqrt(ereff^2-2*alpha0*alpha1+alpha0^2);
x0 = 1+x0n/x0d;

Psur = 377*k0^2/4*ereff*(x0^2-1)/[ereff*[1/sqrt(x0^2-1)+sqrt(x0^2-1)/(...
    ereff-x0^2)]+k0d*[1+ereff^2*(x0^2-1)/(ereff-x0^2)]];

Efficiency=Psp/(Psp+Psur);

Gain=10*log10(Efficiency*2*pi*Leff*Width/lamda0);

set(handles.text14,'String',Efficiency);
set(handles.text15,'String',Gain);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% recessed feedline width
% characteristic impedance

x=30*pi/sqrt(er)/50-0.441;

if sqrt(er)*50 <= 120
    W0=height*x;
else
    W0=height*(0.85-sqrt(0.6-x));
end
% Width_of_microstrip_feed=W0;

if W0/height <= 1
    Z0=60/sqrt(ereff)*log(8*height/W0+W0/4/height);
else
    Z0=120*pi/sqrt(ereff)*inv(W0/height+1.393+.667*log(W0/height+1.444));
end
% characteristic_Impedance = Z0
set(handles.text17,'String',Z0);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes during object creation, after setting all properties.
function text1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to text1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


function result = postfix(str)
    if isempty(str)
        result = '';
    else
        result = sprintf('_%s', str);
    end
end


classdef CoreTextFileWriter < CoreBaseClass
    % CoreTextFileWriter. A helper class to assist with writing a text file
    %
    %
    %     Licence
    %     -------
    %     Part of CoreMat. https://github.com/tomdoel/coremat
    %     Author: Tom Doel, 2013.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties
        FileText
        FileId
    end

    methods
        function obj = CoreTextFileWriter(file_path, file_name, reporting)
            full_file_name = fullfile(file_path, file_name);
            file_id = fopen(full_file_name, 'w');

            if (file_id == -1)
                reporting.Error('CoreTextFileWriter:CannotOpenFile', ['Unable to open file ' full_file_name]);
            else
                obj.FileId = file_id;
            end
        end

        function Close(obj)
            if ~isempty(obj.FileId)
                fclose(obj.FileId);
                obj.FileId = [];
            end
        end

        function delete(obj)
            obj.Close;
        end

        function WriteLine(obj, text)
            fprintf(obj.FileId, [strrep(text, '%', '%%') '\r\n']);
        end

        function is_eof = Eof(obj)
            is_eof = isempty(obj.FileId);
        end
    end
end


function handleKey(dummy1,dummy2)
global finish
finish = 1;
fprintf('Execution interrupted by keypress.\n');
end % by pressing any key, the process will exit


%--- help for prepare_transition_routine ---
%
%  INTERNAL FUNCTION
%
%
%    Other functions named prepare_transition_routine
%
%       dsge/prepare_transition_routine
%       generic/prepare_transition_routine
%


% This script defines a project shortcut.
%
% To get a handle to the current project use the following function:
%
% project = simulinkproject();
%
% You can use the fields of project to get information about the currently
% loaded project.
%
% See: help simulinkproject

Simulink.fileGenControl('reset')

close all;
clear all;


function addQuitMenuItem()
    % ADDQUITMENUITEM add quit menu to main file menu
    hQuit=findall(gcf,'Label','Quit Zmap');
    if isempty(hQuit)
        mainfile=findall(gcf,'Tag','figMenuFile');
        uimenu(mainfile,'Label','Quit Zmap','Separator','on','MenuSelectedFcn',@(~,~)restartZmap);
    end
end


function item = cfg_exbranch(varargin)

% This is the exbranch configuration item class
%
% Data structure
% ==============
% Description fields
%    * name  - display name of config item
%    * tag   - tag of the menu item
%    * val   - 1xn cell array of cfg_items
%    * check - (optional) function handle to implement configuration
%              specific subsasgn checks based on the harvested subtree
%              rooted at this node
%    * help  - help text
% GUI/job manager fields
%    * expanded
%    * hidden
% All fields above are inherited from the branch configuration item class.
%    * prog
%    * vfiles
%    * modality
%    * vout  - function handle that generates sout struct
%    * sout  - source dependency description
%    * jout  - saved output (will be referenced by harvest of a dependency
%              target for dependency resolution at job runtime)
%    * tdeps - list where this branch is target of a dependency
%    * sdeps - list where this branch is source of a dependency
%    * chk   - field to save check status from cfg_item.check callbacks
%    * id    - id of this cfg_exbranch. This is used to reference the
%              cfg_exbranch in cfg_dep objects.
%
% Public Methods
% ==============
%    * get_strings - returns name of object
%    * gettag      - returns tag
%    * help        - returns help text
%    * harvest
%    * all_set
%
% * 'executable branch'  - See branch for details on inherited fields
%
% The layout of the configuration tree and the types of configuration items
% have been kept compatible to a configuration system and job manager
% implementation in SPM5 (Statistical Parametric Mapping, Copyright (C)
% 2005 Wellcome Department of Imaging Neuroscience). This code has been
% completely rewritten based on an object oriented model of the
% configuration tree.
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: cfg_exbranch.m 5678 2013-10-11 14:58:04Z volkmar $

rev = '$Rev: 5678 $'; %#ok

myclass = mfilename;
% Get local fields and defaults from private/mysubs_fields
[fn, defs] = mysubs_fields;

if nargin == 1
    if isstruct(varargin{1})
        % assume input is a struct to be converted back into a class
        % return with error if this does not work
        if numel(fieldnames(varargin{1})) == numel(fn)+1 && ...
                all(isfield(varargin{1}, [fn(:)' {'cfg_branch'}]))
            bitem = varargin{1}.cfg_branch;
            sitem = rmfield(varargin{1},{'cfg_branch'});
            item  = class(sitem, myclass, bitem);
            return;
        else
            cfg_message('matlabbatch:constructor:reclassify', ['Don''t know how to convert this ' ...
                                'into class ''%s''.'], myclass);
        end;
    end;
    if isa(varargin{1},myclass)
        item = varargin{1};
        return;
    end;
end;

mxpnargin = 5; % Max 5 arguments to parent initialisation
pnargin = min([nargin, mxpnargin]);
switch nargin
    case 0
        bitem = cfg_branch;
    case 1
        if isa(varargin{1},myclass)
            item = varargin{1};
            return;
        elseif isstruct(varargin{1})
            % assume input is a struct to be converted back into a class
            % no fieldname checking performed here
            bitem = varargin{1}.cfg_branch;
            sitem = rmfield(varargin{1},'cfg_branch');
            item  = class(sitem, myclass, bitem);
            return;
        else
            bitem = cfg_branch(varargin{1});
        end;
    case {2,3,4,5,6,7,8,9,10}
        bitem = cfg_branch(varargin{1:pnargin});
    otherwise
        cfg_message('matlabbatch:constructor:nargin', 'Wrong number of arguments.');
end;
for k=1:numel(fn)
    sitem.(fn{k})=defs{k};
end;
item = class(sitem, myclass, bitem);
% set additional fields (if any) - field order as in mysubs_fields
for k = 1:min(numel(fn),nargin-mxpnargin)
    item.(fn{k}) = varargin{k+mxpnargin};
end;