function  hout = pdbplot(ID, varargin)
%PDBPLOT plots the 3-D backbone structure of proteins according to the
%Protein Data Bank database
%
%   PDBPLOT(PDBID) retrieves 3-D information for an entry, PDBID, from the
%   PDB database and plots the 3-D backbone structure of the specified
%   protein. PDBID can also be the name of a PDB structure or a file
%   containing a PDB structure.
% 
%   PDBPLOT(..., 'PLOTMODE', 'MAINCHAIN') specifies that the protein's
%   polypeptide backbone be plotted as the series of bonds connecting
%   the alpha-carbon, the carbonyl carbon, the nitrogen, and the oxygen of
%   the protein's backbone. The default is 'BACKBONE' which displays only
%   the alpha-carbon backbone.
% 
%   PDBPLOT(..., 'COLORMODE', C) specifies how the plot is colored. Options
%   are 'atom', 'chain', and 'secondary'. The 'atom' option provides a
%   different color for each atom represented in the graph. Green, blue,
%   and red represent the carbon, nitrogen, and oxygen atoms, respectively.
%   The 'chain' option colors the entire structure in one color. The
%   'secondary' option provides a color for each secondary structure.
%   Alpha-helix, beta-sheet, turn, helix (non alpha), and others are
%   colored yellow, blue, grey, cyan, and green, respectively. The default
%   is 'chain'.
% 
%   PDBPLOT(..., 'SHOWLABEL', true) turns on the labels that represent each
%   amino acid name and sequence number in the protein. The default is
%   false.
% 
%   FIG = PDBPLOT(...) returns a handle to the PDB plot figure. 
% 
%   See
%   www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=808
%   for more on viewing PDB molecules in MATLAB. 
% 
%   Example:
%
%       % Plot the backbone of Insulin-Like-Growth-Factor-1
%       pdbplot('1B9G')
%
%   See also GETPDB, PDBREAD, PDBDISTPLOT, PROTEINPLOT, RAMACHANDRAN.

%   PDBPLOT(..., 'SHOWALPHAC', true) shows spheres that represents alpha
%   carbon atoms. The default is false.

%   Copyright 2003-2004 The MathWorks, Inc. 
%   $Revision: 1.1.12.1 $  $Date: 2004/12/24 20:44:51 $

% Set defaults
plotmode = 'backbone';
colormode = 'chain';
showlabel = false;
showalphac = false;

nvarargin = numel(varargin);
if nvarargin
    if rem(nvarargin,2)
        error('Bioinfo:pdbplot:IncorrectNumberOfArguments',...
            'Incorrect number of arguments to %s.',mfilename);
    end
    okargs = {'plotmode','colormode','showlabel','showalphac'};
    for j=1:2:nvarargin
        pname = varargin{j};
        pval = varargin{j+1};
        k = strmatch(lower(pname), okargs);%#ok 
        if isempty(k)
            error('Bioinfo:pdbplot:UnknownParameterName',...
                'Unknown parameter name: %s.',pname);
        elseif length(k)>1
            error('Bioinfo:pdbplot:AmbiguousParameterName',...
                'Ambiguous parameter name: %s.',pname);
        else
            switch(k)
                case 1 % plotmode
                    plotOptions = {'backbone','mainchain'};
                    plotmode = strmatch(lower(pval),plotOptions); %#ok
                    if isempty(plotmode) 
                      error('Bioinfo:pdbplot:NotValidPlotMode','Not a valid option for PLOTMODE.')
                    end
                    plotmode = plotOptions{plotmode};
                case 2 % colormode
                    colorOptions = {'chain','atom','secondary'};
                    colormode = strmatch(lower(pval),colorOptions); %#ok
                    if isempty(colormode) 
                      error('Bioinfo:pdbplot:NotValidColorMode','Not a valid option for COLORMODE.')
                    end
                    colormode = colorOptions{colormode};
                case 3 % showlabel
                    showlabel = opttf(pval);  
                case 4 % showalphac
                    showalphac = opttf(pval);
            end
        end
    end
end

%read the pdb entry
%ID must either a structure, a pdb file, or a valid PDBID.
try
    if (~isstruct(ID))
        if exist(ID,'file')
            pdbstruct = pdbread(ID);
            [path,name,ext] = fileparts(ID); %#ok 
            id_name = sprintf('%s%s',name,ext);
        else
            pdbstruct = getpdb(ID);
            id_name = ID;
        end
    else
        pdbstruct = ID;
        id_name = inputname(1);
    end
