#!/usr/bin/env python3
from Bio.PDB import *
import math, glob
import os, sys, subprocess
import textwrap
import numpy as np
import pandas as pd
import shutil
import io
import warnings
import tempfile
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
from mpl_toolkits.mplot3d import Axes3D
from PyQt5.QtGui import QPalette, QColor
from PyQt5.QtCore import Qt, QProcess,  pyqtSlot
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox, QDesktopWidget
import errno
from prody import *
from prody.atomic import Atomic, Atom, AtomGroup, Selection, HierView
from prody.utilities import openFile, showFigure, createStringIO, wrapModes
from prody import SETTINGS, PY3K
_version_ = str("v0.6")
plt.rcParams['savefig.dpi'] = 600
ICO = b" "
parser = PDBParser(PERMISSIVE=1)
WORK_PATH = os.path.expanduser('~')


def gromacs_flag(name):
    try:
        devnull = open(os.devnull)
        subprocess.Popen([name], stdout=devnull, stderr=devnull).communicate()
    except OSError as e:
        if e.errno == errno.ENOENT:
            return False
    return True

def iconFromBase64(base64):
    pixmap = QtGui.QPixmap()
    pixmap.loadFromData(QtCore.QByteArray.fromBase64(base64))
    icon = QtGui.QIcon(pixmap)
    return icon

def countModel(file):
    k = 0
    with open(file, 'r') as f:
        for line in f:
            words = line.split()
            for i in words:
                if(i=='MODEL'):
                    k=k+1
    return k
def is_multi_pdb_file(fpath):
    return os.path.isfile(fpath) and os.path.getsize(fpath) > 0 and countModel(fpath)

_help=''' 
    
                                                                                                G_Measures               
                                             
    #########################################################################

    The "Geometric Measures" script that was developed to carry out geometric analysis on protein structures.
    This script support as input MultiPDB files, and the avaliable analysis are: 
    
    1 - Pincer angle.
                            
    Select the residues that will be used to measure the pincer angle. 
   

                (1)              (3)
                    \              /
                      \          /
                        \      /
                          \  / 
                          (2)
    
    2 - Dihedral angle.

    Select the residues that will be used to measure the dihedral angle. 
    

                     (1)             (4)
                       |                 |
                       |                 |
                       |                 |
                       |                 |
                     (2)----------(3)
        
    3 - Triangle area.

    Select the residues that will be used to measure the triangle area. 
    

                            AC
                (1)------------(3)
                    \                /
         AB        \            /     BC
                       \         /
                         \     / 
                          (2)
                            
                           


    4 - PDF (Probability Density Function)
    The Functional Density Function is calculated using different values ​​of mainchain dihedral angles from the considered residue, the mainchain conformation of the equivalent residue between frames.
    
    5 - RMSD

    Compares two protein structures frames (first frame the first frame with the consecutive frames) by computing the root mean square deviation (RMSD).

    6 - RG

    Computes the radius of gyration of the protein and the radii of gyration about the x-, y- and z-axes, as a function of frames.

    7 - FEL
    FEL represents a mapping of all possible conformations a molecule adopted during a simulation, together with their corresponding energy reported as the Gibbs Free Energy. FEL are represented using two variables that reflect specific properties of the system and measure conformational variability. RG measure the torsion angle around a specific bond or the radius of gyration of the protein, and the the RMSD measure the deviation with respective native state (First frame).


The GROMACS program (http://www.gromacs.org/) is required for the 'Converter' and 'FEL' tools.
The only recognized trajectory file format for G_Measures is multi-PDB.
If the user has only XTC trajectory files, the 'Converter' tool can be used.
Click Browse ..., select the multi-PDB file and follow the steps shown in the status bar.

Thank you for using G_Measures!
G_Measures Team
'''
    
def showProtein(*atoms, **kwargs):
    """Show protein representation using :meth:`~mpl_toolkits.mplot3d.Axes3D`.
    This function is designed for generating a quick view of the contents of a
    :class:`~.AtomGroup` or :class:`~.Selection`.    

    Protein atoms matching ``"calpha"`` selection are displayed using solid
    lines by picking a random and unique color per chain.  Line with can
    be adjusted using *lw* argument, e.g. ``lw=12``. Default width is 4.
    Chain colors can be overwritten using chain identifier as in ``A='green'``.

    Water molecule oxygen atoms are represented by red colored circles.  Color
    can be changed using *water* keyword argument, e.g. ``water='aqua'``.
    Water marker and size can be changed using *wmarker* and *wsize* keywords,
    defaults values are ``wmarker='.', wsize=6``.

    Hetero atoms matching ``"hetero and noh"`` selection are represented by
    circles and unique colors are picked at random on a per residue basis.
    Colors can be customized using residue name as in ``NAH='purple'``.  Note
    that this will color all distinct residues with the same name in the same
    color.  Hetero atom marker and size can be changed using *hmarker* and
    *hsize* keywords, default values are ``hmarker='o', hsize=6``.

    ProDy will set the size of axis so the representation is not distorted when
    the shape of figure window is close to a square.  Colors are picked at
    random, except for water oxygens which will always be colored red.
    
    *** Interactive 3D Rendering in Jupyter Notebook ***
    
    If py3Dmol has been imported then it will be used instead to display 
    an interactive viewer.  See :func:`view3D`
    
    
    """

    from prody.dynamics.mode import Mode

    method = kwargs.pop('draw', None)
    modes = kwargs.get('mode', None)
    scale = kwargs.get('scale', 100)

    # modes need to be specifically a list or a tuple (cannot be an array)
    if modes is None:
        n_modes = 0
    else:
        modes = wrapModes(modes)
        n_modes = len(modes)

    if method is None:
        import sys        
        if 'py3Dmol' in sys.modules: 
            method = 'py3Dmol'
        else:
            method = 'matplotlib'
    method = method.lower()
        
    alist = atoms
    for atoms in alist:
        if not isinstance(atoms, Atomic):
            raise TypeError('atoms must be an Atomic instance')
            
    if n_modes and n_modes != len(alist):
        raise RuntimeError('the number of proteins ({0}) does not match that of the modes ({1}).'
                            .format(len(alist), n_modes))

    if '3dmol' in method:
        mol = view3D(*alist, **kwargs)
        return mol
    else:
        import matplotlib.pyplot as plt
        from mpl_toolkits.mplot3d import Axes3D
        cf = plt.gcf()
        show = None
        for child in cf.get_children():
            if isinstance(child, Axes3D):
                show = child
                break
        if show is None:
            show = Axes3D(cf)
        from matplotlib import colors
        cnames = dict(colors.cnames)
        wcolor = kwargs.get('water', 'red').lower()
        avoid = np.array(colors.hex2color(cnames.pop(wcolor, cnames.pop('red'))))
        for cn, val in cnames.copy().items():  # PY3K: OK
            clr = np.array(colors.hex2color(val))
            if clr.sum() > 2.4:
                cnames.pop(cn)
            elif np.abs(avoid - clr).sum() <= 0.6:
                cnames.pop(cn)
        cnames = list(cnames)
        import random
        random.shuffle(cnames)
        cnames_copy = list(cnames)
        min_ = list()
        max_ = list()
        for i, atoms in enumerate(alist):
            if isinstance(atoms, AtomGroup):
                title = atoms.getTitle()
            else:
                title = atoms.getAtomGroup().getTitle()
            calpha = atoms.select('calpha')
            if calpha:
                partition = False
                mode = modes[i] if n_modes else None
                if mode is not None:
                    is3d = False
                    try:
                        arr = mode.getArray()
                        is3d = mode.is3d()
                        n_nodes = mode.numAtoms()
                    except AttributeError:
                        arr = mode
                        is3d = len(arr) == len(calpha)*3
                        n_nodes = len(arr)//3 if is3d else len(arr)
                    if n_nodes != len(calpha):
                        raise RuntimeError('size mismatch between the protein ({0} residues) and the mode ({1} nodes).'
                                            .format(len(calpha), n_nodes))
                    partition = not is3d

                if partition:
                    xyz = calpha._getCoords()
                    chids = calpha.getChids()
                    rbody = []
                    last_sign = np.sign(arr[0])
                    last_chid = chids[0]
                    rcolor = ['red', 'red', 'blue']
                    n = 1
                    for i,a in enumerate(arr):
                        s = np.sign(a)
                        ch = chids[i]
                        if s == 0: s = last_sign
                        if last_sign != s or i == len(arr)-1 or last_chid != ch:
                            if last_chid == ch:
                                rbody.append(i)
                            show.plot(xyz[rbody, 0], xyz[rbody, 1], xyz[rbody, 2],
                                      label=title + '_regid%d'%n,
                                      color=rcolor[int(last_sign+1)],
                                      lw=kwargs.get('lw', 4))
                            rbody = []
                            n += 1
                            last_sign = s
                            last_chid = ch
                        rbody.append(i)
                else:
                    for ch in HierView(calpha, chain=True):
                        xyz = ch._getCoords()
                        chid = ch.getChid()
                        if len(cnames) == 0:
                            cnames = list(cnames_copy)
                        show.plot(xyz[:, 0], xyz[:, 1], xyz[:, 2],
                                label=title + '_' + chid,
                                color=kwargs.get(chid, cnames.pop()).lower(),
                                lw=kwargs.get('lw', 4))
                    
                    if mode is not None:
                        from prody.utilities.drawtools import drawArrow3D
                        XYZ = calpha._getCoords()
                        arr = arr.reshape((n_nodes, 3))
                        XYZ2 = XYZ + arr * scale
                        for i, xyz in enumerate(XYZ):
                            xyz2 = XYZ2[i]
                            mutation_scale = kwargs.pop('mutation_scale', 10)
                            drawArrow3D(xyz, xyz2, mutation_scale=mutation_scale, **kwargs)

            water = atoms.select('water and noh')
            if water:
                xyz = atoms.select('water')._getCoords()
                show.plot(xyz[:, 0], xyz[:, 1], xyz[:, 2], label=title + '_water',
                          color=wcolor,
                          ls='None', marker=kwargs.get('wmarker', '.'),
                          ms=kwargs.get('wsize', 6))
            hetero = atoms.select('not protein and not nucleic and not water')
            if hetero:
                for res in HierView(hetero).iterResidues():
                    xyz = res._getCoords()
                    resname = res.getResname()
                    resnum = str(res.getResnum())
                    chid = res.getChid()
                    if len(cnames) == 0:
                        cnames = list(cnames_copy)
                    show.plot(xyz[:, 0], xyz[:, 1], xyz[:, 2], ls='None',
                              color=kwargs.get(resname, cnames.pop()).lower(),
                              label=title + '_' + chid + '_' + resname + resnum,
                              marker=kwargs.get('hmarker', 'o'),
                              ms=kwargs.get('hsize', 6))
            xyz = atoms._getCoords()
            min_.append(xyz.min(0))
            max_.append(xyz.max(0))

        show.set_xlabel('x')
        show.set_ylabel('y')
        show.set_zlabel('z')
        min_ = np.array(min_).min(0)
        max_ = np.array(max_).max(0)
        center = (max_ + min_) / 2
        half = (max_ - min_).max() / 2
        show.set_xlim3d(center[0]-half, center[0]+half)
        show.set_ylim3d(center[1]-half, center[1]+half)
        show.set_zlim3d(center[2]-half, center[2]+half)
        show.legend(prop={'size': 10})
        plt.axis('off')
        plt.show()   
        
