version = "250711"


import os, wx, sys, fileinput, string
import subprocess
import wx.lib.stattext, wx.lib.buttons

import fliprotsub5
import flipsmall

ID_SMALL = 11
ID_PROT = 13

ID_OPEN=102
ID_SAVE=103
ID_EXIT=200




def find_executable(executable, path=None):
    """Try to find 'executable' in the directories listed in 'path' (a
    string listing directories separated by 'os.pathsep'; defaults to
    os.environ['PATH']).  Returns the complete filename or None if not
    found
    """
    if path is None:
        path = os.environ['PATH']
    paths = path.split(os.pathsep)
    extlist = ['']
    if os.name == 'os2':
        (base, ext) = os.path.splitext(executable)
        # executable files on OS/2 can have an arbitrary extension, but
        # .exe is automatically appended if no dot is present in the name
        if not ext:
            executable = executable + ".exe"
    elif sys.platform == 'win32':
        pathext = os.environ['PATHEXT'].lower().split(os.pathsep)
        (base, ext) = os.path.splitext(executable)
        if ext.lower() not in pathext:
            extlist = pathext
    for ext in extlist:
        execname = executable + ext
        if os.path.isfile(execname):
            return execname
        else:
            for p in paths:
                f = os.path.join(p, execname)
                if os.path.isfile(f):
                    return f
    else:
        return None

class EditWindow(wx.Frame):
   def __init__(self,parent,title,insfile):
# based on a frame, so set up the frame
      wx.Frame.__init__(self,parent,wx.ID_ANY, title)

      self.parent = parent
      self.insfile = insfile
      self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)
      self.CreateStatusBar() # A Statusbar in the bottom of the window

      filemenu= wx.Menu()
      filemenu.Append(ID_OPEN, "&Open"," Open a file to edit")
      filemenu.AppendSeparator()
      filemenu.Append(ID_SAVE, "&Save"," Save file")
      filemenu.AppendSeparator()
      filemenu.Append(ID_EXIT,"E&xit"," Terminate the program")

      menuBar = wx.MenuBar()
      menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar
      self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content.

      wx.EVT_MENU(self, ID_EXIT, self.OnExit)
      wx.EVT_MENU(self, ID_OPEN, self.OnOpen)
      wx.EVT_MENU(self, ID_SAVE, self.OnSave)



      self.sizer=wx.BoxSizer(wx.VERTICAL)
      filehandle=open(insfile,'r')
      self.SetTitle("Editing: "+os.path.basename(insfile))
      self.control.SetValue(filehandle.read())
      self.SetFocus()
      filehandle.close()

      self.sizer.Add(self.control,1,wx.EXPAND)

      self.SetSizer(self.sizer)

      self.Bind(wx.EVT_CLOSE, self.OnExit)

      self.SetClientSize((500, 150))

      self.Show(1)

      self.doiexit = wx.MessageDialog( self, " Exit - Save? \n","Quit", wx.YES_NO)

      self.dirname = ''


   def OnExit(self,e):
     igot = self.doiexit.ShowModal() # Shows it
     if igot == wx.ID_YES:
         itcontains = self.control.GetValue()

         filehandle=open(self.insfile,'w')
         filehandle.write(itcontains)
         filehandle.close()

     self.Destroy() # Closes out this simple application
     self.parent.Enable()

   def OnOpen(self,e):
          dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.*", wx.OPEN)
          if dlg.ShowModal() == wx.ID_OK:
            self.filename=dlg.GetFilename()
            self.dirname=dlg.GetDirectory()

            filehandle=open(os.path.join(self.dirname, self.filename),'r')
            self.control.SetValue(filehandle.read())
            filehandle.close()

            self.SetTitle("Editing ... "+self.filename)
          dlg.Destroy()

   def OnSave(self,e):
# Save away the edited text
# Open the file, do an RU sure check for an overwrite!
      dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.*", \
      wx.SAVE | wx.OVERWRITE_PROMPT)
      if dlg.ShowModal() == wx.ID_OK:
# Grab the content to be saved
         itcontains = self.control.GetValue()

# Open the file for write, write, close
         self.filename=dlg.GetFilename()
         self.dirname=dlg.GetDirectory()
         filehandle=open(os.path.join(self.dirname, self.filename),'w')
         filehandle.write(itcontains)
         filehandle.close()
# Get rid of the dialog to keep things tidy
      dlg.Destroy()


class Main(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, 'Charge Flipping Gui',  style=wx.STAY_ON_TOP| wx.DEFAULT_FRAME_STYLE ^(wx.MAXIMIZE_BOX | wx.RESIZE_BORDER)  )

        self.parent  = parent
        self.panel=wx.Panel(self)
        grid = wx.BoxSizer(wx.HORIZONTAL)
        vbox = wx.BoxSizer(wx.VERTICAL)
        bwidth = 110.0*scale
        bheight = 28.0*scale
        self.panel.SetFont(userfont)

        vbox.Add(wx.StaticText(self.panel, -1, 'Small Molecules/Proteins', (10, 100)), 0, wx.TOP | wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL |  wx.ALIGN_CENTER_HORIZONTAL , 10 )

        sizer1 = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, ''), orient=wx.HORIZONTAL)
        self.small = wx.Button(self.panel, ID_SMALL, 'Small Molecules', (10, 160), size=wx.Size(bwidth, bheight) )
        self.small.Bind(wx.EVT_BUTTON , self.HandlePrograms,id=ID_SMALL)
        sizer1.Add(self.small, 0, wx.ALL | wx.LEFT  | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 10 )



        self.prot = wx.Button(self.panel, ID_PROT, 'Proteins', (10, 160), size=wx.Size(bwidth, bheight) )
        self.prot.Bind(wx.EVT_BUTTON , self.HandlePrograms,id=ID_PROT)
        sizer1.Add(self.prot, 0, wx.ALL | wx.LEFT  | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 10 )

        grid.Add(sizer1,0, wx.ALL | wx.LEFT  | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 10 )
        vbox.Add(grid, 0, wx.ALL | wx.LEFT  | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 10 )

        self.returnbutton = wx.Button(self.panel, 7, 'Quit', (10, 160), size=wx.Size(bwidth, bheight))
        vbox.Add(self.returnbutton, 0, wx.ALL | wx.LEFT  | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 10 )

        self.returnbutton.Bind(wx.EVT_BUTTON , self.OnReturn,id=7)
        self.returnbutton.SetDefault()
        self.returnbutton.SetFocus()

        self.panel.SetSizer(vbox)