catch
    error('Bioinfo:pdbplot:InvalidInput', ...
        'The input should be a structure of data, a pdb file, or a valid PDBID.');
end

pdb_name = sprintf('PDB Plot - %s', id_name);
% Graphics and UI parts
hFig = figure('Visible','off',...
              'Menubar', 'none',...
              'Toolbar', 'none',...
              'Numbertitle','off',...
              'Tag', 'pdbplot',...
              'Name', pdb_name,...
              'Color', 'black',...
              'DeleteFcn', @deleteFcn);
hMainAxes = gca;
set(hMainAxes, 'Position',[0 0 0.8 1],...
         'Tag', 'mainAxes',...
         'Visible', 'off',...
         'DataAspectRatio', [1 1 1]);

% Get title or compond information
id_label = '';
if isfield(pdbstruct, 'Title')
    id_label = ['Title:  ', pdbstruct.Title];
elseif isfield(pdbstruct, 'Compound')
    id_label = ['Compound:  ', pdbstruct.Compound];
end

hBottomPanel = [];
hCInfoPanel = [];
hAxes = [];
  
viewMenuGroup = [];
plotMenuGroup=[];
colorMenuGroup=[];

viewControlGroup = [];
plotControlGroup = [];
colorControlGroup = [];

cColor = [0.0 1.0 0.0]; %Carbon atom color - green
nColor = [0.0, 0.0, 1.0]; %Nitrogen atom color - blue
oColor = [1.0, 0.0, 0.0]; %Oxygen atom color - red
caColor = [1.0, 0.6, 0.3]; % Alpha carbon sphere color - orange
chainColor = [0.0, 1.0, 0.0]; %Chain single color - green
aHColor = [1.0, 1.0, 0.0]; %Alpha helix - yellow
bSColor = [0.0, 0.0, 1.0]; %Beta-strand sheet - blue
tNColor = [0.8, 0.8, 0.8]; %Turn - gray
hXColor = [0.0, 1.0, 1.0]; %Helix (non alpha) - cyan

createPanels(id_label);
hVCPanel=createViewControlPanel;
createMenubar

cameratoolbar;
light;
light('Position',[-1 -1 -2]);
% cla;
%----------------------------------------------------------- 
seqInfo = getSeqPlotInfo;
initplotpdb;

set(hFig, 'Visible','on') 
set(hFig,'ResizeFcn',@resizePDBPlot);
if (nargout > 0)
    hout = hFig;
end
  