def showdialog(msgtitle,msgtxt):
        mb = QMessageBox()
        mb.setIcon(QMessageBox.Information)
        mb.setWindowTitle(msgtitle)
        mb.setText(msgtxt)
        mb.setStandardButtons(QMessageBox.Ok)
        mb.exec_()

class Ui_Help(object):
    def setupUi(self, Help):
        Help.setObjectName("Help")
        Help.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(Help)
        self.centralwidget.setObjectName("centralwidget")
        self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)
        self.scrollArea.setGeometry(QtCore.QRect(10, 10, 771, 511))
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 769, 509))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.plainTextEdit = QtWidgets.QPlainTextEdit(self.scrollAreaWidgetContents)
        self.plainTextEdit.setGeometry(QtCore.QRect(0, 0, 771, 511))
        self.plainTextEdit.setObjectName("plainTextEdit")
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(690, 530, 89, 25))
        self.pushButton.setObjectName("pushButton")
        Help.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(Help)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
        self.menubar.setObjectName("menubar")
        self.menuFile = QtWidgets.QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")
        Help.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(Help)
        self.statusbar.setObjectName("statusbar")
        Help.setStatusBar(self.statusbar)
        self.actionClose = QtWidgets.QAction(Help)
        self.actionClose.setObjectName("actionClose")
        self.menuFile.addAction(self.actionClose)
        self.menubar.addAction(self.menuFile.menuAction())

        self.retranslateUi(Help)
        QtCore.QMetaObject.connectSlotsByName(Help)



    def retranslateUi(self, Help):
        _translate = QtCore.QCoreApplication.translate
        Help.setWindowTitle(_translate("Help", "G_Measures " + _version_ +" - How to Use"))
        self.pushButton.setText(_translate("Help", "Close"))
        self.menuFile.setTitle(_translate("Help", "File"))
        self.actionClose.setText(_translate("Help", "Close"))

        ################################################ Help
        self.plainTextEdit.setReadOnly(True)
        self.plainTextEdit.setPlainText(_help)
        self.actionClose.triggered.connect(Help.close)
        self.pushButton.clicked.connect(Help.close)

class Ui_Converter(object):
    def setupUi(self, Converter):
        Converter.setObjectName("Converter")
        Converter.resize(800, 335)
        self.centralwidget = QtWidgets.QWidget(Converter)
        self.centralwidget.setObjectName("centralwidget")
        self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox.setGeometry(QtCore.QRect(10, 20, 771, 101))
        self.groupBox.setObjectName("groupBox")
        self.tpr_line = QtWidgets.QLineEdit(self.groupBox)
        self.tpr_line.setGeometry(QtCore.QRect(80, 30, 591, 20))
        self.tpr_line.setObjectName("tpr_line")
        self.bt_tpr = QtWidgets.QPushButton(self.groupBox)
        self.bt_tpr.setGeometry(QtCore.QRect(690, 30, 75, 23))
        self.bt_tpr.setObjectName("bt_tpr")
        self.xtc_line = QtWidgets.QLineEdit(self.groupBox)
        self.xtc_line.setGeometry(QtCore.QRect(80, 60, 591, 20))
        self.xtc_line.setObjectName("xtc_line")
        self.bt_xtc = QtWidgets.QPushButton(self.groupBox)
        self.bt_xtc.setGeometry(QtCore.QRect(690, 60, 75, 23))
        self.bt_xtc.setObjectName("bt_xtc")
        self.label = QtWidgets.QLabel(self.groupBox)
        self.label.setGeometry(QtCore.QRect(10, 30, 71, 16))
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.groupBox)
        self.label_2.setGeometry(QtCore.QRect(10, 60, 61, 16))
        self.label_2.setObjectName("label_2")
        self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox_2.setGeometry(QtCore.QRect(10, 160, 771, 121))
        self.groupBox_2.setObjectName("groupBox_2")
        self.pdb_line0 = QtWidgets.QLineEdit(self.groupBox_2)
        self.pdb_line0.setGeometry(QtCore.QRect(80, 30, 591, 20))
        self.pdb_line0.setObjectName("pdb_line0")
        self.bt_pdb0 = QtWidgets.QPushButton(self.groupBox_2)
        self.bt_pdb0.setGeometry(QtCore.QRect(690, 30, 75, 23))
        self.bt_pdb0.setObjectName("bt_pdb0")
        self.label_3 = QtWidgets.QLabel(self.groupBox_2)
        self.label_3.setGeometry(QtCore.QRect(10, 30, 71, 16))
        self.label_3.setObjectName("label_3")
        self.line = QtWidgets.QFrame(self.centralwidget)
        self.line.setGeometry(QtCore.QRect(10, 270, 771, 16))
        self.line.setFrameShape(QtWidgets.QFrame.HLine)
        self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line.setObjectName("line")
        self.bt_convert = QtWidgets.QPushButton(self.centralwidget)
        self.bt_convert.setGeometry(QtCore.QRect(10, 230, 75, 23))
        self.bt_convert.setObjectName("bt_convert")
        self.bt_close = QtWidgets.QPushButton(self.centralwidget)
        self.bt_close.setGeometry(QtCore.QRect(90, 290, 75, 23))
        self.bt_close.setObjectName("bt_close")
        self.bt_cancel = QtWidgets.QPushButton(self.centralwidget)
        self.bt_cancel.setGeometry(QtCore.QRect(10, 290, 75, 23))
        self.bt_cancel.setObjectName("bt_cancel")
        Converter.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(Converter)
        self.statusbar.setObjectName("statusbar")
        Converter.setStatusBar(self.statusbar)
        

        self.retranslateUi(Converter)
        QtCore.QMetaObject.connectSlotsByName(Converter)

    def retranslateUi(self, Converter):
        _translate = QtCore.QCoreApplication.translate
        Converter.setWindowTitle(_translate("Converter", "G_Measures " + _version_ +" - Converter"))
        self.groupBox.setTitle(_translate("Converter", "Input files:"))
        self.bt_tpr.setText(_translate("Converter", "Browse"))
        self.bt_xtc.setText(_translate("Converter", "Browse"))
        self.label.setText(_translate("Converter", "TPR File:"))
        self.label_2.setText(_translate("Converter", "XTC File:"))
        self.groupBox_2.setTitle(_translate("Converter", "Output file:"))
        self.bt_pdb0.setText(_translate("Converter", "Browse"))
        self.label_3.setText(_translate("Converter", "PDB File:"))
        self.bt_convert.setText(_translate("Converter", "Convert"))
        self.bt_close.setText(_translate("Converter", "Close"))
        self.bt_cancel.setText(_translate("Converter", "Cancel"))
        
######################################################## converter
        self.tpr_line.setText('No select file.')
        self.tpr_line.setReadOnly(True)
        self.bt_tpr.clicked.connect(self.opentprfile)
        self.xtc_line.setText('No select file.')
        self.xtc_line.setReadOnly(True)
        self.bt_xtc.clicked.connect(self.openxtcfile)
        self.pdb_line0.setText('No file name.')
        self.pdb_line0.setReadOnly(True)
        self.bt_pdb0.clicked.connect(self.save_pdb)
        self.bt_convert.clicked.connect(self.ConvertingXTCFileToPDBFile)
        self.bt_cancel.clicked.connect(self.kill_process)
        self.bt_close.clicked.connect(Converter.close)
        self.process = QProcess()
        self.mylistofprocesses = []