#        grid.Fit(self.panel)
        self.Bind(wx.EVT_CLOSE, self.OnReturn)
        self.icon = wx.Icon("progmanager.ico", wx.BITMAP_TYPE_ICO)
        self.SetIcon(self.icon)

        w,h = self.panel.GetBestSize()
        self.SetClientSize((w, h))


        self.Centre()
        self.Show()
        if find_executable('superflip') == None:
           print "cannot find superflip"
           dlg = wx.MessageDialog(None, 'The Superflip executable can not be found in the path. Please install', 'Error', wx.OK | wx.ICON_WARNING)
           if (dlg.ShowModal() ==  wx.ID_OK):
              dlg.Destroy()
              sys.exit()


    def HandlePrograms(self, event):

#         print event.GetId()
         evid= event.GetId()
         if event.GetId() == ID_SMALL:
            frame.Hide()
            doedingenframe = Doedingensmall(None,-1,'Small molecules')
         if event.GetId() == ID_PROT:
            frame.Hide()
            doedingenframe = Doedingenprot(None,-1,'Proteins')
    def OnReturn(self, event):
        self.Destroy()  # Close the frame.


class Doedingensmall(wx.Frame):
    def __init__(self,parent,id,title):
        wx.Frame.__init__(self,parent,wx.ID_ANY, title,  style=wx.DEFAULT_FRAME_STYLE ^(wx.MAXIMIZE_BOX  | wx.RESIZE_BORDER) )
        self.parent = parent
        basename = ""


        self.panel = wx.Panel(self)
        self.panel.SetFont(userfont)