%---------Subfunctions------------------------------------
function seqInfo = getSeqPlotInfo()
    numSequences = numel(pdbstruct.Sequence);
    seqInfo=cell(1, numSequences);
    for seq = 1:numSequences
        % get IDs for current chain
        chainID =  pdbstruct.Sequence(seq).ChainID;
        % get coords of Atoms and HeterogenAtoms
        chainCoords = [pdbstruct.Atom.chainID]' == chainID;
        % Create Nx3 matrix of 3D coords
        tmpStruct = pdbstruct.Atom(chainCoords);
        % Get an array of amino acid struct
        aminoacids = [];
        numOfAA = 0;
        for i = 1:numel(tmpStruct)
            %   PDB file list order N CA C O for each amino acid
            if (strcmp(tmpStruct(i).AtomName, 'CA') == 1)
                numOfAA = numOfAA +1;
                aminoacids(numOfAA).resName = tmpStruct(i).resName;
                aminoacids(numOfAA).resSeq = tmpStruct(i).resSeq;
                aminoacids(numOfAA).N.X = tmpStruct(i-1).X;
                aminoacids(numOfAA).N.Y = tmpStruct(i-1).Y;
                aminoacids(numOfAA).N.Z = tmpStruct(i-1).Z;
                aminoacids(numOfAA).CA.X = tmpStruct(i).X;
                aminoacids(numOfAA).CA.Y = tmpStruct(i).Y;
                aminoacids(numOfAA).CA.Z = tmpStruct(i).Z;
                aminoacids(numOfAA).C.X = tmpStruct(i+1).X;
                aminoacids(numOfAA).C.Y = tmpStruct(i+1).Y;
                aminoacids(numOfAA).C.Z = tmpStruct(i+1).Z;
                aminoacids(numOfAA).O.X = tmpStruct(i+2).X;
                aminoacids(numOfAA).O.Y = tmpStruct(i+2).Y;
                aminoacids(numOfAA).O.Z = tmpStruct(i+2).Z;
                aminoacids(numOfAA).color = chainColor;
            end
        end

    % Find secondary structures and add color field to amino acid structure
    if isfield(pdbstruct, 'Helix')
        numHelix = numel(pdbstruct.Helix);
        for j=1:numHelix
            if pdbstruct.Helix(j).helixClass == 1
                tmpColor = aHColor;
            else
                tmpColor = hXColor;
            end
            for n = pdbstruct.Helix(j).initSeqNum : pdbstruct.Helix(j).endSeqNum
                aminoacids(n).color = tmpColor;
            end
        end
    end

    % Sheet
    if isfield(pdbstruct, 'Sheet')
        numSheet = numel(pdbstruct.Sheet);
        for j=1:numSheet
            for n = pdbstruct.Sheet(j).initSeqNum : pdbstruct.Sheet(j).endSeqNum
                aminoacids(n).color = bSColor;
            end
        end
    end

    % Turn
    if isfield(pdbstruct, 'Turn')
        numTurn = numel(pdbstruct.Turn);
        for j=1:numTurn
            for n = pdbstruct.Turn(j).initSeqNum : pdbstruct.Turn(j).endSeqNum
                aminoacids(n).color = tNColor;
            end
        end
    end
    
    seqInfo{seq} = aminoacids;
    end
end
%-----------------------------------------------------------
function h1 = drawChain(coord1, coord2, color)
    h1 = line('XData',[coord1.X, coord2.X],...
    'YData', [coord1.Y, coord2.Y],...
    'ZData', [coord1.Z, coord2.Z],...
    'Linewidth', 0.3,...
    'color', color);
end
%----------------------------------------------------------------
function [h1, h2]=drawBond(coord1, coord2, color1, color2)
    h1 = line('XData',[coord1.X, (coord1.X + coord2.X)/2],...
    'YData', [coord1.Y, (coord1.Y + coord2.Y)/2],...
    'ZData', [coord1.Z, (coord1.Z + coord2.Z)/2],...
    'Linewidth', 0.3,...
    'color', color1);

    h2 = line('XData',[(coord1.X + coord2.X)/2, coord2.X],...
    'YData', [(coord1.Y + coord2.Y)/2, coord2.Y],...
    'ZData', [(coord1.Z + coord2.Z)/2, coord2.Z],...
    'Linewidth', 0.3,...
    'color', color2);
end
%---------------------------------------------
    function plotSecondaryMC
        % Plot seconday structure in main chain
        for seqs = 1:length(seqInfo)
            aminoacids = seqInfo{seqs};
            links = length(aminoacids);
            for i=1:links
                drawChain(aminoacids(i).N, aminoacids(i).CA, aminoacids(i).color);
                drawChain(aminoacids(i).CA, aminoacids(i).C, aminoacids(i).color);
                drawChain(aminoacids(i).C, aminoacids(i).O, aminoacids(i).color);
                if i < links
                    drawBond(aminoacids(i).C, aminoacids(i+1).N, aminoacids(i).color, aminoacids(i+1).color);
                end
            end
        end
    end
%----------------------------------------------------
    function plotBackbone
        for seqs = 1:length(seqInfo)
            % Plot connecting alpha carbons
            aminoacids = seqInfo{seqs};
            links = length(aminoacids);
            for i=1:links-1
                drawChain(aminoacids(i).CA, aminoacids(i+1).CA, chainColor);
            end
        end
    end
%---------------------------------------------
    function plotSecondaryBB
        % Plot seconday structure in backbone
        for seqs = 1:length(seqInfo)
            aminoacids = seqInfo{seqs};
            links = length(aminoacids);
            for i=1:links-1
                drawBond(aminoacids(i).CA, aminoacids(i+1).CA, aminoacids(i).color, aminoacids(i+1).color);
            end
        end
    end