########################################################
	
    
    def kill_process(self):
        self.process.terminate()
        # Wait for Xms and then elevate the situation to terminate
        if not self.process.waitForFinished(10000):
          self.process.kill()
        self.statusbar.showMessage('The process has been canceled.')


    def setupProcess(self):
        
        # Run the process with a given command
        if gromacs_flag('mdrun'):
            cmd ="echo 1, 1 |trjconv -f "+ self.xtc_file[0] +" -s "+ self.tpr_file[0] +" -o "+self.fileName0+" -pbc nojump -ur compact -center"
        elif gromacs_flag('gmx'):
            cmd ="echo 1, 1 |gmx trjconv -f "+ self.xtc_file[0] +" -s "+ self.tpr_file[0] +" -o "+self.fileName0+" -pbc nojump -ur compact -center"
        self.process.start('bash', ['-c', cmd])
        self.process.started.connect(lambda: self.bt_convert.setEnabled(False))
        self.process.finished.connect(lambda: self.bt_convert.setEnabled(True))
        self.process.finished.connect(lambda: self.pdb_line0.clear())
        self.process.finished.connect(lambda: self.xtc_line.clear())
        self.process.finished.connect(lambda: self.tpr_line.clear())
        self.mylistofprocesses.append(self.process)

        status = {QProcess.NotRunning: "Done !",
                  QProcess.Starting: "Starting",
                  QProcess.Running: "Please wait.. Trjconv is running.."}

        self.process.stateChanged.connect(lambda state: self.statusbar.showMessage(status[state]))


    def __del__(self):
        # If QApplication is closed attempt to kill the process
        self.process.terminate()
        # Wait for Xms and then elevate the situation to terminate
        if not self.process.waitForFinished(10000):
          self.process.kill()

    
    
    def opentprfile(self):
        try:
            tpr_dialog = QtWidgets.QFileDialog()
            self.tpr_file = tpr_dialog.getOpenFileName(None, "Select TPR file", WORK_PATH, "TPR files (*.tpr)")
            if os.path.isfile(self.tpr_file[0]):
                self.tpr_line.setText(self.tpr_file[0])
            else:
                self.tpr_line.setText('No select file.')
        except:
            pass

    def openxtcfile(self):
        try:
            xtc_dialog = QtWidgets.QFileDialog()
            self.xtc_file = xtc_dialog.getOpenFileName(None, "Select XTC file", WORK_PATH, "XTC files (*.xtc)")
            if os.path.isfile(self.xtc_file[0]):
                self.xtc_line.setText(self.xtc_file[0])
            else:
                self.xtc_line.setText('No select file.')
        except:
            pass

    def save_pdb(self):
        options = QtWidgets.QFileDialog.Options()
        options |= QtWidgets.QFileDialog.DontUseNativeDialog
        self.fileName, _ = QtWidgets.QFileDialog.getSaveFileName(None,"Save Multi-PDB file",""," Save PDB Files (*.pdb)", options=options)
        if self.fileName:
        	if self.fileName.endswith('.pdb'):
        		self.pdb_line0.setText(self.fileName)
        		self.fileName0 = self.fileName
        	else:
        		self.pdb_line0.setText(self.fileName+'.pdb')
        		self.fileName0 = self.fileName+'.pdb'
        else:
        	self.pdb_line0.setText('No select file.')
    

    def ConvertingXTCFileToPDBFile (self):
        if gromacs_flag('mdrun') or gromacs_flag ('gmx'):
        
            if self.xtc_file[0] and self.tpr_file[0] and self.fileName:
                if os.stat(self.xtc_file[0]).st_size and os.stat(self.tpr_file[0]).st_size != 0:
                    self.setupProcess()         
                else:
                    showdialog('Notice', 'XTC or TPR file not vaid')
            else:
                showdialog('Notice','TPR and XTC files must be selected.')
        else:
            showdialog('Notice', 'GROMACS program must be intalled')       
           
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 380)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.progressBar = QtWidgets.QProgressBar(self.centralwidget)
        self.progressBar.setGeometry(QtCore.QRect(10, 310, 771, 23))
        self.progressBar.setProperty("value", 24)
        self.progressBar.setObjectName("progressBar")
        self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox.setGeometry(QtCore.QRect(10, 20, 771, 91))
        self.groupBox.setObjectName("groupBox")
        self.pdb_line = QtWidgets.QLineEdit(self.groupBox)
        self.pdb_line.setGeometry(QtCore.QRect(10, 30, 671, 20))
        self.pdb_line.setObjectName("pdb_line")
        self.bt_process = QtWidgets.QPushButton(self.groupBox)
        self.bt_process.setGeometry(QtCore.QRect(10, 60, 75, 23))
        self.bt_process.setObjectName("bt_process")
        self.bt_pdb = QtWidgets.QPushButton(self.groupBox)
        self.bt_pdb.setGeometry(QtCore.QRect(690, 30, 75, 23))
        self.bt_pdb.setObjectName("bt_pdb")
        self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox_2.setGeometry(QtCore.QRect(10, 120, 771, 131))
        self.groupBox_2.setObjectName("groupBox_2")
        self.cb_tool = QtWidgets.QComboBox(self.groupBox_2)
        self.cb_tool.setGeometry(QtCore.QRect(50, 40, 131, 22))
        self.cb_tool.setObjectName("cb_tool")
        self.cb_chain = QtWidgets.QComboBox(self.groupBox_2)
        self.cb_chain.setGeometry(QtCore.QRect(60, 80, 51, 22))
        self.cb_chain.setObjectName("cb_chain")
        self.label_2 = QtWidgets.QLabel(self.groupBox_2)
        self.label_2.setGeometry(QtCore.QRect(10, 40, 47, 13))
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.groupBox_2)
        self.label_3.setGeometry(QtCore.QRect(10, 80, 47, 13))
        self.label_3.setObjectName("label_3")
        self.cb_res1 = QtWidgets.QComboBox(self.groupBox_2)
        self.cb_res1.setGeometry(QtCore.QRect(470, 70, 101, 22))
        self.cb_res1.setObjectName("cb_res1")
        self.label_4 = QtWidgets.QLabel(self.groupBox_2)
        self.label_4.setGeometry(QtCore.QRect(390, 70, 71, 16))
        self.label_4.setObjectName("label_4")
        self.label_5 = QtWidgets.QLabel(self.groupBox_2)
        self.label_5.setGeometry(QtCore.QRect(580, 70, 71, 16))
        self.label_5.setObjectName("label_5")
        self.cb_res2 = QtWidgets.QComboBox(self.groupBox_2)
        self.cb_res2.setGeometry(QtCore.QRect(660, 70, 101, 22))
        self.cb_res2.setObjectName("cb_res2")
        self.label_6 = QtWidgets.QLabel(self.groupBox_2)
        self.label_6.setGeometry(QtCore.QRect(390, 100, 71, 16))
        self.label_6.setObjectName("label_6")
        self.cb_res3 = QtWidgets.QComboBox(self.groupBox_2)
        self.cb_res3.setGeometry(QtCore.QRect(470, 100, 101, 22))
        self.cb_res3.setObjectName("cb_res3")
        self.cb_res4 = QtWidgets.QComboBox(self.groupBox_2)
        self.cb_res4.setGeometry(QtCore.QRect(660, 100, 101, 22))
        self.cb_res4.setObjectName("cb_res4")
        self.label_7 = QtWidgets.QLabel(self.groupBox_2)
        self.label_7.setGeometry(QtCore.QRect(580, 100, 71, 16))
        self.label_7.setObjectName("label_7")
        self.label_8 = QtWidgets.QLabel(self.groupBox_2)
        self.label_8.setGeometry(QtCore.QRect(390, 40, 101, 16))
        self.label_8.setObjectName("label_8")
        self.label_9 = QtWidgets.QLabel(self.groupBox_2)
        self.label_9.setGeometry(QtCore.QRect(570, 40, 91, 16))
        self.label_9.setObjectName("label_9")
        self.sb_initial = QtWidgets.QSpinBox(self.groupBox_2)
        self.sb_initial.setGeometry(QtCore.QRect(490, 40, 71, 22))
        self.sb_initial.setObjectName("sb_initial")
        self.sb_final = QtWidgets.QSpinBox(self.groupBox_2)
        self.sb_final.setGeometry(QtCore.QRect(660, 40, 71, 22))
        self.sb_final.setObjectName("sb_final")
        self.bt_plot = QtWidgets.QPushButton(self.centralwidget)
        self.bt_plot.setGeometry(QtCore.QRect(90, 260, 75, 23))
        self.bt_plot.setObjectName("bt_plot")
        self.bt_getcsv = QtWidgets.QPushButton(self.centralwidget)
        self.bt_getcsv.setGeometry(QtCore.QRect(180, 260, 111, 23))
        self.bt_getcsv.setObjectName("bt_getcsv")
        self.line = QtWidgets.QFrame(self.centralwidget)
        self.line.setGeometry(QtCore.QRect(10, 290, 771, 16))
        self.line.setFrameShape(QtWidgets.QFrame.HLine)
        self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line.setObjectName("line")
        self.bt_run = QtWidgets.QPushButton(self.centralwidget)
        self.bt_run.setGeometry(QtCore.QRect(10, 260, 75, 23))
        self.bt_run.setObjectName("bt_run")
        self.cb_selplot = QtWidgets.QComboBox(self.centralwidget)
        self.cb_selplot.setGeometry(QtCore.QRect(310, 260, 50, 23))
        self.cb_selplot.setObjectName("cb_selplot")
        self.label_10 = QtWidgets.QLabel(self.centralwidget)
        self.label_10.setGeometry(QtCore.QRect(350, 260, 100, 23))
        self.label_10.setObjectName("label_10")
        self.sb_frame = QtWidgets.QSpinBox(self.centralwidget)
        self.sb_frame.setGeometry(QtCore.QRect(430, 260, 75, 23))
        self.sb_frame.setObjectName("sb_frame")
        self.bt_getpdb = QtWidgets.QPushButton(self.centralwidget)
        self.bt_getpdb.setGeometry(QtCore.QRect(628, 260, 155, 23))
        self.bt_getpdb.setObjectName("bt_getpdb")
        self.bt_prot_view = QtWidgets.QPushButton(self.centralwidget)
        self.bt_prot_view.setGeometry(QtCore.QRect(520, 260, 100, 23))
        self.bt_prot_view.setObjectName("prot_view")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
        self.menubar.setObjectName("menubar")
        self.menuHelp = QtWidgets.QMenu(self.menubar)
        self.menuHelp.setObjectName("menuHelp")
        self.menuFile = QtWidgets.QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.actionAbout = QtWidgets.QAction(MainWindow)
        self.actionAbout.setObjectName("actionAbout")
        self.actionHow_to_use = QtWidgets.QAction(MainWindow)
        self.actionHow_to_use.setObjectName("actionHow_to_use")
        self.actionNew = QtWidgets.QAction(MainWindow)
        self.actionNew.setObjectName("actionNew")
        self.actionExit = QtWidgets.QAction(MainWindow)
        self.actionExit.setObjectName("actionExit")
        self.actionConverter = QtWidgets.QAction(MainWindow)
        self.actionConverter.setObjectName("actionConverter")
        self.menuHelp.addAction(self.actionAbout)
        self.menuHelp.addAction(self.actionHow_to_use)
        self.menuFile.addAction(self.actionNew)
        self.menuFile.addAction(self.actionConverter)
        self.menuFile.addAction(self.actionExit)
        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuHelp.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