#        if os.name != 'nt': self.panel.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL, False,'MS Shell Dlg 2'))
        self.grid = wx.FlexGridSizer(4, 1)



        sizer1 = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, 'Small molecule structures'), orient=wx.VERTICAL)
        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        hbox1a = wx.BoxSizer(wx.HORIZONTAL)
        hbox2 = wx.GridSizer(2,2)
        hbox4 = wx.BoxSizer(wx.HORIZONTAL)
        vbox1 = wx.FlexGridSizer(7, 2)
        vbox2 = wx.FlexGridSizer(7, 3)




        self.label01 = wx.lib.stattext.GenStaticText(self.panel, 102, "Input file:", wx.Point(120, 150))
        hbox1.Add(self.label01, 0,  wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, 5 )
        self.label01.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.inputfile = wx.TextCtrl(self.panel, 502, "",  (180, 150), (scale*150, -1))
        hbox1.Add(self.inputfile, 0,  wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, 5 )
        self.inputfile.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.browse = wx.Button(self.panel, 67, 'Browse', (10, 160), size=wx.Size(scale*75, -1) )
        hbox1.Add(self.browse, 0,  wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, 5 )
        self.editins = wx.Button(self.panel, 68, 'Edit ins', (10, 160), size=wx.Size(scale*75, -1) )
        hbox1.Add(self.editins, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.editins.Disable()


        self.label02l = wx.lib.stattext.GenStaticText(self.panel, 111, "No of trials:", wx.Point(120, 150))
        vbox1.Add(self.label02l, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label02l.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.trials = wx.TextCtrl(self.panel, 511, "1",  (180, 150), (scale*150, -1))
        vbox1.Add(self.trials, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.trials.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.trials.Disable()


        self.label03l = wx.lib.stattext.GenStaticText(self.panel, 112, "k_ed:", wx.Point(120, 150))
        vbox1.Add(self.label03l, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label03l.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.ked = wx.TextCtrl(self.panel, 512, "auto",  (180, 150), (scale*150, -1))
        self.ked.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        vbox1.Add(self.ked, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.ked.Disable()

        self.label04l = wx.lib.stattext.GenStaticText(self.panel, 113, "Weak:", wx.Point(120, 150))
        vbox1.Add(self.label04l, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label04l.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.weak = wx.TextCtrl(self.panel, 513, "0.20",  (180, 150), (scale*150, -1))
        vbox1.Add(self.weak, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.weak.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.weak.Disable()


        self.label05l = wx.lib.stattext.GenStaticText(self.panel, 114, "Maximum cycles:", wx.Point(120, 150))
        vbox1.Add(self.label05l, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label05l.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.maxcycles = wx.TextCtrl(self.panel, 514, "10000",  (180, 150), (scale*150, -1))
        self.maxcycles.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        vbox1.Add(self.maxcycles, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.maxcycles.Disable()


        self.label02r = wx.lib.stattext.GenStaticText(self.panel, 115, "Normalize:", wx.Point(120, 150))
        vbox2.Add(self.label02r, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label02r.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.norm_yes=wx.RadioButton(self.panel, 515, 'yes', (10, -1), style=wx.RB_GROUP)
        self.norm_no=wx.RadioButton(self.panel, 615, 'no', (10, -1))
        self.norm_yes.SetValue(True)
        self.norm_no.Disable()
        self.norm_yes.Disable()
        self.norm_yes.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.norm_no.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        vbox2.Add(self.norm_yes, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )
        vbox2.Add(self.norm_no, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )

        self.label03r = wx.lib.stattext.GenStaticText(self.panel, 116, "Force symmetry:", wx.Point(120, 150))
        vbox2.Add(self.label03r, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label03r.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.forcesymmetry_yes=wx.RadioButton(self.panel, 516, 'yes', (10, -1), style=wx.RB_GROUP)
        self.forcesymmetry_no=wx.RadioButton(self.panel, 616, 'no', (10, -1))
        self.forcesymmetry_no.SetValue(True)
        self.forcesymmetry_no.Disable()
        self.forcesymmetry_yes.Disable()
        self.forcesymmetry_yes.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.forcesymmetry_no.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        vbox2.Add(self.forcesymmetry_yes, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )
        vbox2.Add(self.forcesymmetry_no, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )


        self.label04r = wx.lib.stattext.GenStaticText(self.panel, 117, "Superposition:", wx.Point(120, 150))
        vbox2.Add(self.label04r, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label04r.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.superposition_yes=wx.RadioButton(self.panel, 517, 'yes', (10, -1), style=wx.RB_GROUP)
        self.superposition_no=wx.RadioButton(self.panel, 617, 'no', (10, -1))
        self.superposition_no.SetValue(True)
        self.superposition_no.Disable()
        self.superposition_yes.Disable()
        self.superposition_yes.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.superposition_no.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        vbox2.Add(self.superposition_yes, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )
        vbox2.Add(self.superposition_no, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )

        self.label05r = wx.lib.stattext.GenStaticText(self.panel, 118, "Edmacontinue:", wx.Point(120, 150))
        vbox2.Add(self.label05r, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label05r.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
#        self.edmacontinue_yes=wx.lib.buttons.GenToggleButton(self.panel, 518, 'yes', (10, -1), style=wx.RB_GROUP)
#        self.edmacontinue_no=wx.lib.buttons.GenToggleButton(self.panel, 618, 'no', (10, -1))

        self.edmacontinue_yes=wx.RadioButton(self.panel, 518, 'yes', (10, -1), style=wx.RB_GROUP)
        self.edmacontinue_no=wx.RadioButton(self.panel, 618, 'no', (10, -1))
        self.edmacontinue_no.SetValue(True)
        self.edmacontinue_no.Disable()
        self.edmacontinue_yes.Disable()
        self.edmacontinue_yes.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.edmacontinue_no.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        vbox2.Add(self.edmacontinue_yes, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )
        vbox2.Add(self.edmacontinue_no, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )

        self.label06r = wx.lib.stattext.GenStaticText(self.panel, 119, "Pure P1 mode:", wx.Point(120, 150))
        vbox2.Add(self.label06r, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label06r.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.p1mode_yes=wx.RadioButton(self.panel, 519, 'yes', (10, -1), style=wx.RB_GROUP)
        self.p1mode_no=wx.RadioButton(self.panel, 619, 'no', (10, -1))
        self.p1mode_no.SetValue(True)
        self.p1mode_no.Disable()
        self.p1mode_yes.Disable()
        self.p1mode_yes.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.p1mode_no.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        vbox2.Add(self.p1mode_yes, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )
        vbox2.Add(self.p1mode_no, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )

        self.label07r = wx.lib.stattext.GenStaticText(self.panel, 120, "Clean up:", wx.Point(120, 150))
        vbox2.Add(self.label07r, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label07r.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.cleanup_yes=wx.RadioButton(self.panel, 520, 'yes', (10, -1), style=wx.RB_GROUP)
        self.cleanup_no=wx.RadioButton(self.panel, 620, 'no', (10, -1))
        self.cleanup_yes.SetValue(True)
        self.cleanup_no.Disable()
        self.cleanup_yes.Disable()
        self.cleanup_yes.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.cleanup_no.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        vbox2.Add(self.cleanup_yes, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )
        vbox2.Add(self.cleanup_no, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )

        hbox1a.Add(vbox1, 0,  wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, 5 )
        hbox1a.Add(vbox2, 0,  wx.LEFT | wx.ALIGN_CENTER_VERTICAL, 5 )

#
        sizer1.Add(hbox1,0,  wx.TOP  | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 20)
        sizer1.Add(hbox1a,0,  wx.TOP  | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 20)
        self.grid.Add(sizer1,0, wx.ALL | wx.LEFT  | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 10 )

        self.flipbutton = wx.Button(self.panel, 2, 'Flip', (60, 290))
        hbox4.Add(self.flipbutton, 0,  wx.TOP | wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 15)
        self.flipbutton.Disable()

        self.button6 = wx.Button(self.panel, 9, 'Cancel', (60, 290))
        hbox4.Add(self.button6, 0,  wx.TOP | wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 15)


        self.grid.Add(hbox4,0, wx.ALL | wx.LEFT  | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 10 )

        self.panel.SetSizer(self.grid)



        self.Bind(wx.EVT_BUTTON, self.OnFlip, id=2)
        self.Bind(wx.EVT_BUTTON, self.OnExit, id=6)
        self.Bind(wx.EVT_CLOSE, self.OnExit)
        self.Bind(wx.EVT_BUTTON, self.OnCancel,id=9)
        self.Bind(wx.EVT_BUTTON, self.OnMercury, id=41)
        self.Bind(wx.EVT_BUTTON, self.Browse, id=67)
        self.Bind(wx.EVT_BUTTON, self.Editins, id=68)

        icon = wx.Icon("progmanager.ico", wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)
        w,h = self.panel.GetBestSize()

        self.SetClientSize((w, h))

        self.Show(True)
        self.Centre(True)



        mercury_checked = False
        mercury_present = False
        editor_checked = False
        editor_present = False
#        self.execu = locals()
        if find_executable('EDMA') == None:
           print "cannot find EDMA"
           dlg = wx.MessageDialog(None, 'The EDMA executable can not be found in the path. Please install', 'Error', wx.OK | wx.ICON_WARNING)
           if (dlg.ShowModal() ==  wx.ID_OK):
              dlg.Destroy()
              sys.exit()


    def Hovertext(self,event):

      if event.GetId()  == 102 or event.GetId()  == 502:
          helptxt = wx.ToolTip("Input Shelx type .ins file")
          helptxt.SetDelay(1)
          if event.GetId()  == 102:
             self.label01.SetToolTip(helptxt)
          else:
             self.inputfile.SetToolTip(helptxt)
      if event.GetId()  == 111 or event.GetId()  == 511:
          helptxt = wx.ToolTip("Number of trials")
          helptxt.SetDelay(1)
          if event.GetId()  == 111:
              self.label02l.SetToolTip(helptxt)
          else:
              self.trials.SetToolTip(helptxt)
      if event.GetId()  == 112 or event.GetId()  == 512:
          helptxt = wx.ToolTip("Flipping parameter k_ed (auto = automatic choice)")
          helptxt.SetDelay(1)
          if event.GetId()  == 112:
              self.label03l.SetToolTip(helptxt)
          else:
              self.ked.SetToolTip(helptxt)
      if event.GetId()  == 113 or event.GetId()  == 513:
          helptxt = wx.ToolTip("Fraction reflections considered to be weak")
          helptxt.SetDelay(1)
          if event.GetId()  == 113:
              self.label04l.SetToolTip(helptxt)
          else:
              self.weak.SetToolTip(helptxt)
      if event.GetId()  == 114 or event.GetId()  == 514:
          helptxt = wx.ToolTip("Maximum number of cycles per run")
          helptxt.SetDelay(1)
          if event.GetId()  == 114:
              self.label05l.SetToolTip(helptxt)
          else:
              self.maxcycles.SetToolTip(helptxt)
      if event.GetId()  == 115:
          helptxt = wx.ToolTip("Use local normalizaton of structure factors")
          helptxt.SetDelay(1)
          self.label02r.SetToolTip(helptxt)
      if event.GetId()  == 515:
          helptxt = wx.ToolTip("Use local normalizaton of structure factors")
          helptxt.SetDelay(1)
          self.norm_yes.SetToolTip(helptxt)
      if event.GetId()  == 615:
          helptxt = wx.ToolTip("Use non-normalized structure factors")
          helptxt.SetDelay(1)
          self.norm_no.SetToolTip(helptxt)
      if event.GetId()  == 116:
          helptxt = wx.ToolTip("Use space group symmetry in .ins file")
          helptxt.SetDelay(1)
          self.label03r.SetToolTip(helptxt)
      if event.GetId()  == 516:
          helptxt = wx.ToolTip("Use space group symmetry in .ins file")
          helptxt.SetDelay(1)
          self.forcesymmetry_yes.SetToolTip(helptxt)
      if event.GetId()  == 616:
          helptxt = wx.ToolTip("Auto-determine space group symmetry")
          helptxt.SetDelay(1)
          self.forcesymmetry_no.SetToolTip(helptxt)
      if event.GetId()  == 117:
          helptxt = wx.ToolTip("Use initial minimum superposition map")
          helptxt.SetDelay(1)
          self.label04r.SetToolTip(helptxt)
      if event.GetId()  == 517:
          helptxt = wx.ToolTip("Use initial minimum superposition map")
          helptxt.SetDelay(1)
          self.superposition_yes.SetToolTip(helptxt)
      if event.GetId()  == 617:
          helptxt = wx.ToolTip("Use initial random map")
          helptxt.SetDelay(1)
          self.superposition_no.SetToolTip(helptxt)
      if event.GetId()  == 118:
          helptxt = wx.ToolTip("Analyze density map after non-convergence")
          helptxt.SetDelay(1)
          self.label05r.SetToolTip(helptxt)
      if event.GetId()  == 518:
          helptxt = wx.ToolTip("Analyze density map after non-convergence")
          helptxt.SetDelay(1)
          self.edmacontinue_yes.SetToolTip(helptxt)
      if event.GetId()  == 618:
          helptxt = wx.ToolTip("Do not analyze density map after non-convergence")
          helptxt.SetDelay(1)
          self.edmacontinue_no.SetToolTip(helptxt)
      if event.GetId()  == 119:
          helptxt = wx.ToolTip("Merge reflection according to Laue symmetry")
          helptxt.SetDelay(1)
          self.label06r.SetToolTip(helptxt)
      if event.GetId()  == 519:
          helptxt = wx.ToolTip("Do not merge reflection according to Laue symmetry")
          helptxt.SetDelay(1)
          self.p1mode_yes.SetToolTip(helptxt)
      if event.GetId()  == 619:
          helptxt = wx.ToolTip("Merge reflection according to Laue symmetry")
          helptxt.SetDelay(1)
          self.p1mode_no.SetToolTip(helptxt)
      if event.GetId()  == 120:
          helptxt = wx.ToolTip("Delete intermediate files after flip run")
          helptxt.SetDelay(1)
          self.label07r.SetToolTip(helptxt)
      if event.GetId()  == 520:
          helptxt = wx.ToolTip("Delete intermediate files after flip run")
          helptxt.SetDelay(1)
          self.cleanup_yes.SetToolTip(helptxt)
      if event.GetId()  == 620:
          helptxt = wx.ToolTip("Do not delete intermediate files after flip run")
          helptxt.SetDelay(1)
          self.cleanup_no.SetToolTip(helptxt)

      event.Skip()


    def Editins(self,event):
        view = EditWindow(self, "Edit .ins file",os.path.join(self.dirname, self.filename))
        self.Disable()


    def OnFlip(self,event):
        self.change_to_structure_directory()
        args = ["guirun",self.filename]
        if self.superposition_yes.GetValue():
           args.append("superposition=yes")
        else:
           args.append("superposition=no")
        if self.norm_no.GetValue():
           args.append("normalize=no")
        else:
           args.append("normalize=yes")
        if self.cleanup_no.GetValue():
           args.append("cleanup=no")
        else:
           args.append("cleanup=yes")
        if self.edmacontinue_yes.GetValue():
           args.append("edmacontinue=yes")
        else:
           args.append("edmacontinue=no")
        if self.p1mode_yes.GetValue():
           args.append("p1=yes")
        else:
           args.append("p1=no")
        if self.forcesymmetry_yes.GetValue():
           args.append("forcesymmetry=yes")
        else:
           args.append("forcesymmetry=no")
        try:
           args.append("ked=%s" % float(self.ked.GetValue()) )
        except:
           args.append("ked=auto")
        try:
           args.append("weak=%s" % float(self.weak.GetValue()) )
        except:
           args.append("weak=0.2" % float(self.weak.GetValue()) )
        try:
           args.append("maxcycl=%s" % int(self.maxcycles.GetValue()) )
        except:
           args.append("maxcycl=10000" % int(self.maxcycles.GetValue()) )
        try:
           args.append("trial=%s" % int(self.trials.GetValue()) )
        except:
           args.append("trial=1" % int(self.trials.GetValue()) )
        if os.path.isfile(self.filename.replace('.ins','.res')): os.remove(self.filename.replace('.ins','.res'))
        self.Hide()
        flipsmall.flip(args)
        self.Show()
        if os.path.isfile(self.filename.replace('.ins','.res')):
           dlg = wx.MessageDialog(self, 'Visualize solved structure in Mercury?', 'Question', wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
           if (dlg.ShowModal() ==  wx.ID_YES):
              dlg.Destroy()
              self.OnMercury()
        os.chdir(self.current_directory)

        return


    def Browse(self,event):
        global lastdirectory
#        lastdirectory = "y:/exterieur/ecryst/ecryst119"
        dlg = wx.FileDialog(None, "Choose the name of the .ins file.",lastdirectory , wildcard = "Shelx type .ins file (*.ins)|*.ins|" "All files (*.*)|*.*", style=wx.STAY_ON_TOP)
        choice =  dlg.ShowModal()
        dlg.Destroy()
        if choice == wx.ID_OK:
            self.filename=dlg.GetFilename()
            self.inputfile.SetValue(self.filename)
            self.dirname=dlg.GetDirectory()

            lastdirectory = self.dirname

            if os.path.splitext(self.filename)[1] != '.ins':
               dlg = wx.MessageDialog(None, 'The selected file has not the extension .ins. Try again', 'Error', wx.OK | wx.ICON_WARNING)
               choice =  dlg.ShowModal()
               dlg.Destroy()
               return
            self.maxcycles.Enable()
            self.ked.Enable()
            self.weak.Enable()
            self.trials.Enable()
            self.norm_no.Enable()
            self.norm_yes.Enable()
            self.superposition_no.Enable()
            self.superposition_yes.Enable()
            self.edmacontinue_no.Enable()
            self.edmacontinue_yes.Enable()
            self.p1mode_no.Enable()
            self.p1mode_yes.Enable()
            self.cleanup_no.Enable()
            self.cleanup_yes.Enable()
            self.forcesymmetry_no.Enable()
            self.forcesymmetry_yes.Enable()
            self.editins.Enable()
            self.flipbutton.Enable()


    def	change_to_structure_directory(self):
        self.current_directory = os.getcwd()
        print "change to: %s" % self.dirname
        os.chdir(self.dirname)
        return




    def OnMercury(self):
        mercuryname = 'mercury'
        if os.name != 'nt': self.checkexec('mercury',mercuryname)
        try:
            resname =  self.filename.replace('.ins','.res')
            subprocess.Popen(resname,shell=True)
        except:
             print 'failure on opening mercury'
             dlg = wx.MessageDialog(self, 'Mercury is not found in the path. Check your system.', 'Error', wx.OK | wx.ICON_WARNING)
             dlg.ShowModal()
             dlg.Destroy()
             return
        return

    def OnCancel(self, event):
        frame.Show()
        self.Destroy()  # Close the frame.



    def OnExit(self, event):
        frame.Show()

        self.Destroy()  # Close the frame.


class Doedingenprot(wx.Frame):
    def __init__(self,parent,id,title):
        wx.Frame.__init__(self,parent,wx.ID_ANY, title,  style=wx.DEFAULT_FRAME_STYLE ^(wx.MAXIMIZE_BOX  | wx.RESIZE_BORDER) )
        self.parent = parent
        basename = ""


        self.panel = wx.Panel(self)
        self.panel.SetFont(userfont)

#        if os.name != 'nt': self.panel.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL, False,'MS Shell Dlg 2'))
        self.grid = wx.FlexGridSizer(4, 1)



        sizer1 = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, 'Protein structures'), orient=wx.VERTICAL)
        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        hbox1a = wx.BoxSizer(wx.HORIZONTAL)
        hbox2a = wx.BoxSizer(wx.HORIZONTAL)

        hbox2 = wx.GridSizer(2,2)
        hbox4 = wx.BoxSizer(wx.HORIZONTAL)
        vbox1 = wx.FlexGridSizer(7, 2)
        vbox2 = wx.FlexGridSizer(7, 2)
        hbox5 = wx.BoxSizer(wx.HORIZONTAL)
        vbox5 = wx.BoxSizer(wx.VERTICAL)



        self.label01 = wx.lib.stattext.GenStaticText(self.panel, 102, "Input file:", wx.Point(120, 150))
        hbox1.Add(self.label01, 0,  wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, 5 )
        self.label01.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.inputfile = wx.TextCtrl(self.panel, 502, "",  (180, 150), (scale*150, -1))
        self.inputfile.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        hbox1.Add(self.inputfile, 0,  wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, 5 )
        self.browse = wx.Button(self.panel, 67, 'Browse', (10, 160), size=wx.Size(scale*75, -1) )
        hbox1.Add(self.browse, 0,  wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, 5 )

        self.prot=wx.RadioButton(self.panel, -1, 'Ab-initio high resolution', (10, -1), style=wx.RB_GROUP)
        self.sub=wx.RadioButton(self.panel, -1, 'Substructure medium resolution', (10, -1))
        self.prot.SetValue(True)
        self.prot.Disable()
        self.sub.Disable()
        hbox2a.Add(self.prot, 0,  wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, 5 )
        hbox2a.Add(self.sub, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )


        self.label02l = wx.lib.stattext.GenStaticText(self.panel, 111, "Generic name", wx.Point(120, 150))
        vbox1.Add(self.label02l, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label02l.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.name = wx.TextCtrl(self.panel, 511, "fliprot",  (180, 150), (scale*150, -1))
        self.name.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        vbox1.Add(self.name, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.name.Disable()

        self.label03l = wx.lib.stattext.GenStaticText(self.panel, 112, "k_ed:", wx.Point(120, 150))
        vbox1.Add(self.label03l, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label03l.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.ked = wx.TextCtrl(self.panel, 512, "1.3",  (180, 150), (scale*150, -1))
        vbox1.Add(self.ked, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.ked.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.ked.Disable()

        self.label04l = wx.lib.stattext.GenStaticText(self.panel, 113, "Weak:", wx.Point(120, 150))
        vbox1.Add(self.label04l, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label04l.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.weak = wx.TextCtrl(self.panel, 513, "",  (180, 150), (scale*150, -1))
        self.weak.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        vbox1.Add(self.weak, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.weak.Disable()

        self.label05l = wx.lib.stattext.GenStaticText(self.panel, 114, "Number of trials:", wx.Point(120, 150))
        vbox1.Add(self.label05l, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label05l.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.trials = wx.TextCtrl(self.panel, 514, "1",  (180, 150), (scale*150, -1))
        self.trials.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        vbox1.Add(self.trials, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.trials.Disable()


        self.label06l = wx.lib.stattext.GenStaticText(self.panel, 115, "Maximum cycles:", wx.Point(120, 150))
        vbox1.Add(self.label06l, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label06l.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.maxcycles = wx.TextCtrl(self.panel, 515, "10000",  (180, 150), (scale*150, -1))
        self.maxcycles.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        vbox1.Add(self.maxcycles, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.maxcycles.Disable()


        self.label01r = wx.lib.stattext.GenStaticText(self.panel, 116, "Dmin (A):", wx.Point(120, 150))
        vbox2.Add(self.label01r, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label01r.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.dmin = wx.TextCtrl(self.panel, 516, "",  (180, 150), (scale*150, -1))
        self.dmin.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        vbox2.Add(self.dmin, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.dmin.Disable()

        self.label02r = wx.lib.stattext.GenStaticText(self.panel, 117, "Convergence:", wx.Point(120, 150))
        vbox2.Add(self.label02r, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label02r.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.converg = wx.TextCtrl(self.panel, -1, "",  (180, 150), (scale*150, -1))
        vbox2.Add(self.converg, 517,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.converg.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.converg.Disable()

        self.label03r = wx.lib.stattext.GenStaticText(self.panel, 118, "Fprot label:", wx.Point(120, 150))
        vbox2.Add(self.label03r, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label03r.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.fprot = wx.TextCtrl(self.panel, 518, "",  (180, 150), (scale*150, -1))
        self.fprot.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        vbox2.Add(self.fprot, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.fprot.Disable()

        self.label04r = wx.lib.stattext.GenStaticText(self.panel, 119, "Fsub label:", wx.Point(120, 150))
        vbox2.Add(self.label04r, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label04r.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.fsub = wx.TextCtrl(self.panel, 519, "",  (180, 150), (scale*150, -1))
        self.fsub.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        vbox2.Add(self.fsub, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.fsub.Disable()

        self.label05r = wx.lib.stattext.GenStaticText(self.panel, 120, "Space group:", wx.Point(120, 150))
        vbox2.Add(self.label05r, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label05r.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.spgr = wx.TextCtrl(self.panel, 520, "auto",  (180, 150), (scale*150, -1))
        self.spgr.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        vbox2.Add(self.spgr, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )
        self.spgr.Disable()

        self.label06r = wx.lib.stattext.GenStaticText(self.panel, 121, "Normalize:", wx.Point(120, 150))
        vbox2.Add(self.label06r, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )
        self.label06r.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.norm_yes=wx.RadioButton(self.panel, 521, 'yes', (10, -1), style=wx.RB_GROUP)
        self.norm_no=wx.RadioButton(self.panel, 621, 'no', (10, -1))
        self.norm_yes.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.norm_no.Bind(wx.EVT_ENTER_WINDOW, self.Hovertext)
        self.norm_yes.SetValue(True)
        self.norm_no.Disable()
        self.norm_yes.Disable()
        hbox5.Add(self.norm_yes, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )
        hbox5.Add(self.norm_no, 0,  wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_VERTICAL, 1 )
        vbox2.Add(hbox5, 0,  wx.ALIGN_CENTER_VERTICAL, 1 )

        hbox1a.Add(vbox1, 0,  wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, 5 )
        hbox1a.Add(vbox2, 0,  wx.LEFT | wx.ALIGN_CENTER_VERTICAL, 5 )

#
        sizer1.Add(hbox1,0,  wx.TOP  | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 20)
        sizer1.Add(hbox2a,0,  wx.TOP  | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 20)
        sizer1.Add(hbox1a,0,  wx.TOP  | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 20)
        self.grid.Add(sizer1,0, wx.ALL | wx.LEFT  | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 10 )

        self.flipbutton = wx.Button(self.panel, 2, 'Flip', (60, 290))
        hbox4.Add(self.flipbutton, 0,  wx.TOP | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 15)
        self.flipbutton.Disable()

        self.button6 = wx.Button(self.panel, 9, 'Cancel', (60, 290))
        hbox4.Add(self.button6, 0,  wx.TOP | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 15)


        self.grid.Add(hbox4,0, wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 10 )

        self.panel.SetSizer(self.grid)



        self.Bind(wx.EVT_BUTTON, self.OnFlip, id=2)
        self.Bind(wx.EVT_BUTTON, self.OnExit, id=6)
        self.Bind(wx.EVT_CLOSE, self.OnExit)
        self.Bind(wx.EVT_BUTTON, self.OnCancel,id=9)
        self.Bind(wx.EVT_BUTTON, self.Browse, id=67)



        icon = wx.Icon("progmanager.ico", wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)

        w,h = self.panel.GetBestSize()
        self.SetClientSize((w, h))


        self.Show(True)
        self.Centre(True)




    def Hovertext(self,event):
      if event.GetId()  == 102 or event.GetId()  == 502:
          helptxt = wx.ToolTip("Input file: .mfm, .cif, .ent, .sca, .sf")
          helptxt.SetDelay(1)
          if event.GetId()  == 102:
              self.label01.SetToolTip(helptxt)
          else:
              self.inputfile.SetToolTip(helptxt)
      if event.GetId()  == 111 or event.GetId()  == 511:
          helptxt = wx.ToolTip("Base name for output files")
          helptxt.SetDelay(1)
          if event.GetId()  == 111:
              self.label02l.SetToolTip(helptxt)
          else:
              self.name.SetToolTip(helptxt)
      if event.GetId()  == 112 or event.GetId()  == 512:
          helptxt = wx.ToolTip("Flipping parameter k_ed")
          helptxt.SetDelay(1)
          if event.GetId()  == 112:
              self.label03l.SetToolTip(helptxt)
          else:
              self.ked.SetToolTip(helptxt)
      if event.GetId()  == 113 or event.GetId()  == 513:
          helptxt = wx.ToolTip("Fraction reflections considered to be weak")
          helptxt.SetDelay(1)
          if event.GetId()  == 113:
              self.label04l.SetToolTip(helptxt)
          else:
              self.weak.SetToolTip(helptxt)
      if event.GetId()  == 114 or event.GetId()  == 514:
          helptxt = wx.ToolTip("Number of trials")
          helptxt.SetDelay(1)
          if event.GetId()  == 114:
              self.label05l.SetToolTip(helptxt)
          else:
              self.trials.SetToolTip(helptxt)
      if event.GetId()  == 115 or event.GetId()  == 515:
          helptxt = wx.ToolTip("Maximum number of cycles per run")
          helptxt.SetDelay(1)
          if event.GetId()  == 115:
              self.label06l.SetToolTip(helptxt)
          else:
              self.maxcycles.SetToolTip(helptxt)
      if event.GetId()  == 116 or event.GetId()  == 516:
          helptxt = wx.ToolTip("Minimum resolution in Angstrom (default all reflections)")
          helptxt.SetDelay(1)
          if event.GetId()  == 116:
              self.label01r.SetToolTip(helptxt)
          else:
              self.dmin.SetToolTip(helptxt)
      if event.GetId()  == 117 or event.GetId()  == 517:
          helptxt = wx.ToolTip("Convergence criterion (peakiness)")
          helptxt.SetDelay(1)
          if event.GetId()  == 117:
              self.label02r.SetToolTip(helptxt)
          else:
              self.dmin.SetToolTip(helptxt)
      if event.GetId()  == 118 or event.GetId()  == 518:
          helptxt = wx.ToolTip("MTZ label assignement for amplitude (no default)")
          helptxt.SetDelay(1)
          if event.GetId()  == 118:
              self.label03r.SetToolTip(helptxt)
          else:
              self.fprot.SetToolTip(helptxt)
      if event.GetId()  == 119 or event.GetId()  == 519:
          helptxt = wx.ToolTip("MTZ label assignement for substructure signal (no default)")
          helptxt.SetDelay(1)
          if event.GetId()  == 119:
              self.label04r.SetToolTip(helptxt)
          else:
              self.fsub.SetToolTip(helptxt)
      if event.GetId()  == 120 or event.GetId()  == 520:
          helptxt = wx.ToolTip("Space group number (read from mtz file)")
          helptxt.SetDelay(1)
          if event.GetId()  == 120:
              self.label05r.SetToolTip(helptxt)
          else:
              self.spgr.SetToolTip(helptxt)
      if event.GetId()  == 121 or event.GetId()  == 521 or event.GetId()  == 621:
          if event.GetId()  == 121:
              helptxt = wx.ToolTip("Locally normalize structure factors")
              helptxt.SetDelay(1)
              self.label06r.SetToolTip(helptxt)
          elif event.GetId()  == 521:
              helptxt = wx.ToolTip("Locally normalize structure factors")
              helptxt.SetDelay(1)
              self.norm_yes.SetToolTip(helptxt)
          else:
              helptxt = wx.ToolTip("Do not locally normalize structure factors")
              helptxt.SetDelay(1)
              self.norm_no.SetToolTip(helptxt)


    def OnFlip(self,event):
        self.change_to_structure_directory()
        args = ["guirun",self.filename]
        if self.norm_no.GetValue():
           args.append("normalize=no")
        else:
           args.append("normalize=yes")
        if self.name.GetValue() != "": args.append("name=%s" % self.name.GetValue())
        if self.ked.GetValue() != "":
           args.append("ked=%s" % self.ked.GetValue())
        else:
           args.append("ked=1.3" % self.ked.GetValue())
        if self.weak.GetValue() != "":  args.append("weak=%s" % self.weak.GetValue())
        if self.dmin.GetValue() != "": args.append("dmin=%s" % self.dmin.GetValue())
        if self.converg.GetValue() != "": args.append("converg=%s" % self.converg.GetValue())
        if self.fprot.GetValue() != "": args.append("Fprot=%s" % self.fprot.GetValue())
        if self.fsub.GetValue() != "": args.append("Fsub=%s" % self.fsub.GetValue())
        if self.spgr.GetValue() != "auto" and self.spgr.GetValue() != "":
           args.append("SG=%s" % self.spgr.GetValue())
        try:
           args.append("maxcycl=%s" % int(self.maxcycles.GetValue()) )
        except:
           args.append("maxcycl=10000")
        try:
           args.append("repeat=%s" % int(self.trials.GetValue()) )
        except:
           args.append("repeat=1"  )
#        print "arguments passed"
#        print args
        self.Hide()
        fliprotsub5.flip(args)
        self.Show()
        os.chdir(self.current_directory)

        return


    def Browse(self,event):

        global lastdirectory
        mtz=False
        dlg = wx.FileDialog(None, "Choose the name of the structure factor file.",lastdirectory , wildcard="Structure factor file (*.mtz; *.cif; *.ent; *.sca; *.sf)|*.mtz;*.cif; *.ent; *.sca; *.sf|" "All files (*.*)|*.*", style=wx.STAY_ON_TOP)
        choice =  dlg.ShowModal()
        dlg.Destroy()
        if choice == wx.ID_OK:
            self.filename=dlg.GetFilename()
            self.inputfile.SetValue(self.filename)
            self.dirname=dlg.GetDirectory()

            lastdirectory = self.dirname
            print os.path.splitext(self.filename)[1]
            if os.path.splitext(self.filename)[1] != '.mtz' and os.path.splitext(self.filename)[1] != '.sca' and os.path.splitext(self.filename)[1] != '.cif' and os.path.splitext(self.filename)[1] != '.ent' and os.path.splitext(self.filename)[1] != '.sf':
               dlg = wx.MessageDialog(None, 'The selected file is not a legal protein reflection file. Try again', 'Error', wx.OK | wx.ICON_WARNING)
               choice =  dlg.ShowModal()
               dlg.Destroy()
               return
            if os.path.splitext(self.filename)[1] == '.mtz':
               dlg = wx.MessageDialog(None, 'Is the file for high resolution phasing (YES) or substructure phasing (NO)?', 'Question', wx.YES_NO | wx.ICON_WARNING)
               choice =  dlg.ShowModal()
               mtz = True
               if choice == wx.ID_NO:
                  self.sub.SetValue(True)
               else:
                  self.prot.SetValue(True)
               dlg.Destroy()
            if os.path.splitext(self.filename)[1] == '.sca': self.sub.SetValue(True)
            if os.path.splitext(self.filename)[1] == '.cif' or os.path.splitext(self.filename)[1] == '.ent' or os.path.splitext(self.filename)[1] == '.sf': self.prot.SetValue(True)

            self.name.Enable()
            self.maxcycles.Enable()
            self.ked.Enable()
            self.weak.Enable()
            self.trials.Enable()
            self.norm_no.Enable()
            self.norm_yes.Enable()
            self.converg.Enable()
            self.dmin.Enable()
            self.spgr.Enable()
            if mtz: self.spgr.SetValue("auto")
            if self.prot.GetValue():
               self.converg.SetValue("7.0")
               self.dmin.SetValue("0.8")
               self.weak.SetValue("0.20")
            else:
               self.converg.SetValue("3.0")
               self.dmin.SetValue("2.0")
               self.weak.SetValue("0.30")
               self.maxcycles.SetValue("5000")
               self.name.SetValue("flipsub")
            if os.path.splitext(self.filename)[1] != '.cif' and self.prot.GetValue(): self.fprot.Enable()
            if self.sub.GetValue(): self.fsub.Enable()
            self.flipbutton.Enable()

    def	change_to_structure_directory(self):
        self.current_directory = os.getcwd()
        print "change to: %s" % self.dirname
        os.chdir(self.dirname)
        return



    def OnCancel(self, event):

        frame.Show()
        self.Destroy()  # Close the frame.



    def OnExit(self, event):
        print "exit"
        frame.Show()

        self.Destroy()  # Close the frame.

def choosefont():
         global userfont,scale,ftsize
         Dw, Dh = wx.DisplaySize()
         Dw_mm, Dh_mm =  wx.DisplaySizeMM()
         Dw_i = Dw_mm / 25.4
         Dh_i = Dh_mm / 25.4
         ppi = Dw /Dw_i
         userfont=wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
         systemfontsize = userfont.GetPointSize()

         scale = ppi/100.0
         ftsize = int(round(scale*10.0,0))
         scale = float(ftsize)/float(systemfontsize)
         userfont.SetPointSize(ftsize)
#         print " ftsize %s; scale %s" % (ftsize,scale)
         return

global frame

global lastdirectory
lastdirectory = ""

app = wx.App(0)
choosefont()


frame = Main(None, -1)
app.MainLoop()