%---------------------------------------------
    function plotColorAtom
        for seqs = 1:length(seqInfo)
            aminoacids = seqInfo{seqs};
            links = length(aminoacids);
            for i=1:links
                drawBond(aminoacids(i).N, aminoacids(i).CA, nColor, cColor);
                drawBond(aminoacids(i).CA, aminoacids(i).C, cColor, cColor);
                drawBond(aminoacids(i).C, aminoacids(i).O, cColor, oColor);
                if i < links
                    drawBond(aminoacids(i).C, aminoacids(i+1).N, cColor, nColor);
                end
            end
        end
    end
%---------------------------------------------
    function plotMainChain
        for seqs = 1:length(seqInfo)
            aminoacids = seqInfo{seqs};
            links = length(aminoacids);
            for i=1:links
                drawChain(aminoacids(i).N, aminoacids(i).CA, chainColor);
                drawChain(aminoacids(i).CA, aminoacids(i).C, chainColor);
                drawChain(aminoacids(i).C, aminoacids(i).O, chainColor);
                if i < links
                    drawChain(aminoacids(i).C, aminoacids(i+1).N, chainColor);
                end
            end
        end
    end
%---------------------------------------------
    function showLabels
        for seqs = 1:length(seqInfo)
            aminoacids = seqInfo{seqs};
            links = length(aminoacids);
            for i=1:links
                text(aminoacids(i).CA.X+0.5,...
                    aminoacids(i).CA.Y+1,...
                    aminoacids(i).CA.Z,...
                    [aminoacids(i).resName num2str(aminoacids(i).resSeq)],...
                    'color', [1.0, 1.0, 1.0],...
                    'FontSize', 7);
            end
        end
    end
%---------------------------------------------
    function showAlphaC
        for seqs = 1:length(seqInfo)
            aminoacids = seqInfo{seqs};
            links = length(aminoacids);
            [x,y,z] = sphere(20);
            r = 0.2;
            for i=1:links
                surface('XData', aminoacids(i).CA.X + r*x,...
                    'YData', aminoacids(i).CA.Y + r*y,...
                    'ZData', aminoacids(i).CA.Z + r*z,...
                    'FaceColor', caColor,...
                    'EdgeColor', 'none',...
                    'FaceLighting','gouraud',...
                    'meshstyle', 'row',...
                    'linewidth', 3);
            end
        end
    end
%----------------------------------------------
    function plotpdb
       set(hFig,'CurrentAxes',hMainAxes)
       cla;
%         light;
%         light('Position',[-1 -1 -2]);
        switch plotmode
            case 'backbone'
                if isequal(colormode, 'secondary')
                    plotSecondaryBB;
                else % default atom
                    plotBackbone;
                end
            case 'mainchain'
                if isequal(colormode, 'atom')
                    plotColorAtom;
                elseif isequal(colormode, 'secondary')
                    plotSecondaryMC;
                else % default chain
                    plotMainChain;
                end
        end
        showMarkers;
        colorInfoHelp(colormode)
    end

    function initplotpdb
        plotpdb;
        makePlotCurrent;
        makeViewCurrent(colormode);
        makeViewCurrent('showlabel');
        makeViewCurrent('showalphac');
    end

    function showMarkers
         if showlabel
            showLabels;
        end

        if showalphac
            showAlphaC;
        end
    end

%--------------------
    function createPanels(id_label)
        units = 'Pixels';
        hFigPos = getpixelposition(hFig);
        % Create bottom panel
        hBottomPanel = uipanel('Parent',hFig,...
            'Tag','BottomPanel',...
            'BorderType','none',...
            'Units',units,...
            'Position',[1 1 hFigPos(3) 21]);

        posPanel = [1 1 hFigPos(3) 20];
        %%%
        hTitlePanel = uipanel('Parent',hBottomPanel,...
            'Units',units, ...
            'Position',posPanel,...
            'Bordertype','none');
        %%%
        hTitleLabel = uicontrol('Parent',hTitlePanel,...
            'Style','text',...
            'String',id_label, ...
            'Units',units,...
            'BackgroundColor', get(hTitlePanel,'BackgroundColor'));

        labelExtent = get(hTitleLabel,'Extent');
        posLabel = [posPanel(1) posPanel(2) labelExtent(3) labelExtent(4)];
        set(hTitleLabel,'Position',posLabel);
    end