########################################################## main

        self.progressBar.setProperty("value", 0)
        self.pdb_line.setObjectName("pdb_line")
        self.pdb_line.setText('No select file.')
        self.pdb_line.setReadOnly(True)
        self.bt_process.clicked.connect(self.preprocess)
        self.bt_process.setEnabled(False)
        self.bt_pdb.clicked.connect(self.openpdbfile)
        self.cb_tool.setObjectName("cb_tool")
        self.cb_tool.addItem("Pincer angle")
        self.cb_tool.addItem("Dihedral angle")
        self.cb_tool.addItem("Triangle area")
        self.cb_tool.addItem("PDF")
        self.cb_tool.addItem("RMSD")
        self.cb_tool.addItem("RG")
        self.cb_tool.addItem("FEL")
        self.cb_tool.currentIndexChanged.connect(self.res_hide)
        self.cb_tool.setEnabled(False)
        self.cb_selplot.addItem("2D")
        self.cb_selplot.addItem("3D")
        self.cb_selplot.setVisible(False)
        self.cb_chain.setEnabled(False)
        self.cb_res1.setEnabled(False)
        self.cb_res2.setEnabled(False)
        self.cb_res3.setEnabled(False)
        self.cb_res4.setEnabled(False)
        self.cb_res4.setVisible(False)
        self.label_7.setVisible(False)
        self.sb_initial.setEnabled(False)
        self.sb_final.setEnabled(False)
        self.bt_plot.setEnabled(False)
        self.bt_plot.clicked.connect(self.plottingData)
        self.bt_getcsv.clicked.connect(self.save_csv)
        self.bt_getcsv.setEnabled(False)
        self.bt_run.clicked.connect(self.run_tool)
        self.bt_prot_view.clicked.connect(self.proteinView)
        self.bt_prot_view.setEnabled(False)
        self.bt_run.setEnabled(False)
        self.bt_getpdb.setEnabled(False)
        self.sb_frame.setEnabled(False)
        self.bt_getpdb.clicked.connect(self.save_pdb)
        self.actionAbout.triggered.connect(self.showabout)
        self.actionConverter.triggered.connect(self.conVerter)
        self.actionHow_to_use.triggered.connect(self.heLp)
        self.actionNew.triggered.connect(self.new)
        self.actionExit.triggered.connect(QtWidgets.qApp.quit)
        self.process = QProcess()
        self.mylistofprocesses = []
##################################################################

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "G_Measures " + _version_))
        self.groupBox.setTitle(_translate("MainWindow", "Multi-PDB File:"))
        self.bt_process.setText(_translate("MainWindow", "Process"))
        self.bt_pdb.setText(_translate("MainWindow", "Browse"))
        self.groupBox_2.setTitle(_translate("MainWindow", "Analysis"))
        self.label_2.setText(_translate("MainWindow", "Tool:"))
        self.label_3.setText(_translate("MainWindow", "Chain:"))
        self.label_4.setText(_translate("MainWindow", "Residue 1:"))
        self.label_5.setText(_translate("MainWindow", "Residue 2:"))
        self.label_6.setText(_translate("MainWindow", "Residue 3:"))
        self.label_7.setText(_translate("MainWindow", "Residue 4:"))
        self.label_8.setText(_translate("MainWindow", "Initial Frame:"))
        self.label_9.setText(_translate("MainWindow", "Final Frame:"))
        self.label_10.setText(_translate("MainWindow", "Frame (10 ps):"))
        self.bt_plot.setText(_translate("MainWindow", "Plot"))
        self.bt_getcsv.setText(_translate("MainWindow", "Get CSV file"))
        self.bt_run.setText(_translate("MainWindow", "Run"))
        self.bt_getpdb.setText(_translate("MainWindow", "Get PDB time frame"))
        self.bt_prot_view.setText(_translate("MainWindow", "Show Protein"))
        self.menuHelp.setTitle(_translate("MainWindow", "Help"))
        self.menuFile.setTitle(_translate("MainWindow", "File"))
        self.actionAbout.setText(_translate("MainWindow", "About"))
        self.actionHow_to_use.setText(_translate("MainWindow", "How to use"))
        self.actionNew.setText(_translate("MainWindow", "New"))
        self.actionExit.setText(_translate("MainWindow", "Exit"))
        self.actionConverter.setText(_translate("MainWindow", "Converter"))
        