%---------------------
    function createMenubar
        filemenu = uimenu(hFig, 'Label','&File','Tag','file menu');
        viewmenu = uimenu(hFig, 'Label','&View','Tag','view menu');
        helpmenu = uimenu(hFig, 'Label','&Help','Tag','help menu');

        % File menu
        uimenu(filemenu,'Label','Save to Figure file',...
            'Tag','save menu',...
            'Callback',@save_cb);

        uimenu(filemenu,'Label','Print',...
            'Tag','printMenu',...
            'Callback',@print_cb);

        uimenu(filemenu,'Label','&Close','Accelerator','W',...
            'Separator','on', 'Tag', 'closePDBPlot',...
            'Callback',@closePDBPlot);
        uimenu(filemenu,'Label','Close &All',...
            'Tag', 'closeAllPDBPlot',...
            'Callback',@closeAllPDBPlots);

        % View menu
        backboneItem = createViewMenuItem(viewmenu,'&Backbone','backbone');
        mainchainItem = createViewMenuItem(viewmenu,'Main &Chain','mainchain');
        coloratomItem = createViewMenuItem(viewmenu,'Color &Atom','atom','Separator','on');
        colorsecondItem = createViewMenuItem(viewmenu,'Color &Secondary','secondary');
        showlabelItem = createViewMenuItem(viewmenu,'Show Labels','showlabel', 'Separator','on');
%         showalphacItem = createViewMenuItem(viewmenu,'Show Alpha Carbon','showalphac');

        viewMenuGroup = [coloratomItem, colorsecondItem,...
                         showlabelItem];
        plotMenuGroup = [backboneItem, mainchainItem];
        colorMenuGroup = [coloratomItem, colorsecondItem];
        
        % Help menu
        bioinfostandardhelp(helpmenu);
    end

%-----------------------------------------------  
   function menuH = createViewMenuItem(parent,labelname,tag, varargin)
     % CREATEVIEWMENUITEM Creates a view menu Item and connects its behavior
     %    to the behavior of the controls with same name.
   
     menu_tag = [tag, ' menu'];     
     control = findobj(hFig,'tag',tag);
     if isempty(control)
       menuH = [];
       return;
     end
     
     menuH = uimenu(parent,'Label',labelname,'Tag',menu_tag,varargin{:});
     if isempty(findobj(plotControlGroup, 'Tag', tag))
         set(menuH,'Callback',@view_cb);
     else
         set(menuH,'Callback',@plot_cb);
     end
   end



%------------View Control panel----------------------
    function hVCPanel = createViewControlPanel
        %
        % Create the view control panel.
        %
        hFigPos = getpixelposition(hFig);
        hVCPanel = uipanel('parent', hFig, ...
            'units', 'pixels', ...
            'position', [hFigPos(3)-120, 21,120,hFigPos(4)-20]);

       plotControlGroup = createRadioPanel(hVCPanel,... %#ok 
            [0.05, 0.74, .9, 0.23],...
            'Plot',...
            {'backbone', 'mainchain'},...
            {'Backbone', 'Main Chain'},...
            {'Plot backbone', 'Plot main chain'});

        colorControlGroup = createCheckboxPanel(hVCPanel,... %#ok 
            [0.05, 0.47, .9, 0.23],...
            'Color',...
            {'atom', 'secondary'},...
            {'Atoms', 'Secondary'},...
            {'Color atoms', 'Color secondary structures'});

%         hShowControls = createCheckboxPanel(hVCPanel,...
%             [0.05, 0.19, .9, 0.23],...
%             'Show',...
%             {'showlabel', 'showalphac'},...
%             {'Labels', 'Alpha carbons'},...
%             {'Show labels', 'Show alpha carbons'});
        
          hShowControls = createCheckboxPanel(hVCPanel,... %#ok 
            [0.05, 0.19, .9, 0.23],...
            'Show',...
            {'showlabel'},...
            {'Labels'},...
            {'Show labels'});
        
        viewControlGroup = [colorControlGroup, hShowControls];
        
        hCInfoPanel = uipanel('parent', hVCPanel,...
            'units', 'normalized', ...
            'position', [0.05, 0.01, .9, 0.15],...
            'Tag','cTablePanel',...
            'BorderType','none',...
            'backgroundcolor', 'black');
    end

    function hControls = createCheckboxPanel(hParentPanel, panelPos, panelTitle, ctrlTags, ctrlLabels, ctrlTooltips)

        bgColor = get(hParentPanel, 'BackgroundColor');
        hPanel = uipanel('parent', hParentPanel, ...
            'units', 'normalized', ...
            'position', panelPos,...
            'title', panelTitle,...
            'titlePosition', 'lefttop',...
            'BackgroundColor', bgColor);
        hControls = zeros(1, length(ctrlTags));
        for i = 1:length(ctrlTags);
            hControls(i) = uicontrol('Parent', hPanel, ...
                'Units', 'characters', ...
                'Style', 'checkbox', ...
                'Tag', ctrlTags{i}, ...
                'HorizontalAlignment', 'right', ...
                'BackgroundColor', bgColor, ...
                'String', ctrlLabels{i}, ...
                'TooltipString', ctrlTooltips{i},...
                'callback', @view_cb);
        end

        % Position the check box
        labelExtents = get(hControls,'extent');
        if length(hControls) > 1
            labelExtents = [labelExtents{:}];
            maxExtentLength = max(labelExtents(3:4:end));
            maxExtentHeight = max(labelExtents(4:4:end));
        else
            maxExtentLength = max(labelExtents(3));
            maxExtentHeight = max(labelExtents(4));
        end

        for i = 1:length(hControls)
            set(hControls(i), 'position', [1, 5-(i-1)*2-maxExtentHeight, maxExtentLength+3, maxExtentHeight]);
        end

    end

    function hControls = createRadioPanel(hParentPanel, panelPos, panelTitle, ctrlTags, ctrlLabels, ctrlTooltips)
        bgColor = get(hParentPanel, 'BackgroundColor');
        hRadioGrp = uibuttongroup('Parent',hParentPanel,...
            'Tag','radioPanel',...
            'units', 'normalized', ...
            'TitlePosition','lefttop',...
            'Title',panelTitle,...
            'position', panelPos,...
            'BackgroundColor', bgColor);

        hControls = zeros(1, length(ctrlTags));
        for i = 1:length(ctrlTags);
            hControls(i) = uicontrol('Parent', hRadioGrp, ...
                'Units', 'characters', ...
                'Style', 'radiobutton', ...
                'Tag', ctrlTags{i}, ...
                'HorizontalAlignment', 'right', ...
                'BackgroundColor', bgColor, ...
                'String', ctrlLabels{i}, ...
                'TooltipString', ctrlTooltips{i});
        end

        % Position the radiobuttons
        labelExtents = get(hControls,'extent');
        labelExtents = [labelExtents{:}];
        maxExtentLength = max(labelExtents(3:4:end));
        maxExtentHeight = max(labelExtents(4:4:end));

        for i = 1:length(hControls)
            set(hControls(i), 'position', [1, 5-(i-1)*2-maxExtentHeight, maxExtentLength+3, maxExtentHeight]);
        end

        set(hRadioGrp,'SelectionChangeFcn',@plotRadioSelect);
    end        

%----------------------------------
    function managePlots(hSrc,event)
        % Manage mutually exclusive itmes on plot controls and menus
        type = lower(get(hSrc,'type'));

        if strcmp(type,'uimenu')
            % caller is the menu item
            tg = strrep(get(hSrc,'tag'),' menu','');
            hSrcControlPeer = findall(plotControlGroup,'tag',tg);
            if get(hSrcControlPeer,'Value')==1
                set(hSrcControlPeer,'Value',0);
            else
                set(hSrcControlPeer,'Value',1);
            end
        else
            hSrcControlPeer=hSrc;
        end          
        plotControlChange(hSrcControlPeer,event);         
    end

%------------------------------------------
    function plotControlChange(hSrc,event)%#ok 
        menu_tag = [get(hSrc,'tag'),' menu'];
        hSrcMenuPeer = findobj(plotMenuGroup,'tag',menu_tag);      
        otherMenu = plotMenuGroup(plotMenuGroup~=hSrcMenuPeer);
        if get(hSrc,'Value')== 1
            plotmode = get(hSrc,'tag');
            set(otherMenu,'Checked','off');
            set(hSrcMenuPeer,'Checked','on');
        else
            plotmode = strrep(get(otherMenu,'tag'), ' menu','');
            set(hSrcMenuPeer,'Checked','off');
            set(otherMenu, 'Checked', 'on');
            set(plotControlGroup(plotControlGroup~=hSrc), 'Value', 1);
        end
    end