########################################################## main    
        self.TEMP_PATH = tempfile.mkdtemp()
        self.TABLE_PATH = self.TEMP_PATH+"/output.tbl"
        self.SHAM_PATH = self.TEMP_PATH+"/g_sham2.xvg"

    
    def conVerter(self):
        self.Converter = QtWidgets.QMainWindow()
        self.ui = Ui_Converter()
        self.ui.setupUi(self.Converter)
        self.Converter.show()

    def heLp(self):
        self.Help = QtWidgets.QMainWindow()
        self.ui = Ui_Help()
        self.ui.setupUi(self.Help)
        self.Help.show()

    def showabout(self):
        mb = QMessageBox()
        mb.setWindowTitle('About')
        mb.setText('''
                                                        G_Measures {}
The "Geometric Measures" script that was developed to carry out geometric analysis on protein structures.

Contributors:

Luciano Porto Kagami, Gustavo Machado das Neves, Luís Fernando Saraiva Macedo Timmers, Rafael Andrade Cáceres and Vera Lucia Eifler-Lima

         '''.format(_version_)   )
        mb.setStandardButtons(QMessageBox.Ok)
        mb.exec_()    
      
        # Calculate the differntial geometry for all residues (arc length, curvature, writhing, phi and psi)

    def setupProcess(self):
        
        # Run the process with a given command
        if gromacs_flag('mdrun'):
            cmd ='g_sham -f g_sham2.xvg -ls free-energy-landscape.xpm'
        elif gromacs_flag('gmx'):
            cmd = 'gmx sham -f g_sham2.xvg -ls free-energy-landscape.xpm'                    
        self.process.start('bash', ['-c', cmd])
        self.process.finished.connect(lambda: self.dataFEL())
        self.mylistofprocesses.append(self.process)

        status = {QProcess.NotRunning: "Please wait ..",
                  QProcess.Starting: "Starting",
                  QProcess.Running: "Please wait.. Sham is running.."}

        self.process.stateChanged.connect(lambda state: self.statusbar.showMessage(status[state]))
    
    def kill_process(self):
        self.process.terminate()
        # Wait for Xms and then elevate the situation to terminate
        if not self.process.waitForFinished(10000):
          self.process.kill()
        self.statusbar.showMessage('Process has canceled.')

    def res_hide(self):
        if self.cb_tool.currentText() == "Dihedral angle":
            self.label_4.setVisible(True)
            self.cb_res1.setVisible(True)
            self.label_5.setVisible(True)
            self.cb_res2.setVisible(True)
            self.label_6.setVisible(True)
            self.cb_res3.setVisible(True)
            self.label_7.setVisible(True)
            self.cb_res4.setVisible(True)
            try:
            	shutil.rmtree(self.TABLE_PATH)
            except:
            	pass
            self.bt_run.setEnabled(True)
            self.bt_getcsv.setEnabled(False)
            self.bt_plot.setEnabled(False)
            self.statusbar.showMessage('Ready. Select the protein chain, amino acid residues and frame range. After click on Run.')

        elif self.cb_tool.currentText() == "RMSD":
            self.label_4.setVisible(False)
            self.cb_res1.setVisible(False)
            self.label_5.setVisible(False)
            self.cb_res2.setVisible(False)
            self.label_6.setVisible(False)
            self.cb_res3.setVisible(False)
            self.label_7.setVisible(False)
            self.cb_res4.setVisible(False)
            try:
            	shutil.rmtree(self.TABLE_PATH)
            except:
            	pass
            self.bt_run.setEnabled(True)
            self.bt_getcsv.setEnabled(False)
            self.bt_plot.setEnabled(False)
            self.statusbar.showMessage('Ready. Select the protein chain and frame range. After click on Run.')

        elif self.cb_tool.currentText() == "Pincer angle":
            self.label_4.setVisible(True)
            self.cb_res1.setVisible(True)
            self.label_5.setVisible(True)
            self.cb_res2.setVisible(True)
            self.label_6.setVisible(True)
            self.cb_res3.setVisible(True)
            self.label_7.setVisible(False)
            self.cb_res4.setVisible(False)
            try:
            	shutil.rmtree(self.TABLE_PATH)
            except:
            	pass
            self.bt_run.setEnabled(True)
            self.bt_getcsv.setEnabled(False)
            self.bt_plot.setEnabled(False)
            self.statusbar.showMessage('Ready. Select the protein chain, amino acid residues and frame range. After click on Run.')

        elif self.cb_tool.currentText() == "PDF":
        	self.label_4.setVisible(False)
        	self.cb_res1.setVisible(False)
        	self.label_5.setVisible(False)
        	self.cb_res2.setVisible(False)
        	self.label_6.setVisible(False)
        	self.cb_res3.setVisible(False)
        	self.label_7.setVisible(False)
        	self.cb_res4.setVisible(False)
        	try:
        		shutil.rmtree(self.TEMP_PATH+'/data.csv')
        	except:
        		pass
        	self.bt_run.setEnabled(True)
        	self.bt_getcsv.setEnabled(False)
        	self.bt_plot.setEnabled(False)
        	self.statusbar.showMessage('Ready. Select the protein chain and frame range. After click on Run.')

        elif self.cb_tool.currentText() == "RG":
            self.label_4.setVisible(False)
            self.cb_res1.setVisible(False)
            self.label_5.setVisible(False)
            self.cb_res2.setVisible(False)
            self.label_6.setVisible(False)
            self.cb_res3.setVisible(False)
            self.label_7.setVisible(False)
            self.cb_res4.setVisible(False)
            try:
            	shutil.rmtree(self.TABLE_PATH)
            except:
            	pass
            self.bt_run.setEnabled(True)
            self.bt_getcsv.setEnabled(False)
            self.bt_plot.setEnabled(False)
            self.statusbar.showMessage('Ready. Select the protein chain and frame range. After click on Run.')

        elif self.cb_tool.currentText() == "FEL":
            self.label_4.setVisible(False)
            self.cb_res1.setVisible(False)
            self.label_5.setVisible(False)
            self.cb_res2.setVisible(False)
            self.label_6.setVisible(False)
            self.cb_res3.setVisible(False)
            self.label_7.setVisible(False)
            self.cb_res4.setVisible(False)
            self.cb_selplot.setVisible(True)
            try:
            	shutil.rmtree(self.SHAM_PATH)
            except:
            	pass
            self.bt_run.setEnabled(True)
            self.bt_getcsv.setEnabled(False)
            self.bt_plot.setEnabled(False)
            self.statusbar.showMessage('Ready. Select the protein chain and frame range. After click on Run.')
        
        else:
            self.label_4.setVisible(True)
            self.cb_res1.setVisible(True)
            self.label_5.setVisible(True)
            self.cb_res2.setVisible(True)
            self.label_6.setVisible(True)
            self.cb_res3.setVisible(True)
            self.label_7.setVisible(False)
            self.cb_res4.setVisible(False)
            self.statusbar.showMessage('Ready. Select the protein chain, amino acid residues and frame range. After click on Run.')

    
        

    def openpdbfile(self):
        try:
            pdb_dialog = QtWidgets.QFileDialog()
            self.pdb_file = pdb_dialog.getOpenFileName(None, "Select PDB file", WORK_PATH, "PDB files (*.pdb)")
            if os.path.isfile(self.pdb_file[0]):
                self.pdb_line.setText(self.pdb_file[0])
                self.bt_process.setEnabled(True)
                self.statusbar.showMessage('Click in Process ...')
            else:
                self.statusbar.showMessage('')
                self.pdb_line.setText('No select file.')
                self.bt_process.setEnabled(False)        
        except:
            self.statusbar.showMessage('')
            self.pdb_line.setText('No select file.')
            self.bt_process.setEnabled(False)
            self.statusbar.showMessage('')
            self.pdb_line.setText('No select file.')
            self.bt_process.setEnabled(False)
    def list_residues(self):
        res_list = []
        structure = parser.get_structure(self.TEMP_PATH+"/complex_1.pdb",  self.TEMP_PATH+"/complex_1.pdb")
        for model in structure:
            for chain in model:
                for residue in chain:
                    resname = residue.get_resname()
                    resnumber = residue.get_id()
                    if resname != 'HOH':
                        res_list.append(resname+'_'+str(resnumber[1]))
        return res_list
   
    def list_chain(self):
        chain_list = []
        structure = parser.get_structure(self.TEMP_PATH+"/complex_1.pdb",  self.TEMP_PATH+"/complex_1.pdb")
        for model in structure:
            for chain in model:
                chain_list.append(chain.get_id())
        return chain_list

    def preprocess(self):
    	self.statusbar.showMessage('Please wait...Recognizing the multi-PDB file.')
    	showdialog('Notice','Processing time varies by file size. Please wait until the end of the process.')
    	shutil.copy(self.pdb_file[0], self.TEMP_PATH+'/multipdb.pdb')
    	if is_multi_pdb_file(self.TEMP_PATH+'/multipdb.pdb'):
    		self.postprocess()
    	else:
    		showdialog('Error','This file is not a valid Multi-PDB format')
    		self.statusbar.showMessage('Error. Multi-PDB file not recognized.')
        
    def postprocess(self):        
        
        # Get the number of MODELS in the Multi-PDB file
        self.models = countModel(self.TEMP_PATH+'/multipdb.pdb')
        model = 1
        new_text = ""

        # Setting the progress bar
        self.progressBar.setMaximum(self.models)
        count = 0
        for line in open(self.TEMP_PATH+'/multipdb.pdb', "r"):
            line = line.strip()
            if line == "ENDMDL":
                output = open(self.TEMP_PATH+"/complex_" + str(model) + ".pdb", "w")
                output.write(new_text.strip())
                output.close()
                model += 1
                new_text = ""
                # Updating progress bar
                count += 1
                self.progressBar.setValue(count)

            else:
                new_text += line + "\n"
        res_list = self.list_residues()
        ch_list = self.list_chain()
        for item in res_list:
            self.cb_res1.addItem(item)
            self.cb_res2.addItem(item)
            self.cb_res3.addItem(item)
            self.cb_res4.addItem(item)
            
        for item in ch_list:
            self.cb_chain.addItem(str(item))
        self.sb_final.setMaximum(self.models)
        self.sb_final.setValue(self.models)
        self.sb_initial.setMinimum(1)
        self.cb_res1.setEnabled(True)
        self.cb_res2.setEnabled(True)
        self.cb_res3.setEnabled(True)
        self.cb_res4.setEnabled(True)
        self.sb_initial.setEnabled(True)
        self.sb_final.setEnabled(True)
        self.cb_chain.setEnabled(True)
        self.progressBar.setProperty("value", 0)
        self.bt_run.setEnabled(True)
        self.bt_process.setEnabled(False)
        self.bt_pdb.setEnabled(False)
        self.cb_tool.setEnabled(True)
        self.sb_frame.setMaximum(self.models)
        self.sb_frame.setMinimum(1)
        self.statusbar.showMessage('Ready. Select the protein chain, amino acid residues and frame range. After click on Run.')
    
    def dataFEL(self):
        xpm_file = 'free-energy-landscape.xpm'
        xpm_handle = open(xpm_file)
        xpm_data = []
        x_axis, y_axis = [], []
        letter_to_value = {}
        for line in xpm_handle:
            if line.startswith("/* x-axis"):
                x_ax = map(float, line.split()[2:-2]) # We trim the last value
                x_axis = list(x_ax)
            if line.startswith("/* y-axis"):
                y_ax = map(float, line.split()[2:-2]) # We trim the last value
                y_axis = list(y_ax)
            if line.startswith('"') and x_axis and y_axis: # Read data
                xpm_data.insert(0, line.strip().strip(',')[1:-1])
            if line.startswith('"') and len(line.split()) > 4:
                letter = line.split()[0][1:]
                value = float(line.split()[-2][1:-1])
                letter_to_value[letter] = value
        xpm_handle.close()
        txt_values = []
        data = []
        for y_index, data_value in enumerate(xpm_data):
            y_value = y_axis[y_index]
            for x_index, x_value in enumerate(x_axis):
                txt_values.append([x_value, y_value, letter_to_value[data_value[x_index]]])
            for x, y, z in txt_values:
                data.append ([float(x),float(y),float(z)])
        labels = ['RMSD (nm)', 'RG (nm)', 'Gb_E (kj/mol)']
        df = pd.DataFrame.from_records(data, columns=labels)
        df.to_csv('data.csv')                   
        self.bt_plot.setEnabled(True)
        self.bt_getcsv.setEnabled(True)
        self.bt_run.setEnabled(False)
        self.sb_frame.setEnabled(True)
        self.bt_getpdb.setEnabled(True)
        self.bt_prot_view.setEnabled(True)
        self.statusbar.showMessage('Done! Click in Plot or Get CSV File')

    def run_tool(self):
        _res1 = str(self.cb_res1.currentText())
        _res2 = str(self.cb_res2.currentText())
        _res3 = str(self.cb_res3.currentText())
        _res4 = str(self.cb_res4.currentText())
        res1=_res1.split('_')
        res2=_res2.split('_')
        res3=_res3.split('_')
        res4=_res4.split('_')
        trajectory_file=self.TEMP_PATH+'/multipdb.pdb'
        chain=self.cb_chain.currentText()
        final=self.sb_final.value()
        first=self.sb_initial.value()
        self.statusbar.showMessage('Running '+ self.cb_tool.currentText() + ' tool please wait...')

        if self.cb_tool.currentText() == "Pincer angle":
            values = [res1[1],res2[1],res3[1]]
            if len(values) == len(set(values)):
                res_angle=str(res1[1])+','+str(res2[1])+','+str(res3[1])
                dataAll = [] 
                dataArea = []
                dataAngle = []
                dataDihedral = []
                dataRMSD = []
                dataRG = []
                areaLabels = 'Frame\tDist_AB\tDist_AC\tDist_BC\tArea\n'
                angleLabels = 'Frame\tAngle\n'
                dihedralLabels = 'Frame\tDihedral\n'
                rmsLabels = 'Frame\tRMSD\n'
                rgLabels = 'Frame\tRG\n'
                allLabels = 'Frame\tDist_AB\tDist_AC\tDist_BC\tArea\tAngle\tDihedral\tRMSD\tRG\n'
                self.progressBar.setMaximum(final - 1)
                count = 0
                angleRes = res_angle.split(',')
                for frame in range(first ,final):
                        
                    model = parser.get_structure(self.TEMP_PATH+"/complex_" + str(frame) + ".pdb", self.TEMP_PATH+"/complex_" + str(frame) + ".pdb")
                        
                    # Updating progress bar2
                    count += 1
                    self.progressBar.setValue(count)

                    # Calculate pincer angle
                        
                    atom1 = model[0][chain][int(angleRes[0])]['CA']
                    atom2 = model[0][chain][int(angleRes[1])]['CA']
                    atom3 = model[0][chain][int(angleRes[2])]['CA']
                    vector1 = atom1.get_vector()
                    vector2 = atom2.get_vector()
                    vector3 = atom3.get_vector()
                    angle = calc_angle(vector1, vector2, vector3)
                    angleLabels += "%i\t%.2f\n" %(frame,math.degrees(angle))

                dataAngle.append(angleLabels)
                Angleoutput = open(self.TABLE_PATH, "w")
                Angleoutput.writelines(dataAngle)   
                Angleoutput.close()
                self.bt_plot.setEnabled(True)
                self.bt_getcsv.setEnabled(True)
                self.bt_run.setEnabled(False)
                self.sb_frame.setEnabled(True)
                self.bt_getpdb.setEnabled(True)
                self.bt_prot_view.setEnabled(True)
                self.statusbar.showMessage('Done! Click in Plot or Get CSV File')        
                 
            else:
                showdialog('Notice', 'Selected Residues must be differents.')

        elif self.cb_tool.currentText() == "Dihedral angle":
            values = [res1[1],res2[1],res3[1],res4[1]]
            if len(values) == len(set(values)):
                res_dihedral=str(res1[1])+','+str(res2[1])+','+str(res3[1])+','+str(res4[1])
                dataAll = [] 
                dataArea = []
                dataAngle = []
                dataDihedral = []
                dataRMSD = []
                dataRG = []
                areaLabels = 'Frame\tDist_AB\tDist_AC\tDist_BC\tArea\n'
                angleLabels = 'Frame\tAngle\n'
                dihedralLabels = 'Frame\tDihedral\n'
                rmsLabels = 'Frame\tRMSD\n'
                rgLabels = 'Frame\tRG\n'
                allLabels = 'Frame\tDist_AB\tDist_AC\tDist_BC\tArea\tAngle\tDihedral\tRMSD\tRG\n'
                self.progressBar.setMaximum(final - 1)
                count = 0
                dihedralRes = res_dihedral.split(',')
                for frame in range(first ,final):
                            
                    model = parser.get_structure(self.TEMP_PATH+"/complex_" + str(frame) + ".pdb",  self.TEMP_PATH+"/complex_" + str(frame) + ".pdb")
                            
                    # Updating progress bar2
                    count += 1
                    self.progressBar.setValue(count)
                        
                    atom1 = model[0][chain][int(dihedralRes[0])]['CA']
                    atom2 = model[0][chain][int(dihedralRes[1])]['CA']
                    atom3 = model[0][chain][int(dihedralRes[2])]['CA']
                    atom4 = model[0][chain][int(dihedralRes[3])]['CA']
                    vector1 = atom1.get_vector()
                    vector2 = atom2.get_vector()
                    vector3 = atom3.get_vector()
                    vector4 = atom4.get_vector()
                    dihedral = calc_dihedral(vector1, vector2, vector3, vector4)
                    dihedralLabels += "%i\t%.2f\n" %(frame,math.degrees(dihedral))

                dataDihedral.append(dihedralLabels)
                Dihedraloutput = open(self.TABLE_PATH, "w")
                Dihedraloutput.writelines(dataDihedral) 
                Dihedraloutput.close()
                self.bt_plot.setEnabled(True)
                self.bt_getcsv.setEnabled(True)
                self.bt_run.setEnabled(False)
                self.sb_frame.setEnabled(True)
                self.bt_getpdb.setEnabled(True)
                self.bt_prot_view.setEnabled(True)
                self.statusbar.showMessage('Done! Click in Plot or Get CSV File')                    
            else:
                showdialog('Notice', 'Selected Residues must be differents.')

        elif self.cb_tool.currentText() == "Triangle area":
            values = [res1[1],res2[1],res3[1]]
            if len(values) == len(set(values)):
                res_area=str(res1[1])+','+str(res2[1])+','+str(res3[1])
                dataAll = [] 
                dataArea = []
                dataAngle = []
                dataDihedral = []
                dataRMSD = []
                dataRG = []
                areaLabels = 'Frame\tDist_AB\tDist_AC\tDist_BC\tArea\n'
                angleLabels = 'Frame\tAngle\n'
                dihedralLabels = 'Frame\tDihedral\n'
                rmsLabels = 'Frame\tRMSD\n'
                rgLabels = 'Frame\tRG\n'
                allLabels = 'Frame\tDist_AB\tDist_AC\tDist_BC\tArea\tAngle\tDihedral\tRMSD\tRG\n'
                self.progressBar.setMaximum(final - 1)
                count = 0
                areaRes = res_area.split(',')                
                for frame in range(first ,final):
                        
                        
                    model = parser.get_structure(self.TEMP_PATH+"/complex_" + str(frame) + ".pdb",  self.TEMP_PATH+"/complex_" + str(frame) + ".pdb")
                            
                    count += 1
                    self.progressBar.setValue(count)    
                                                                    
                    atom1 = model[0][chain][int(areaRes[0])]['CA']
                    atom2 = model[0][chain][int(areaRes[1])]['CA']
                    atom3 = model[0][chain][int(areaRes[2])]['CA']
                            
                    coordAB = model[0][chain][int(areaRes[0])]['CA'].coord - model[0][chain][int(areaRes[1])]['CA'].coord
                    coordAC = model[0][chain][int(areaRes[0])]['CA'].coord - model[0][chain][int(areaRes[2])]['CA'].coord
                    coordBC = model[0][chain][int(areaRes[1])]['CA'].coord - model[0][chain][int(areaRes[2])]['CA'].coord
                            
                    distAB = np.sqrt(np.sum(coordAB * coordAB))
                    distAC = np.sqrt(np.sum(coordAC * coordAC))
                    distBC = np.sqrt(np.sum(coordBC * coordBC))
                            
                    sPerimeter = (distAB + distAC + distBC) / 2
                            
                    area = (sPerimeter*(sPerimeter-distAB)*(sPerimeter-distAC)*(sPerimeter-distBC)) ** 0.5
                    areaLabels += "%i\t%.2f\t%.2f\t%.2f\t%.2f\n" %(frame, distAB, distAC, distBC, area)

                dataArea.append(areaLabels)
                Triangleoutput = open(self.TABLE_PATH, "w")
                Triangleoutput.writelines(dataArea) 
                Triangleoutput.close()
                self.bt_plot.setEnabled(True)
                self.bt_getcsv.setEnabled(True)
                self.bt_run.setEnabled(False)
                self.sb_frame.setEnabled(True)
                self.bt_getpdb.setEnabled(True)
                self.bt_prot_view.setEnabled(True)
                self.statusbar.showMessage('Done! Click in Plot or Get CSV File')
            else:
                showdialog('Notice', 'Selected Residues must be differents.')

        elif self.cb_tool.currentText() == "PDF":
	            dataAll = [] 
	            dataArea = []
	            dataAngle = []
	            dataDihedral = []
	            dataRMSD = []
	            dataRG = []
	            dataFEL = []
	            FELlabels = ''
	            rmsLabels = ''
	            rgLabels = ''
	            Frame = np.array([])
	            k = 0
	            self.statusbar.showMessage('Running PDF tool (RMSD) please wait...')
	            refStruct = parser.get_structure(self.TABLE_PATH+"/complex_1.pdb",  self.TEMP_PATH+"/complex_1.pdb")
	            refStruct = refStruct[0]
	            refModelChain = refStruct[chain]
	            refCaAtoms = []
	            for refRes in refModelChain:
	                resnum = refRes.get_id()[1]
	                refCaAtoms.append(refRes['CA'])
	            # Setting the progress bar2
	            self.progressBar.setMaximum(final - 1)
	            count = 0
	                            
	            for frame in range(first ,final):
	                            
	                model = parser.get_structure(self.TEMP_PATH+"/complex_" + str(frame) + ".pdb",  self.TEMP_PATH+"/complex_" + str(frame) + ".pdb")
	                            
	                # Updating progress bar2
	                count += 1
	                self.progressBar.setValue(count)     
	                                                                
	                modelStruct = model[0]
	                ModelChain = modelStruct[chain]
	                modelCaAtoms = []
	                for modelRes in ModelChain:
	                    resnum = modelRes.get_id()[1]
	                    modelCaAtoms.append(modelRes['CA'])
	                sup = Superimposer()
	                sup.set_atoms(refCaAtoms, modelCaAtoms)
	                rmsd = sup.rms
	                dataRMSD.append(rmsd)
	            self.progressBar.setProperty("value", 0)
	            refStruct = parser.get_structure(self.TABLE_PATH+"/complex_1.pdb",  self.TEMP_PATH+"/complex_1.pdb")
	            refStruct = refStruct[0]
	            refModelChain = refStruct[chain]
	            refCaAtoms = []
	            for refRes in refModelChain:
	                resnum = refRes.get_id()[1]
	                refCaAtoms.append(refRes['CA'])
	                        
	            # Setting the progress bar2
	            self.progressBar.setMaximum(final - 1)
	            count = 0
	            self.statusbar.showMessage('Running PDF tool (RG) please wait...')                        
	            for frame in range(first ,final):
	                model = parser.get_structure(self.TEMP_PATH+"/complex_" + str(frame) + ".pdb",  self.TEMP_PATH+"/complex_" + str(frame) + ".pdb")
	                count += 1
	                self.progressBar.setValue(count)
	                m = model[0]                
	                allCA = []
	                for chain in m:
	                    for residue in chain:
	                        for atom in residue:
	                            if atom.get_id() == 'CA':
	                                caCoord = atom.get_coord()
	                                allCA.append(caCoord)

	                CoM = sum(allCA)/(len(allCA))
	                allCA2 = []
	                for chain in m:
	                    for residue in chain:
	                        for atom in residue:
	                            if atom.get_id() == 'CA':
	                                caCoord2 = atom.get_coord() - CoM
	                                quadCoord = (caCoord2)**2 * 12.04
	                                allCA2.append(quadCoord)
	                rg = math.sqrt((np.sum(allCA2))/((len(allCA2))*12.04))
	                dataRG.append(rg)
	                k=k+1
	                Frame = np.append(Frame, np.array([k]), axis=0)
	            
	            os.chdir(self.TEMP_PATH)
	            g_data =  pd.DataFrame()
	            g_data['Time (ps)'] = Frame
	            g_data['RMSD (nm)'] = dataRMSD
	            g_data['RG (nm)'] = dataRG
	            g_data.to_csv('data.csv')
	            self.bt_plot.setEnabled(True)
	            self.bt_getcsv.setEnabled(True)
	            self.bt_run.setEnabled(False)
	            self.sb_frame.setEnabled(True)
	            self.bt_getpdb.setEnabled(True)
	            self.bt_prot_view.setEnabled(True)
	            self.statusbar.showMessage('Done! Click in Plot or Get CSV File')

        elif self.cb_tool.currentText() == "RMSD":

                dataAll = [] 
                dataArea = []
                dataAngle = []
                dataDihedral = []
                dataRMSD = []
                dataRG = []
                areaLabels = 'Frame\tDist_AB\tDist_AC\tDist_BC\tArea\n'
                angleLabels = 'Frame\tAngle\n'
                dihedralLabels = 'Frame\tDihedral\n'
                rmsLabels = 'Frame\tRMSD\n'
                rgLabels = 'Frame\tRG\n'
                allLabels = 'Frame\tDist_AB\tDist_AC\tDist_BC\tArea\tAngle\tDihedral\tRMSD\tRG\n'
                
                refStruct = parser.get_structure(self.TABLE_PATH+"/complex_1.pdb",  self.TEMP_PATH+"/complex_1.pdb")
                refStruct = refStruct[0]
                refModelChain = refStruct[chain]
                refCaAtoms = []
                for refRes in refModelChain:
                    resnum = refRes.get_id()[1]
                    refCaAtoms.append(refRes['CA'])
                # Setting the progress bar2
                self.progressBar.setMaximum(final - 1)
                count = 0
                    
                for frame in range(first ,final):
                        
                    model = parser.get_structure(self.TEMP_PATH+"/complex_" + str(frame) + ".pdb",  self.TEMP_PATH+"/complex_" + str(frame) + ".pdb")
                                
                    # Updating progress bar2
                    count += 1
                    self.progressBar.setValue(count) 
                                                    
                    modelStruct = model[0]
                    ModelChain = modelStruct[chain]
                    modelCaAtoms = []
                    for modelRes in ModelChain:
                        resnum = modelRes.get_id()[1]
                        modelCaAtoms.append(modelRes['CA'])
                    sup = Superimposer()
                    sup.set_atoms(refCaAtoms, modelCaAtoms)
                    rmsd = sup.rms
                    rmsLabels += "%i\t%.2f\n" %(frame,rmsd)
                
                dataRMSD.append(rmsLabels)
                RMSDoutput = open(self.TABLE_PATH, "w")
                RMSDoutput.writelines(dataRMSD) 
                RMSDoutput.close()
                self.bt_plot.setEnabled(True)
                self.bt_getcsv.setEnabled(True)
                self.bt_run.setEnabled(False)
                self.sb_frame.setEnabled(True)
                self.bt_getpdb.setEnabled(True)
                self.bt_prot_view.setEnabled(True)
                self.statusbar.showMessage('Done! Click in Plot or Get CSV File')
                         
        elif self.cb_tool.currentText() == "RG":
            
                dataAll = [] 
                dataArea = []
                dataAngle = []
                dataDihedral = []
                dataRMSD = []
                dataRG = []
                areaLabels = 'Frame\tDist_AB\tDist_AC\tDist_BC\tArea\n'
                angleLabels = 'Frame\tAngle\n'
                dihedralLabels = 'Frame\tDihedral\n'
                rmsLabels = 'Frame\tRMSD\n'
                rgLabels = 'Frame\tRG\n'
                allLabels = 'Frame\tDist_AB\tDist_AC\tDist_BC\tArea\tAngle\tDihedral\tRMSD\tRG\n'
                
                refStruct = parser.get_structure(self.TABLE_PATH+"/complex_1.pdb",  self.TEMP_PATH+"/complex_1.pdb")
                refStruct = refStruct[0]
                refModelChain = refStruct[chain]
                refCaAtoms = []
                for refRes in refModelChain:
                    resnum = refRes.get_id()[1]
                    refCaAtoms.append(refRes['CA'])
                
                # Setting the progress bar2
                self.progressBar.setMaximum(final - 1)
                count = 0
                        
                for frame in range(first ,final):
                    model = parser.get_structure(self.TEMP_PATH+"/complex_" + str(frame) + ".pdb",  self.TEMP_PATH+"/complex_" + str(frame) + ".pdb")
                    # Updating progress bar2
                    count += 1
                    self.progressBar.setValue(count) 
                    m = model[0]                
                    allCA = []
                    for chain in m:
                        for residue in chain:
                            for atom in residue:
                                if atom.get_id() == 'CA':
                                    caCoord = atom.get_coord()
                                    allCA.append(caCoord)

                    CoM = sum(allCA)/(len(allCA))
                    allCA2 = []
                    for chain in m:
                        for residue in chain:
                            for atom in residue:
                                if atom.get_id() == 'CA':
                                    caCoord2 = atom.get_coord() - CoM
                                    quadCoord = (caCoord2)**2 * 12.04
                                    allCA2.append(quadCoord)

                    rg = math.sqrt((np.sum(allCA2))/((len(allCA2))*12.04))
                    rgLabels += "%i\t%.2f\n" %(frame,rg)
                
                dataRG.append(rgLabels)
                RGoutput = open(self.TABLE_PATH, "w")
                RGoutput.writelines(dataRG) 
                RGoutput.close()
                self.bt_plot.setEnabled(True)
                self.bt_getcsv.setEnabled(True)
                self.bt_run.setEnabled(False)
                self.sb_frame.setEnabled(True)
                self.bt_getpdb.setEnabled(True)
                self.bt_prot_view.setEnabled(True)
                self.statusbar.showMessage('Done! Click in Plot or Get CSV File')

        elif self.cb_tool.currentText() == "FEL":
            
            if gromacs_flag('mdrun') or gromacs_flag('gmx'):
                dataAll = [] 
                dataArea = []
                dataAngle = []
                dataDihedral = []
                dataRMSD = []
                dataRG = []
                dataFEL = []
                FELlabels = ''
                rmsLabels = ''
                rgLabels = ''
                Frame = np.array([])
                k = 0
                self.statusbar.showMessage('Running FEL tool (RMSD) please wait...')
                refStruct = parser.get_structure(self.TABLE_PATH+"/complex_1.pdb",  self.TEMP_PATH+"/complex_1.pdb")
                refStruct = refStruct[0]
                refModelChain = refStruct[chain]
                refCaAtoms = []
                for refRes in refModelChain:
                    resnum = refRes.get_id()[1]
                    refCaAtoms.append(refRes['CA'])
                # Setting the progress bar2
                self.progressBar.setMaximum(final - 1)
                count = 0
                                
                for frame in range(first ,final):
                                
                    model = parser.get_structure(self.TEMP_PATH+"/complex_" + str(frame) + ".pdb",  self.TEMP_PATH+"/complex_" + str(frame) + ".pdb")
                                
                    # Updating progress bar2
                    count += 1
                    self.progressBar.setValue(count)     
                                                                    
                    modelStruct = model[0]
                    ModelChain = modelStruct[chain]
                    modelCaAtoms = []
                    for modelRes in ModelChain:
                        resnum = modelRes.get_id()[1]
                        modelCaAtoms.append(modelRes['CA'])
                    sup = Superimposer()
                    sup.set_atoms(refCaAtoms, modelCaAtoms)
                    rmsd = sup.rms
                    dataRMSD.append(rmsd)
                self.progressBar.setProperty("value", 0)
                refStruct = parser.get_structure(self.TABLE_PATH+"/complex_1.pdb",  self.TEMP_PATH+"/complex_1.pdb")
                refStruct = refStruct[0]
                refModelChain = refStruct[chain]
                refCaAtoms = []
                for refRes in refModelChain:
                    resnum = refRes.get_id()[1]
                    refCaAtoms.append(refRes['CA'])
                            
                # Setting the progress bar2
                self.progressBar.setMaximum(final - 1)
                count = 0
                self.statusbar.showMessage('Running FEL tool (RG) please wait...')                        
                for frame in range(first ,final):
                    model = parser.get_structure(self.TEMP_PATH+"/complex_" + str(frame) + ".pdb",  self.TEMP_PATH+"/complex_" + str(frame) + ".pdb")
                    count += 1
                    self.progressBar.setValue(count)
                    m = model[0]                
                    allCA = []
                    for chain in m:
                        for residue in chain:
                            for atom in residue:
                                if atom.get_id() == 'CA':
                                    caCoord = atom.get_coord()
                                    allCA.append(caCoord)

                    CoM = sum(allCA)/(len(allCA))
                    allCA2 = []
                    for chain in m:
                        for residue in chain:
                            for atom in residue:
                                if atom.get_id() == 'CA':
                                    caCoord2 = atom.get_coord() - CoM
                                    quadCoord = (caCoord2)**2 * 12.04
                                    allCA2.append(quadCoord)
                    rg = math.sqrt((np.sum(allCA2))/((len(allCA2))*12.04))
                    dataRG.append(rg)
                    k=k+1
                    Frame = np.append(Frame, np.array([k]), axis=0)
                
                os.chdir(self.TEMP_PATH)
                g_data =  pd.DataFrame()
                g_data['a'] = Frame
                g_data['b'] = dataRMSD
                g_data['c'] = dataRG
                g_data.to_csv('g_sham2.xvg', sep='\t', index=False,  header=0)
                with open('g_sham2.xvg', 'r') as fin:
                    data = fin.read().splitlines(True)
                with open('g_sham2.xvg', 'w') as fout:
                    fout.writelines(data[1:])
                os.chdir(self.TEMP_PATH)
                self.setupProcess()                        
                   
            else:
                showdialog('Notice', 'GROMACS program must be intalled') 
              
    def plottingData(self):
        if self.cb_tool.currentText() == "Pincer angle":
            option='Angle'
            data=self.TABLE_PATH
            df = pd.read_csv(data, delimiter= '\t', header=0, sep='\t')
        elif self.cb_tool.currentText() == "Dihedral angle":
            option='Dihedral'
            data=self.TABLE_PATH
            df = pd.read_csv(data, delimiter= '\t', header=0, sep='\t')
        elif self.cb_tool.currentText() == "Triangle area":
            option='Area'
            data=self.TABLE_PATH
            df = pd.read_csv(data, delimiter= '\t', header=0, sep='\t')
        elif self.cb_tool.currentText() == "PDF":
            option='PDF'
            df = pd.read_csv(self.TEMP_PATH+'/data.csv')
        elif self.cb_tool.currentText() == "RMSD":
            option='RMSD'
            data=self.TABLE_PATH
            df = pd.read_csv(data, delimiter= '\t', header=0, sep='\t')
        elif self.cb_tool.currentText() == "RG":
            option = 'RG'
            data=self.TABLE_PATH
            df = pd.read_csv(data, delimiter= '\t', header=0, sep='\t')
        elif self.cb_tool.currentText() == "FEL":
            option='FEL'
            data = self.TEMP_PATH+'/data.csv'
            
        if option == 'PDF':

            fig, (ax1) = plt.subplots(nrows=1)            
            # Setting data
            x = df['RMSD (nm)']
            y = df['RG (nm)']

            # Calculate the point density
            xy = np.vstack([x,y])
            z = gaussian_kde(xy)(xy)

            # Sort the points by density, so that the densest points are plotted last
            idx = z.argsort()
            x, y, z = x[idx], y[idx], z[idx]

            # Setting plot type 
            pdf = ax1.scatter(x, y, c = z, s = 50, edgecolor = '', cmap=plt.cm.jet)

            # Plot title
            ax1.set_title('RMSD by RG')

            # Hide right and top spines
            ax1.spines['right'].set_visible(False)
            ax1.spines['top'].set_visible(False)
            ax1.yaxis.set_ticks_position('left')
            ax1.xaxis.set_ticks_position('bottom')

            # Set x and y limits
            xmin = df['RMSD (nm)'].min() - 1
            xmax = df['RMSD (nm)'].max() + 1
            ymin = df['RG (nm)'].min() - 1
            ymax = df['RG (nm)'].max() + 1        
            plt.xlim(xmin, xmax)
            plt.ylim(ymin, ymax)

            # Set x and y labels
            plt.xlabel('RMSD (nm)')
            plt.ylabel('RG (nm)')

            # Adding the color bar 
            colbar = plt.colorbar(pdf)
            colbar.set_label('Probability Density Function')     
            plt.show()

        elif option != 'PDF' and option != 'FEL':

            fig, (ax1) = plt.subplots(nrows=1)
            ax1.plot(df['Frame'], df[option])
            ax1.set_title(option + ' by Time')
            ax1.spines['right'].set_visible(False)
            ax1.spines['top'].set_visible(False)
            ax1.yaxis.set_ticks_position('left')
            ax1.xaxis.set_ticks_position('bottom')
            plt.xlabel('Frame (10 ps)')
            xmin1 = df['Frame'].min() - 1
            xmax1 = df['Frame'].max() + 1
            plt.xlim(xmin1, xmax1)
            plt.ylabel(option)        
            plt.show()
        
        elif option == 'FEL':
        	if self.cb_selplot.currentText() == "3D":
	            df = pd.read_csv(data)
	            fig = plt.figure(figsize=(15,10))
	            fig.suptitle('Free Energy Landscape', fontsize=20)
	            ax = fig.gca(projection='3d')
	            ax.set_xlabel('RMSD (nm)', fontsize=15)
	            ax.set_ylabel('RG (nm)', fontsize=15)
	            ax.set_zlabel('Gibbs Free Energy (kj/mol)', fontsize=15)
	            ax = fig.gca(projection='3d')
	            ax.plot_trisurf(df['RMSD (nm)'], df['RG (nm)'], df['Gb_E (kj/mol)'], cmap=plt.cm.jet, linewidth=0, antialiased=False)
	                
	            # to Add a color bar which maps values to colors.
	            surf=ax.plot_trisurf(df['RMSD (nm)'], df['RG (nm)'], df['Gb_E (kj/mol)'], cmap=plt.cm.jet, linewidth=0, antialiased=False)
	            colbar = fig.colorbar( surf, shrink=0.5, aspect=5)
	            colbar.set_label('Gibbs Free Energy (kj/mol)')
	            ax.tricontourf(df['RMSD (nm)'], df['RG (nm)'], df['Gb_E (kj/mol)'], zdir='z', offset=-1, cmap=plt.cm.jet)
	                
	            # Rotate it
	            ax.view_init(30, 15)
	            plt.show()
	        else:
	        	df = pd.read_csv(data)
	        	z = df['Gb_E (kj/mol)']
	        	X = df['RMSD (nm)']
	        	Y = df['RG (nm)']
	        	fig, ax = plt.subplots()
	        	fig.suptitle('Free Energy Landscape', fontsize=20)
	        	trico = ax.tricontourf(df['RMSD (nm)'], df['RG (nm)'], df['Gb_E (kj/mol)'], zdir='z', offset=-1, cmap=plt.cm.jet)
	        	ax.set_xlabel('RMSD (nm)', fontsize=15)
	        	ax.set_ylabel('RG (nm)', fontsize=15)
	        	colbar = fig.colorbar(trico, shrink=0.5, aspect=5)
	        	colbar.set_label('Gibbs Free Energy (kj/mol)')
	        	plt.show()

    def clean_temp_files(self):
    	try:
    		shutil.rmtree(self.TEMP_PATH)
    	except:
    		pass



    def new(self):
        
        showdialog('Notice', 'Please wait .. Deleting the temporary folder may take a few minutes.')
        shutil.rmtree(self.TEMP_PATH)
        self.TEMP_PATH = tempfile.mkdtemp()
        self.pdb_line.clear()
        self.cb_res1.clear()
        self.cb_res2.clear()
        self.cb_res3.clear()
        self.cb_res4.clear()
        self.cb_chain.clear()
        self.bt_pdb.setEnabled(True)
        self.bt_getcsv.setEnabled(False)
        self.bt_plot.setEnabled(False)
        self.sb_final.setValue(0)
        self.sb_initial.setValue(0)
        self.statusbar.showMessage('Ready...')



    def save_csv(self):
        options = QtWidgets.QFileDialog.Options()
        options |= QtWidgets.QFileDialog.DontUseNativeDialog
        fileName, _ = QtWidgets.QFileDialog.getSaveFileName(None,"Save CSV file",""," Save CSV Files (*.csv)", options=options)
        if fileName:
            if self.cb_tool.currentText() != "FEL" and self.cb_tool.currentText() != "PDF":
                data=self.TABLE_PATH
                df = pd.read_csv(data, delimiter= '\t', sep='\t')
                if fileName.endswith('.csv'):
                	df.to_csv(fileName)
                else:
                	df.to_csv(fileName+'.csv')
            elif self.cb_tool.currentText() == "PDF":
            	df = pd.read_csv(self.TEMP_PATH+'/data.csv')

            	if fileName.endswith('.csv'):
            		df.to_csv(fileName)
            	else:
                	df.to_csv(fileName+'.csv')
            else:
                if os.path.exists(self.TEMP_PATH+'/data.csv'):
                	if fileName.endswith('.csv'):
                		shutil.copy(self.TEMP_PATH+'/data.csv', fileName)
                	else:
                		shutil.copy(self.TEMP_PATH+'/data.csv', fileName+'.csv')
        else:
            print('Error')

    def save_pdb(self):
        options = QtWidgets.QFileDialog.Options()
        options |= QtWidgets.QFileDialog.DontUseNativeDialog
        fileName, _ = QtWidgets.QFileDialog.getSaveFileName(None,"Save PDB file",""," Save PDB Files (*.pdb)", options=options)
        frame_time = self.sb_frame.value()
        if fileName:
        	if fileName.endswith('.pdb'):
        		shutil.copy(self.TEMP_PATH+"/complex_" + str(frame_time) + ".pdb", fileName)
        	else:
        		shutil.copy(self.TEMP_PATH+"/complex_" + str(frame_time) + ".pdb", fileName+'.pdb')
        else:
            print('Error')        	
    
    def closeEvent(self):
        print('Bye')
        self.clean_temp_files
        sys.exit(0)

    def proteinView(self):
    	_res1 = str(self.cb_res1.currentText())
    	_res2 = str(self.cb_res2.currentText())
    	_res3 = str(self.cb_res3.currentText())
    	_res4 = str(self.cb_res4.currentText())
    	res1=_res1.split('_')
    	res2=_res2.split('_')
    	res3=_res3.split('_')
    	res4=_res4.split('_')
    	frame_time = self.sb_frame.value()
    	prot = parsePDB(self.TEMP_PATH+"/complex_" + str(frame_time) + ".pdb")
    	prot0 =  parsePDB(self.TEMP_PATH+"/complex_1.pdb")
    	if self.cb_tool.currentText() == "Pincer angle" or self.cb_tool.currentText() == "Triangle area":
    		selres = prot.select('resnum {0} {1} {2}'.format(res1[1], res2[1], res3[1]))
    		selres0 = prot0.select('resnum {0} {1} {2}'.format(res1[1], res2[1], res3[1]))
    	elif self.cb_tool.currentText() == "PDF" or self.cb_tool.currentText() == "RMSD" or self.cb_tool.currentText() == "RG" or self.cb_tool.currentText() == "FEL":
    		selres = None
    		selres0 = None
    	elif self.cb_tool.currentText() == "Dihedral angle":
    		selres = prot.select('resnum {0} {1} {2} {3}'.format(res1[1], res2[1], res3[1], res4[1]))
    		selres0 = prot0.select('resnum {0} {1} {2} {3}'.format(res1[1], res2[1], res3[1], res4[1]))

    	showProtein(prot0, prot, selres0, selres)   

def call_main():
    import sys
    app = QtWidgets.QApplication(sys.argv)
    icon = iconFromBase64(ICO)
    app.setWindowIcon(icon)
    app.setStyle('Fusion')
    palette = QPalette()
    palette.setColor(QPalette.Window, QColor(53, 53, 53))
    palette.setColor(QPalette.WindowText, Qt.white)
    palette.setColor(QPalette.Base, QColor(25, 25, 25))
    palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
    palette.setColor(QPalette.ToolTipBase, Qt.white)
    palette.setColor(QPalette.ToolTipText, Qt.white)
    palette.setColor(QPalette.Text, Qt.white)
    palette.setColor(QPalette.Button, QColor(53, 53, 53))
    palette.setColor(QPalette.ButtonText, Qt.white)
    palette.setColor(QPalette.BrightText, Qt.red)
    palette.setColor(QPalette.Link, QColor(42, 130, 218))
    palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
    palette.setColor(QPalette.HighlightedText, Qt.black)
    app.setPalette(palette)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    app.aboutToQuit.connect(ui.closeEvent)
    MainWindow.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
	call_main()