%-------------------
    function makePlotCurrent
        plotCtrl = findobj(plotControlGroup, 'Tag', plotmode);
        plotControlChange(plotCtrl,[]);
    end

%----------------------------------
    function manageViews(hSrc,event)
        type = lower(get(hSrc,'type'));

        if strcmp(type,'uimenu')
            % caller is the menu item
            tg = strrep(get(hSrc,'tag'),' menu','');
            hSrcControlPeer = findall(viewControlGroup,'tag',tg);
            if get(hSrcControlPeer,'Value')==1
                set(hSrcControlPeer,'Value',0);
            else
                set(hSrcControlPeer,'Value',1);
            end
        else
            hSrcControlPeer=hSrc;
        end
            
        viewControlChange(hSrcControlPeer,event);        
    end
%------------------------------------------
    function viewControlChange(hSrc,event) %#ok 
        menu_tag = [get(hSrc,'tag'),' menu'];
        hSrcMenuPeer = findobj(colorMenuGroup,'tag',menu_tag);

        if isempty(hSrcMenuPeer)
            hSrcMenuPeer = findobj(viewMenuGroup,'tag',menu_tag);
            menuGrp = hSrcMenuPeer;
            controlGrp = hSrc;
        else
            menuGrp = colorMenuGroup;
            controlGrp = colorControlGroup;
        end
        otherMenu = menuGrp(menuGrp~=hSrcMenuPeer);
        
        if get(hSrc,'Value')== 1
            if isempty(otherMenu) % not colormode
                if strcmpi(get(hSrc,'tag'),'showlabel')==1
                    showlabel=true;
                elseif strcmpi(get(hSrc,'tag'),'showalphac')==1
                    showalphac=true;
                end
            else
                set(controlGrp(controlGrp~=hSrc),'Value',0)
                set(otherMenu,'Checked','off');
                colormode = get(hSrc,'tag');
            end
            set(hSrcMenuPeer,'Checked','on');
            
        else
            set(menuGrp,'Checked','off');
            if isempty(otherMenu)
                if strcmpi(get(hSrc,'tag'),'showlabel')==1
                    showlabel=false;
                elseif strcmpi(get(hSrc,'tag'),'showalphac')==1
                    showalphac=false;
                end
            else
                colormode = 'chain';
            end
        end
    end

%-------------------
    function makeViewCurrent(viewmode)
        modeControl = findobj(viewControlGroup, 'Tag', viewmode);
        if strcmpi(get(modeControl,'tag'),'showlabel')==1
            if showlabel
                set(modeControl, 'Value', 1);
            else
                set(modeControl, 'Value', 0);
            end
        elseif strcmpi(get(modeControl,'tag'),'showalphac')==1
            if showalphac
                set(modeControl, 'Value', 1);
            else
                set(modeControl, 'Value', 0);
            end
        else
            set(modeControl, 'Value', 1);
        end
        viewControlChange(modeControl,[]);
    end

%--------------------------------------------------
  function resizePDBPlot(hSrc,event) %#ok
  
    figPos = getpixelposition(hFig);
    
    % Make sure hViewControlPane moves L/R as window shrinks/grows.
    viewControlPos = getpixelposition(hVCPanel);
    viewControlPos(1) = figPos(3) - viewControlPos(3);
    viewControlPos(4) = figPos(4) - 21;
    setpixelposition(hVCPanel,viewControlPos);

    % Update hBottomPanel width to match figure width
    bottomPanelPos = getpixelposition(hBottomPanel);
    bottomPanelPos(3) = figPos(3);
    setpixelposition(hBottomPanel,bottomPanelPos);    

  end

 %------------------------------------------------
    function colorInfoHelp(colormode)
        if strcmpi(colormode, 'chain') == 1
            % Not need info
            if ~isempty(hAxes)
            cla(hAxes);
            end
            set(hCInfoPanel, 'backgroundcolor', get(get(hCInfoPanel, 'parent'), 'backgroundColor'));
        else
            set(hCInfoPanel, 'backgroundcolor', 'black');
            if isempty(hAxes)
                hAxes = axes('parent', hCInfoPanel,...
                    'tag', 'colorInfoAxes',...
                    'position', [0,0, 1, 1],...
                    'visible', 'off');
            end
            cla(hAxes);
%             'position', [10, pos(4)+6-iLoop*14],...
            if strcmpi(colormode, 'secondary') == 1
                color_labels = {'\alpha Helix', '\beta Sheet', 'Turn', 'Helix'};
                colors = {aHColor, bSColor, tNColor, hXColor};
                for iLoop = 1:length(color_labels)
                    text('parent', hAxes,...
                        'Units', 'normalized',...
                        'position', [0.25, 0.9-(iLoop-1)*.25],...
                        'Color', colors{iLoop},...
                        'String', color_labels{iLoop});
                end
            else
                color_labels = {'C', 'N', 'O'};
                colors = {cColor, nColor, oColor};
                for iLoop = 1:length(color_labels)
                    text('parent', hAxes,...
                        'Units', 'normalized',...
                        'position', [0.1+(iLoop-1)*0.3, 0.5],...
                        'Color', colors{iLoop},...
                        'String', color_labels{iLoop});
                end
            end
        end
    end 
  

%---------Callbacks-------------------- 
    function plot_cb(hSrc, event)
        managePlots(hSrc, event);
        plotpdb;
    end

    function view_cb(hSrc, event)
        manageViews(hSrc, event);
        plotpdb;
    end

    function plotRadioSelect(hSrc, event)
        % Makes the plot associated with the selected radio button
        plotControlChange(get(hSrc, 'SelectedObject'), event);
        plotpdb;
    end

    function print_cb(hSrc, event) %#ok
        old_axes = findobj(hFig, 'type', 'axes');
        if length(old_axes) > 1 % Because there may be colorInfoAxes
            old_axes = findobj(old_axes, 'tag', 'mainAxes');
        end
            
        h_figure = figure('Visible', 'off');
        
        copyobj(old_axes, h_figure);
        printdlg(h_figure);
        delete(h_figure);
    end

    function save_cb(hSrc, event) %#ok
        old_axes = findobj(hFig, 'type', 'axes');
        if length(old_axes) > 1 % Because there may be colorInfoAxes
            old_axes = findobj(old_axes, 'tag', 'mainAxes');
        end
        h_figure = figure('Visible', 'off');

        copyobj(old_axes, h_figure);
        
        [fname,pname] = uiputfile({'*.fig', 'Figure file'},'Save As');

        if ischar(fname) && ischar(pname)
            set(h_figure,'Visible','on')
            hgsave(h_figure,fullfile(pname,fname));
        end
        delete(h_figure);
    end

%-----------------------------------------------
    function closePDBPlot(obj,evt)%#ok
        close(hFig);
    end

%-----------------------------------------------
    function closeAllPDBPlots(obj, evt)%#ok
        figs = findall(0,'Type','figure','Tag','pdbplot');
        close(figs)
    end

%---------------------------------------------
    function deleteFcn(obj,eventData)%#ok
        if ishandle(hFig)
            delete(hFig);
        end
    end
%-------------------------------------------------
    function bioinfostandardhelp(helpmenu)
        % BIOINFOSTANDARDHELP Add Toolbox, Demos, and About to help menu.
        uimenu(helpmenu, 'Label', 'Bioinformatics &Toolbox Help', ...
            'Callback', @(varargin) doc('bioinfo/'));
        uimenu(helpmenu, 'Label', 'Bioinformatics Toolbox &Demos', ...
            'Callback', @(varargin) demo('toolbox','bioinformatics'), ...
            'Separator', 'on');
        uimenu(helpmenu, 'Label', 'About Bioinformatics Toolbox', ...
            'Callback', @bioinfoabout, ...
            'Separator', 'on');
    end

    function bioinfoabout(varargin)%#ok
        %BIOINFOABOUT About the Bioinformatics Toolbox.

        tlbx = ver('bioinfo');
        tlbx = tlbx(1);
        str = sprintf('%s %s\nCopyright 1993-%s The MathWorks, Inc.', ...
            tlbx.Name, tlbx.Version, datestr(tlbx.Date, 10));
        msgbox(str,tlbx.Name,'modal');
    end

end
