Convert from DOS to UNIX line endings.
[hooke.git] / hooke / hooke.py
old mode 100755 (executable)
new mode 100644 (file)
index 55f23b1..547d7cc
-#!/usr/bin/env python\r
-\r
-'''\r
-HOOKE - A force spectroscopy review & analysis tool\r
-\r
-(C) 2008 Massimo Sandal\r
-\r
-Copyright (C) 2008 Massimo Sandal (University of Bologna, Italy).\r
-\r
-This program is released under the GNU General Public License version 2.\r
-'''\r
-\r
-from libhooke import HOOKE_VERSION\r
-from libhooke import WX_GOOD\r
-\r
-import os\r
-\r
-import wxversion\r
-wxversion.select(WX_GOOD)\r
-import wx\r
-import wxmpl\r
-from wx.lib.newevent import NewEvent\r
-\r
-import matplotlib.numerix as nx\r
-import scipy as sp\r
-\r
-from threading import *\r
-import Queue\r
-\r
-from hooke_cli import HookeCli\r
-from libhooke import *\r
-import libhookecurve as lhc\r
-\r
-#import file versions, just to know with what we're working...\r
-from hooke_cli import __version__ as hookecli_version\r
-\r
-global __version__\r
-global events_from_gui\r
-global config\r
-global CLI_PLUGINS\r
-global GUI_PLUGINS\r
-global LOADED_PLUGINS\r
-global PLOTMANIP_PLUGINS\r
-global FILE_DRIVERS\r
-\r
-__version__=HOOKE_VERSION[0]\r
-__release_name__=HOOKE_VERSION[1]\r
-\r
-events_from_gui=Queue.Queue() #GUI ---> CLI COMMUNICATION\r
-\r
-print 'Starting Hooke.'\r
-#CONFIGURATION FILE PARSING\r
-config_obj=HookeConfig()\r
-config=config_obj.load_config('hooke.conf')\r
-\r
-#IMPORTING PLUGINS\r
-\r
-CLI_PLUGINS=[]\r
-GUI_PLUGINS=[]\r
-PLOTMANIP_PLUGINS=[]\r
-LOADED_PLUGINS=[]\r
-\r
-plugin_commands_namespaces=[]\r
-plugin_gui_namespaces=[]\r
-for plugin_name in config['plugins']:\r
-    try:\r
-        plugin=__import__(plugin_name)\r
-        try:\r
-            eval('CLI_PLUGINS.append(plugin.'+plugin_name+'Commands)') #take Command plugin classes\r
-            plugin_commands_namespaces.append(dir(eval('plugin.'+plugin_name+'Commands')))\r
-        except:\r
-            pass\r
-        try:\r
-            eval('GUI_PLUGINS.append(plugin.'+plugin_name+'Gui)') #take Gui plugin classes\r
-            plugin_gui_namespaces.append(dir(eval('plugin.'+plugin_name+'Gui')))\r
-        except:\r
-            pass\r
-    except ImportError:\r
-        print 'Cannot find plugin ',plugin_name\r
-    else:\r
-        LOADED_PLUGINS.append(plugin_name)\r
-        print 'Imported plugin ',plugin_name\r
-\r
-#eliminate names common to all namespaces\r
-for i in range(len(plugin_commands_namespaces)):\r
-    plugin_commands_namespaces[i]=[item for item in plugin_commands_namespaces[i] if (item != '__doc__' and item != '__module__' and item != '_plug_init')]\r
-#check for conflicts in namespaces between plugins\r
-#FIXME: only in commands now, because I don't have Gui plugins to check\r
-#FIXME: how to check for plugin-defined variables (self.stuff) ??\r
-plugin_commands_names=[]\r
-whatplugin_defines=[]\r
-plugin_gui_names=[]\r
-for namespace,plugin_name in zip(plugin_commands_namespaces, config['plugins']):\r
-    for item in namespace:\r
-        if item in plugin_commands_names:\r
-            i=plugin_commands_names.index(item) #we exploit the fact index gives the *first* occurrence of a name...\r
-            print 'Error. Plugin ',plugin_name,' defines a function already defined by ',whatplugin_defines[i],'!'\r
-            print 'This should not happen. Please disable one or both plugins and contact the plugin authors to solve the conflict.'\r
-            print 'Hooke cannot continue.'\r
-            exit()\r
-        else:\r
-            plugin_commands_names.append(item)\r
-            whatplugin_defines.append(plugin_name)\r
-\r
-\r
-config['loaded_plugins']=LOADED_PLUGINS #FIXME: kludge -this should be global but not in config!\r
-#IMPORTING DRIVERS\r
-#FIXME: code duplication\r
-FILE_DRIVERS=[]\r
-LOADED_DRIVERS=[]\r
-for driver_name in config['drivers']:\r
-    try:\r
-        driver=__import__(driver_name)\r
-        try:\r
-            eval('FILE_DRIVERS.append(driver.'+driver_name+'Driver)')\r
-        except:\r
-            pass\r
-    except ImportError:\r
-        print 'Cannot find driver ',driver_name\r
-    else:\r
-        LOADED_DRIVERS.append(driver_name)\r
-        print 'Imported driver ',driver_name\r
-config['loaded_drivers']=LOADED_DRIVERS\r
-\r
-#LIST OF CUSTOM WX EVENTS FOR CLI ---> GUI COMMUNICATION\r
-#FIXME: do they need to be here?\r
-list_of_events={}\r
-\r
-plot_graph, EVT_PLOT = NewEvent()\r
-list_of_events['plot_graph']=plot_graph\r
-\r
-plot_contact, EVT_PLOT_CONTACT = NewEvent()\r
-list_of_events['plot_contact']=plot_contact\r
-\r
-measure_points, EVT_MEASURE_POINTS = NewEvent()\r
-list_of_events['measure_points']=measure_points\r
-\r
-export_image, EVT_EXPORT_IMAGE = NewEvent()\r
-list_of_events['export_image']=export_image\r
-\r
-close_plot, EVT_CLOSE_PLOT = NewEvent()\r
-list_of_events['close_plot'] = close_plot\r
-\r
-show_plots, EVT_SHOW_PLOTS = NewEvent()\r
-list_of_events['show_plots'] = show_plots\r
-\r
-get_displayed_plot, EVT_GET_DISPLAYED_PLOT = NewEvent()\r
-list_of_events['get_displayed_plot'] = get_displayed_plot\r
-#------------\r
-\r
-class CliThread(Thread):\r
-\r
-    def __init__(self,frame,list_of_events):\r
-        Thread.__init__(self)\r
-\r
-        #here we have to put temporary references to pass to the cli object.\r
-        self.frame=frame\r
-        self.list_of_events=list_of_events\r
-\r
-        self.debug=0 #to be used in the future\r
-\r
-    def run(self):\r
-        print '\n\nThis is Hooke, version',__version__ , __release_name__\r
-        print\r
-        print '(c) Massimo Sandal & others, 2006-2008. Released under the GNU Lesser General Public License Version 3'\r
-        print 'Hooke is Free software.'\r
-        print '----'\r
-        print ''\r
-\r
-        def make_command_class(*bases):\r
-            #FIXME: perhaps redundant\r
-            return type(HookeCli)("HookeCliPlugged", bases + (HookeCli,), {})\r
-        cli = make_command_class(*CLI_PLUGINS)(self.frame,self.list_of_events,events_from_gui,config,FILE_DRIVERS)\r
-        cli.cmdloop()\r
-\r
-'''\r
-GUI CODE\r
-\r
-FIXME: put it in a separate module in the future?\r
-'''\r
-class MainMenuBar(wx.MenuBar):\r
-    '''\r
-    Creates the menu bar\r
-    '''\r
-    def __init__(self):\r
-        wx.MenuBar.__init__(self)\r
-        '''the menu description. the key of the menu is XX&Menu, where XX is a number telling\r
-        the order of the menus on the menubar.\r
-        &Menu is the Menu text\r
-        the corresponding argument is ('&Item', 'itemname'), where &Item is the item text and itemname\r
-        the inner reference to use in the self.menu_items dictionary.\r
-\r
-        See create_menus() to see how it works\r
-\r
-        Note: the mechanism on page 124 of "wxPython in Action" is less awkward, maybe, but I want\r
-        binding to be performed later. Perhaps I'm wrong :)\r
-        ''' \r
-\r
-        self.menu_desc={'00&File':[('&Open playlist','openplaymenu'),('&Exit','exitmenu')], \r
-                        '01&Edit':[('&Export text...','exporttextmenu'),('&Export image...','exportimagemenu')],\r
-                        '02&Help':[('&About Hooke','aboutmenu')]}\r
-        self.create_menus()\r
-\r
-    def create_menus(self):\r
-        '''\r
-        Smartish routine to create the menu from the self.menu_desc dictionary\r
-        Hope it's a workable solution for the future.\r
-        '''\r
-        self.menus=[] #the menu objects to append to the menubar\r
-        self.menu_items={} #the single menu items dictionary, to bind to events\r
-\r
-        names=self.menu_desc.keys() #we gotta sort, because iterating keys goes in odd order\r
-        names.sort()\r
-\r
-        for name in names:\r
-            self.menus.append(wx.Menu())\r
-            for menu_item in self.menu_desc[name]:\r
-                self.menu_items[menu_item[1]]=self.menus[-1].Append(-1, menu_item[0])\r
-\r
-        for menu,name in zip(self.menus,names):\r
-            self.Append(menu,name[2:])\r
-\r
-class MainPanel(wx.Panel):\r
-    def __init__(self,parent,id):  \r
-\r
-        wx.Panel.__init__(self,parent,id)\r
-        self.splitter = wx.SplitterWindow(self)\r
-\r
-ID_FRAME=100        \r
-class MainWindow(wx.Frame):\r
-    '''we make a frame inheriting wx.Frame and setting up things on the init'''\r
-    def __init__(self,parent,id,title):\r
-\r
-        #-----------------------------\r
-        #WX WIDGETS INITIALIZATION\r
-\r
-        wx.Frame.__init__(self,parent,ID_FRAME,title,size=(800,600),style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)\r
-\r
-        self.mainpanel=MainPanel(self,-1)\r
-        self.cpanels=[]\r
-\r
-        self.cpanels.append(wx.Panel(self.mainpanel.splitter,-1))\r
-        self.cpanels.append(wx.Panel(self.mainpanel.splitter,-1))\r
-\r
-        self.statusbar=wx.StatusBar(self,-1)\r
-        self.SetStatusBar(self.statusbar)\r
-\r
-        self.mainmenubar=MainMenuBar()\r
-        self.SetMenuBar(self.mainmenubar)\r
-\r
-        self.controls=[]\r
-        self.figures=[]\r
-        self.axes=[]\r
-\r
-        #This is our matplotlib plot\r
-        self.controls.append(wxmpl.PlotPanel(self.cpanels[0],-1))\r
-        self.controls.append(wxmpl.PlotPanel(self.cpanels[1],-1))\r
-        #These are our figure and axes, so to have easy references\r
-        #Also, we initialize\r
-        self.figures=[control.get_figure() for control in self.controls]\r
-        self.axes=[figure.gca() for figure in self.figures]\r
-\r
-        self.cpanels[1].Hide()\r
-        self.mainpanel.splitter.Initialize(self.cpanels[0])\r
-\r
-        self.sizer_dance() #place/size the widgets\r
-\r
-        self.controls[0].SetSize(self.cpanels[0].GetSize())\r
-        self.controls[1].SetSize(self.cpanels[1].GetSize())\r
-\r
-        #resize the frame to properly draw on Windows\r
-        frameSize=self.GetSize()\r
-        frameSize.DecBy(1, 1)\r
-        self.SetSize(frameSize)\r
-        '''\r
-        #if you need the exact same size as before DecBy, uncomment this block\r
-        frameSize.IncBy(1, 1)\r
-        self.SetSize(frameSize)\r
-        '''\r
-\r
-        #-------------------------------------------\r
-        #NON-WX WIDGETS INITIALIZATION\r
-\r
-        #Flags.\r
-        self.click_plot=0\r
-\r
-        #FIXME: These could become a single flag with different (string?) values\r
-        #self.on_measure_distance=False\r
-        #self.on_measure_force=False\r
-\r
-        self.plot_fit=False\r
-\r
-        #Number of points to be clicked\r
-        self.num_of_points = 2\r
-\r
-        #Data.\r
-        '''\r
-            self.current_x_ext=[[],[]]\r
-            self.current_y_ext=[[],[]]\r
-            self.current_x_ret=[[],[]]\r
-            self.current_y_ret=[[],[]]\r
-\r
-\r
-            self.current_x_unit=[None,None]\r
-            self.current_y_unit=[None,None]\r
-            '''\r
-\r
-        #Initialize xaxes, yaxes\r
-        #FIXME: should come from config\r
-        self.current_xaxes=0\r
-        self.current_yaxes=0\r
-\r
-        #Other\r
-\r
-\r
-        self.index_buffer=[]\r
-\r
-        self.clicked_points=[]\r
-\r
-        self.measure_set=None\r
-\r
-        self.events_from_gui = events_from_gui\r
-\r
-        '''\r
-            This dictionary keeps all the flags and the relative functon names that\r
-            have to be called when a point is clicked.\r
-            That is:\r
-            - if point is clicked AND foo_flag=True\r
-            - foo()\r
-\r
-            Conversely, foo_flag is True if a corresponding event is launched by the CLI.\r
-\r
-            self.ClickedPoints() takes care of handling this\r
-            '''\r
-\r
-        self.click_flags_functions={'measure_points':[False, 'MeasurePoints']}\r
-\r
-        #Binding of custom events from CLI --> GUI functions!                       \r
-        #FIXME: Should use the self.Bind() syntax\r
-        EVT_PLOT(self, self.PlotCurve)\r
-        EVT_PLOT_CONTACT(self, self.PlotContact)\r
-        EVT_GET_DISPLAYED_PLOT(self, self.OnGetDisplayedPlot)\r
-        EVT_MEASURE_POINTS(self, self.OnMeasurePoints)\r
-        EVT_EXPORT_IMAGE(self,self.ExportImage)\r
-        EVT_CLOSE_PLOT(self, self.OnClosePlot)\r
-        EVT_SHOW_PLOTS(self, self.OnShowPlots)\r
-\r
-        #This event and control decide what happens when I click on the plot 0.\r
-        wxmpl.EVT_POINT(self, self.controls[0].GetId(), self.ClickPoint0)\r
-        wxmpl.EVT_POINT(self, self.controls[1].GetId(), self.ClickPoint1)\r
-\r
-        #RUN PLUGIN-SPECIFIC INITIALIZATION\r
-        #make sure we execute _plug_init() for every command line plugin we import\r
-        for plugin_name in config['plugins']:\r
-            try:\r
-                plugin=__import__(plugin_name)\r
-                try:\r
-                    eval('plugin.'+plugin_name+'Gui._plug_init(self)')\r
-                    pass\r
-                except AttributeError:\r
-                    pass\r
-            except ImportError:\r
-                pass\r
-\r
-\r
-\r
-    #WX-SPECIFIC FUNCTIONS\r
-    def sizer_dance(self):\r
-        '''\r
-            adjust size and placement of wxpython widgets.\r
-            '''\r
-        self.splittersizer = wx.BoxSizer(wx.VERTICAL)\r
-        self.splittersizer.Add(self.mainpanel.splitter, 1, wx.EXPAND)\r
-\r
-        self.plot1sizer = wx.BoxSizer()\r
-        self.plot1sizer.Add(self.controls[0], 1, wx.EXPAND)\r
-\r
-        self.plot2sizer = wx.BoxSizer()\r
-        self.plot2sizer.Add(self.controls[1], 1, wx.EXPAND)\r
-\r
-        self.panelsizer=wx.BoxSizer()\r
-        self.panelsizer.Add(self.mainpanel, -1, wx.EXPAND)\r
-\r
-        self.cpanels[0].SetSizer(self.plot1sizer)\r
-        self.cpanels[1].SetSizer(self.plot2sizer)\r
-\r
-        self.mainpanel.SetSizer(self.splittersizer)\r
-        self.SetSizer(self.panelsizer)\r
-\r
-    def binding_dance(self):\r
-        self.Bind(wx.EVT_MENU, self.OnOpenPlayMenu, self.menubar.menu_items['openplaymenu'])\r
-        self.Bind(wx.EVT_MENU, self.OnExitMenu, self.menubar.menu_items['exitmenu'])\r
-        self.Bind(wx.EVT_MENU, self.OnExportText, self.menubar.menu_items['exporttextmenu'])\r
-        self.Bind(wx.EVT_MENU, self.OnExportImage, self.menubar.menu_items['exportimagemenu'])\r
-        self.Bind(wx.EVT_MENU, self.OnAboutMenu, self.menubar.menu_items['aboutmenu'])\r
-\r
-    # DOUBLE PLOT MANAGEMENT\r
-    #----------------------\r
-    def show_both(self):\r
-        '''\r
-            Shows both plots.\r
-            '''\r
-        self.mainpanel.splitter.SplitHorizontally(self.cpanels[0],self.cpanels[1])\r
-        self.mainpanel.splitter.SetSashGravity(0.5)\r
-        self.mainpanel.splitter.SetSashPosition(300) #FIXME: we should get it and restore it\r
-        self.mainpanel.splitter.UpdateSize()\r
-\r
-    def close_plot(self,plot):\r
-        '''\r
-            Closes one plot - only if it's open\r
-            '''\r
-        if not self.cpanels[plot].IsShown():\r
-            return\r
-        if plot != 0:\r
-            self.current_plot_dest = 0\r
-        else:\r
-            self.current_plot_dest = 1\r
-        self.cpanels[plot].Hide()\r
-        self.mainpanel.splitter.Unsplit(self.cpanels[plot])\r
-        self.mainpanel.splitter.UpdateSize()\r
-\r
-\r
-    def OnClosePlot(self,event):\r
-        self.close_plot(event.to_close)       \r
-\r
-    def OnShowPlots(self,event):\r
-        self.show_both()\r
-\r
-\r
-    #FILE MENU FUNCTIONS\r
-    #--------------------\r
-    def OnOpenPlayMenu(self, event):\r
-        pass \r
-\r
-    def OnExitMenu(self,event):\r
-        pass\r
-\r
-    def OnExportText(self,event):\r
-        pass\r
-\r
-    def OnExportImage(self,event):\r
-        pass\r
-\r
-    def OnAboutMenu(self,event):\r
-        pass\r
-\r
-    #PLOT INTERACTION    \r
-    #----------------                        \r
-    def PlotCurve(self,event):\r
-        '''\r
-            plots the current ext,ret curve.\r
-            '''\r
-        dest=0\r
-\r
-        #FIXME: BAD kludge following. There should be a well made plot queue mechanism, with replacements etc.\r
-        #---\r
-        #If we have only one plot in the event, we already have one in self.plots and this is a secondary plot,\r
-        #do not erase self.plots but append the new plot to it.\r
-        if len(event.plots) == 1 and event.plots[0].destination != 0 and len(self.plots) == 1:\r
-            self.plots.append(event.plots[0])\r
-        #if we already have two plots and a new secondary plot comes, we substitute the previous\r
-        if len(event.plots) == 1 and event.plots[0].destination != 0 and len(self.plots) > 1:\r
-            self.plots[1] = event.plots[0]\r
-        else:\r
-            self.plots = event.plots\r
-\r
-        #FIXME. Should be in PlotObject, somehow\r
-        c=0\r
-        for plot in self.plots:\r
-            if self.plots[c].styles==[]:\r
-                self.plots[c].styles=[None for item in plot.vectors] \r
-            if self.plots[c].colors==[]:\r
-                self.plots[c].colors=[None for item in plot.vectors] \r
-\r
-        for plot in self.plots:\r
-            '''\r
-            MAIN LOOP FOR ALL PLOTS (now only 2 are allowed but...)\r
-            '''\r
-            if 'destination' in dir(plot):\r
-                dest=plot.destination\r
-\r
-            #if the requested panel is not shown, show it\r
-            if not ( self.cpanels[dest].IsShown() ):\r
-                self.show_both()\r
-\r
-            self.axes[dest].hold(False)\r
-            self.current_vectors=plot.vectors\r
-            self.current_title=plot.title\r
-            self.current_plot_dest=dest #let's try this way to take into account the destination plot...\r
-\r
-            c=0\r
-\r
-            if len(plot.colors)==0:\r
-                plot.colors=[None] * len(plot.vectors)\r
-            if len(plot.styles)==0:\r
-                plot.styles=[None] * len(plot.vectors)     \r
-\r
-            for vectors_to_plot in self.current_vectors: \r
-                if plot.styles[c]=='scatter':\r
-                    if plot.colors[c]==None:\r
-                        self.axes[dest].scatter(vectors_to_plot[0], vectors_to_plot[1])\r
-                    else:\r
-                        self.axes[dest].scatter(vectors_to_plot[0], vectors_to_plot[1],color=plot.colors[c])\r
-                else:\r
-                    if plot.colors[c]==None:\r
-                        self.axes[dest].plot(vectors_to_plot[0], vectors_to_plot[1])\r
-                    else:\r
-                        self.axes[dest].plot(vectors_to_plot[0], vectors_to_plot[1], color=plot.colors[c])\r
-                self.axes[dest].hold(True)\r
-                c+=1\r
-\r
-            '''\r
-                for vectors_to_plot in self.current_vectors:\r
-                    if len(vectors_to_plot)==2: #3d plots are to come...\r
-                        if len(plot.styles) > 0 and plot.styles[c] == 'scatter':\r
-                            self.axes[dest].scatter(vectors_to_plot[0],vectors_to_plot[1])\r
-                        elif len(plot.styles) > 0 and plot.styles[c] == 'scatter_red':\r
-                            self.axes[dest].scatter(vectors_to_plot[0],vectors_to_plot[1],color='red')\r
-                        else:\r
-                            self.axes[dest].plot(vectors_to_plot[0],vectors_to_plot[1])\r
-\r
-                        self.axes[dest].hold(True)\r
-                        c+=1\r
-                    else:\r
-                        pass\r
-                '''               \r
-            #FIXME: tackles only 2d plots\r
-            self.axes[dest].set_xlabel(plot.units[0])\r
-            self.axes[dest].set_ylabel(plot.units[1])\r
-\r
-            #FIXME: set smaller fonts\r
-            self.axes[dest].set_title(plot.title)\r
-\r
-            if plot.xaxes: \r
-                #swap X axis\r
-                xlim=self.axes[dest].get_xlim()\r
-                self.axes[dest].set_xlim((xlim[1],xlim[0])) \r
-            if plot.yaxes:\r
-                #swap Y axis\r
-                ylim=self.axes[dest].get_ylim()        \r
-                self.axes[dest].set_ylim((ylim[1],ylim[0])) \r
-\r
-            self.controls[dest].draw()\r
-\r
-\r
-    def PlotContact(self,event):\r
-        '''\r
-            plots the contact point\r
-            DEPRECATED!\r
-            '''\r
-        self.axes[0].hold(True)\r
-        self.current_contact_index=event.contact_index\r
-\r
-        #now we fake a clicked point \r
-        self.clicked_points.append(ClickedPoint())\r
-        self.clicked_points[-1].absolute_coords=self.current_x_ret[dest][self.current_contact_index], self.current_y_ret[dest][self.current_contact_index]\r
-        self.clicked_points[-1].is_marker=True    \r
-\r
-        self._replot()\r
-        self.clicked_points=[]\r
-\r
-    def OnMeasurePoints(self,event):\r
-        '''\r
-            trigger flags to measure N points\r
-            '''\r
-        self.click_flags_functions['measure_points'][0]=True\r
-        if 'num_of_points' in dir(event):\r
-            self.num_of_points=event.num_of_points\r
-        if 'set' in dir(event):    \r
-            self.measure_set=event.set            \r
-\r
-    def ClickPoint0(self,event):\r
-        self.current_plot_dest=0\r
-        self.ClickPoint(event)\r
-    def ClickPoint1(self,event):\r
-        self.current_plot_dest=1\r
-        self.ClickPoint(event)\r
-\r
-    def ClickPoint(self,event):\r
-        '''\r
-            this function decides what to do when we receive a left click on the axes.\r
-            We trigger other functions:\r
-            - the action chosen by the CLI sends an event\r
-            - the event raises a flag : self.click_flags_functions['foo'][0]\r
-            - the raised flag wants the function in self.click_flags_functions[1] to be called after a click\r
-            '''\r
-        for key, value in self.click_flags_functions.items():\r
-            if value[0]:\r
-                eval('self.'+value[1]+'(event)')\r
-\r
-\r
-\r
-    def MeasurePoints(self,event,current_set=1):\r
-        dest=self.current_plot_dest\r
-        try:\r
-            current_set=self.measure_set\r
-        except AttributeError:\r
-            pass\r
-\r
-        #find the current plot matching the clicked destination\r
-        plot=self._plot_of_dest()\r
-        if len(plot.vectors)-1 < current_set: #what happens if current_set is 1 and we have only 1 vector?\r
-            current_set=current_set-len(plot.vectors)\r
-\r
-        xvector=plot.vectors[current_set][0]\r
-        yvector=plot.vectors[current_set][1]\r
-\r
-        self.clicked_points.append(ClickedPoint())            \r
-        self.clicked_points[-1].absolute_coords=event.xdata, event.ydata\r
-        self.clicked_points[-1].find_graph_coords(xvector,yvector)\r
-        self.clicked_points[-1].is_marker=True    \r
-        self.clicked_points[-1].is_line_edge=True\r
-        self.clicked_points[-1].dest=dest                \r
-\r
-        self._replot()\r
-\r
-        if len(self.clicked_points)==self.num_of_points:\r
-            self.events_from_gui.put(self.clicked_points)\r
-            #restore to default state:\r
-            self.clicked_points=[]\r
-            self.click_flags_functions['measure_points'][0]=False    \r
-\r
-\r
-    def OnGetDisplayedPlot(self,event):\r
-        if 'dest' in dir(event):\r
-            self.GetDisplayedPlot(event.dest)\r
-        else:\r
-            self.GetDisplayedPlot(self.current_plot_dest)\r
-\r
-    def GetDisplayedPlot(self,dest):\r
-        '''\r
-            returns to the CLI the currently displayed plot for the given destination\r
-            '''\r
-        displayed_plot=self._plot_of_dest(dest)\r
-        events_from_gui.put(displayed_plot)\r
-\r
-    def ExportImage(self,event):\r
-        '''\r
-            exports an image as a file.\r
-            Current supported file formats: png, eps\r
-            (matplotlib docs say that jpeg should be supported too, but with .jpg it doesn't work for me!)\r
-            '''\r
-        #dest=self.current_plot_dest\r
-        dest=event.dest\r
-        filename=event.name\r
-        self.figures[dest].savefig(filename)\r
-\r
-    '''\r
-        def _find_nearest_point(self, mypoint, dataset=1):\r
-\r
-            #Given a clicked point on the plot, finds the nearest point in the dataset (in X) that\r
-            #corresponds to the clicked point.\r
-\r
-            dest=self.current_plot_dest\r
-\r
-            xvector=plot.vectors[dataset][0]\r
-            yvector=plot.vectors[dataset][1]\r
-\r
-            #Ye Olde sorting algorithm...\r
-            #FIXME: is there a better solution?\r
-            index=0\r
-            best_index=0\r
-            best_diff=10^9 #hope we never go over this magic number :(\r
-            for point in xvector:\r
-                diff=abs(point-mypoint)\r
-                if diff<best_diff:\r
-                    best_index=index\r
-                    best_diff=diff\r
-                index+=1\r
-\r
-            return best_index,xvector[best_index],yvector[best_index]\r
-         '''   \r
-\r
-    def _plot_of_dest(self,dest=None):\r
-        '''\r
-            returns the plot that has the current destination\r
-            '''\r
-        if dest==None:\r
-            dest=self.current_plot_dest\r
-\r
-        plot=None\r
-        for aplot in self.plots:\r
-            if aplot.destination == dest:\r
-                plot=aplot\r
-        return plot\r
-\r
-    def _replot(self):\r
-        '''\r
-            this routine is needed for a fresh clean-and-replot of interface\r
-            otherwise, refreshing works very badly :(\r
-\r
-            thanks to Ken McIvor, wxmpl author!\r
-            '''\r
-        dest=self.current_plot_dest\r
-        #we get current zoom limits\r
-        xlim=self.axes[dest].get_xlim()\r
-        ylim=self.axes[dest].get_ylim()           \r
-        #clear axes\r
-        self.axes[dest].cla()\r
-\r
-        #Plot curve:         \r
-        #find the current plot matching the clicked destination\r
-        plot=self._plot_of_dest()\r
-        #plot all superimposed plots \r
-        c=0 \r
-        if len(plot.colors)==0:\r
-            plot.colors=[None] * len(plot.vectors)\r
-        if len(plot.styles)==0:\r
-            plot.styles=[None] * len(plot.vectors)     \r
-        for plotset in plot.vectors: \r
-            if plot.styles[c]=='scatter':\r
-                if plot.colors[c]==None:\r
-                    self.axes[dest].scatter(plotset[0], plotset[1])\r
-                else:\r
-                    self.axes[dest].scatter(plotset[0], plotset[1],color=plot.colors[c])\r
-            else:\r
-                if plot.colors[c]==None:\r
-                    self.axes[dest].plot(plotset[0], plotset[1])\r
-                else:\r
-                    self.axes[dest].plot(plotset[0], plotset[1], color=plot.colors[c])\r
-            '''    \r
-                if len(plot.styles) > 0 and plot.styles[c]=='scatter':\r
-                    self.axes[dest].scatter(plotset[0], plotset[1],color=plot.colors[c])\r
-                elif len(plot.styles) > 0 and plot.styles[c] == 'scatter_red':\r
-                    self.axes[dest].scatter(plotset[0],plotset[1],color='red')\r
-                else:\r
-                    self.axes[dest].plot(plotset[0], plotset[1])\r
-                '''\r
-            c+=1\r
-        #plot points we have clicked\r
-        for item in self.clicked_points:\r
-            if item.is_marker:\r
-                if item.graph_coords==(None,None): #if we have no graph coords, we display absolute coords\r
-                    self.axes[dest].scatter([item.absolute_coords[0]],[item.absolute_coords[1]])\r
-                else:\r
-                    self.axes[dest].scatter([item.graph_coords[0]],[item.graph_coords[1]])               \r
-\r
-        if self.plot_fit:\r
-            print 'DEBUGGING WARNING: use of self.plot_fit is deprecated!'\r
-            self.axes[dest].plot(self.plot_fit[0],self.plot_fit[1])\r
-\r
-        self.axes[dest].hold(True)      \r
-        #set old axes again\r
-        self.axes[dest].set_xlim(xlim)\r
-        self.axes[dest].set_ylim(ylim)\r
-        #set title and names again...\r
-        self.axes[dest].set_title(self.current_title)           \r
-        self.axes[dest].set_xlabel(plot.units[0])\r
-        self.axes[dest].set_ylabel(plot.units[1])\r
-        #and redraw!\r
-        self.controls[dest].draw()\r
-\r
-\r
-class MySplashScreen(wx.SplashScreen):\r
-    """\r
-    Create a splash screen widget.\r
-    That's just a fancy addition... every serious application has a splash screen!\r
-    """\r
-    def __init__(self, frame):\r
-        # This is a recipe to a the screen.\r
-        # Modify the following variables as necessary.\r
-        #aBitmap = wx.Image(name = "wxPyWiki.jpg").ConvertToBitmap()\r
-        aBitmap=wx.Image(name='hooke.jpg').ConvertToBitmap()\r
-        splashStyle = wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT\r
-        splashDuration = 2000 # milliseconds\r
-        splashCallback = None\r
-        # Call the constructor with the above arguments in exactly the\r
-        # following order.\r
-        wx.SplashScreen.__init__(self, aBitmap, splashStyle,\r
-                                 splashDuration, None, -1)\r
-        wx.EVT_CLOSE(self, self.OnExit)\r
-        self.frame=frame\r
-        wx.Yield()\r
-\r
-    def OnExit(self, evt):\r
-        self.Hide()\r
-\r
-        self.frame.Show()\r
-        # The program will freeze without this line.\r
-        evt.Skip()  # Make sure the default handler runs too...\r
-\r
-\r
-#------------------------------------------------------------------------------\r
-\r
-def main():\r
-\r
-    #save the directory where Hooke is located\r
-    config['hookedir']=os.getcwd()\r
-\r
-    #now change to the working directory.\r
-    try:\r
-        os.chdir(config['workdir'])\r
-    except OSError:\r
-        print "Warning: Invalid work directory."\r
-\r
-    app=wx.PySimpleApp()\r
-\r
-    def make_gui_class(*bases):\r
-        return type(MainWindow)("MainWindowPlugged", bases + (MainWindow,), {})\r
-\r
-    main_frame = make_gui_class(*GUI_PLUGINS)(None, -1, ('Hooke '+__version__))\r
-\r
-    #FIXME. The frame.Show() is called by the splashscreen here! Ugly as hell.\r
-\r
-    mysplash=MySplashScreen(main_frame)\r
-    mysplash.Show()\r
-\r
-    my_cmdline=CliThread(main_frame, list_of_events)\r
-    my_cmdline.start()\r
-\r
-\r
-    app.MainLoop()\r
-\r
-if __name__ == '__main__':\r
-    main()\r
+#!/usr/bin/env python
+
+'''
+HOOKE - A force spectroscopy review & analysis tool
+
+Copyright (C) 2008-2010 Massimo Sandal (University of Bologna, Italy).
+                        Rolf Schmidt (Concordia University, Canada).
+
+This program is released under the GNU General Public License version 2.
+'''
+
+from libhooke import WX_GOOD
+
+import wxversion
+wxversion.select(WX_GOOD)
+import copy
+import cStringIO
+import os
+import os.path
+import sys
+import glob
+import time
+
+import imp
+import wx
+import wx.html
+import wx.aui
+import wxmpl
+import wx.lib.agw.aui as aui
+import wx.propgrid as wxpg
+
+import libhooke as lh
+from config import config
+import drivers
+import plugins
+import hookecommands
+import hookeplaylist
+import hookepropertyeditor
+import hookeresults
+import playlist
+
+global __version__
+
+__version__ = lh.HOOKE_VERSION[0]
+__release_name__ = lh.HOOKE_VERSION[1]
+
+#TODO: order menu items, get rid of all unused IDs
+ID_ExportText = wx.NewId()
+ID_ExportImage = wx.NewId()
+ID_Config = wx.NewId()
+ID_About = wx.NewId()
+ID_Next = wx.NewId()
+ID_Previous = wx.NewId()
+
+ID_ViewAssistant = wx.NewId()
+ID_ViewCommands = wx.NewId()
+ID_ViewFolders = wx.NewId()
+ID_ViewOutput = wx.NewId()
+ID_ViewPlaylists = wx.NewId()
+ID_ViewProperties = wx.NewId()
+ID_ViewResults = wx.NewId()
+
+ID_CommandsList = wx.NewId()
+ID_CommandsListBox = wx.NewId()
+
+ID_TextContent = wx.NewId()
+ID_TreeContent = wx.NewId()
+ID_HTMLContent = wx.NewId()
+ID_SizeReportContent = wx.NewId()
+ID_DeletePerspective = wx.NewId()
+ID_SavePerspective = wx.NewId()
+
+ID_FirstPerspective = ID_SavePerspective + 1000
+#I hope we'll never have more than 1000 perspectives
+ID_FirstPlot = ID_SavePerspective + 2000
+
+class Hooke(wx.App):
+
+    def OnInit(self):
+        self.SetAppName('Hooke')
+        self.SetVendorName('')
+
+        #set the Hooke directory
+        lh.hookeDir = os.path.abspath(os.path.dirname(__file__))
+
+        windowPosition = (config['main']['left'], config['main']['top'])
+        windowSize = (config['main']['width'], config['main']['height'])
+
+        #setup the splashscreen
+        if config['splashscreen']['show']:
+            filename = lh.get_file_path('hooke.jpg', ['resources'])
+            if os.path.isfile(filename):
+                bitmap = wx.Image(filename).ConvertToBitmap()
+                splashStyle = wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_TIMEOUT
+                splashDuration = config['splashscreen']['duration']
+                wx.SplashScreen(bitmap, splashStyle, splashDuration, None, -1)
+                wx.Yield()
+                '''
+                we need for the splash screen to disappear
+                for whatever reason splashDuration and sleep do not correspond to each other
+                at least not on Windows
+                maybe it's because duration is in milliseconds and sleep in seconds
+                thus we need to increase the sleep time a bit
+                a factor of 1.2 seems to work quite well
+                '''
+                sleepFactor = 1.2
+                time.sleep(sleepFactor * splashDuration / 1000)
+
+        plugin_objects = []
+        for plugin in config['plugins']:
+            if config['plugins'][plugin]:
+                filename = ''.join([plugin, '.py'])
+                path = lh.get_file_path(filename, ['plugins'])
+                if os.path.isfile(path):
+                    #get the corresponding filename and path
+                    plugin_name = ''.join(['plugins.', plugin])
+                    module = __import__(plugin_name)
+                    #get the file that contains the plugin
+                    class_file = getattr(plugins, plugin)
+                    #get the class that contains the commands
+                    class_object = getattr(class_file, plugin + 'Commands')
+                    plugin_objects.append(class_object)
+
+        def make_command_class(*bases):
+            #create metaclass with plugins and plotmanipulators
+            return type(HookeFrame)("HookeFramePlugged", bases + (HookeFrame,), {})
+        frame = make_command_class(*plugin_objects)(parent=None, id=wx.ID_ANY, title='Hooke', pos=windowPosition, size=windowSize)
+        frame.Show(True)
+        self.SetTopWindow(frame)
+
+        return True
+
+    def OnExit(self):
+        #TODO: write values to ini file if necessary
+        return True
+
+
+class HookeFrame(wx.Frame):
+
+    def __init__(self, parent, id=-1, title='', pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE|wx.SUNKEN_BORDER|wx.CLIP_CHILDREN):
+        #call parent constructor
+        wx.Frame.__init__(self, parent, id, title, pos, size, style)
+        self.config = config
+        self.CreateApplicationIcon()
+        #self.configs contains: {the name of the Commands file: corresponding ConfigObj}
+        self.configs = {}
+        ##self.playlists contains: {the name of the playlist: [playlist, tabIndex, plotID]}
+        #self.playlists = {}
+        #self.plugins contains: {the name of the plugin: [caption, function]}
+        self.plugins = {}
+        #self.plotmanipulators list contains: [the name of the plotmanip, function, name of the module]
+        self.plotmanipulators = []
+
+        #tell FrameManager to manage this frame
+        self._mgr = aui.AuiManager()
+        self._mgr.SetManagedWindow(self)
+        #set the gradient style
+        self._mgr.GetArtProvider().SetMetric(aui.AUI_DOCKART_GRADIENT_TYPE, aui.AUI_GRADIENT_NONE)
+        #set transparent drag
+        self._mgr.SetFlags(self._mgr.GetFlags() ^ aui.AUI_MGR_TRANSPARENT_DRAG)
+
+        # set up default notebook style
+        self._notebook_style = aui.AUI_NB_DEFAULT_STYLE | aui.AUI_NB_TAB_EXTERNAL_MOVE | wx.NO_BORDER
+        self._notebook_theme = 0
+
+        #holds the perspectives: {name, [index, perspectiveStr]}
+        self._perspectives = {}
+
+        # min size for the frame itself isn't completely done.
+        # see the end up FrameManager::Update() for the test
+        # code. For now, just hard code a frame minimum size
+        self.SetMinSize(wx.Size(400, 300))
+        #create panels here
+        self.panelAssistant = self.CreatePanelAssistant()
+        self.panelCommands = self.CreatePanelCommands()
+        self.panelFolders = self.CreatePanelFolders()
+        self.panelPlaylists = self.CreatePanelPlaylists()
+        self.panelProperties = self.CreatePanelProperties()
+        self.panelOutput = self.CreatePanelOutput()
+        self.panelResults = self.CreatePanelResults()
+        self.plotNotebook = self.CreateNotebook()
+        #self.textCtrlCommandLine=self.CreateCommandLine()
+
+        # add panes
+        self._mgr.AddPane(self.panelFolders, aui.AuiPaneInfo().Name('Folders').Caption('Folders').Left().CloseButton(True).MaximizeButton(False))
+        self._mgr.AddPane(self.panelPlaylists, aui.AuiPaneInfo().Name('Playlists').Caption('Playlists').Left().CloseButton(True).MaximizeButton(False))
+        self._mgr.AddPane(self.plotNotebook, aui.AuiPaneInfo().Name('Plots').CenterPane().PaneBorder(False))
+        self._mgr.AddPane(self.panelCommands, aui.AuiPaneInfo().Name('Commands').Caption('Settings and commands').Right().CloseButton(True).MaximizeButton(False))
+        self._mgr.AddPane(self.panelProperties, aui.AuiPaneInfo().Name('Properties').Caption('Properties').Right().CloseButton(True).MaximizeButton(False))
+        self._mgr.AddPane(self.panelAssistant, aui.AuiPaneInfo().Name('Assistant').Caption('Assistant').Right().CloseButton(True).MaximizeButton(False))
+        self._mgr.AddPane(self.panelOutput, aui.AuiPaneInfo().Name('Output').Caption('Output').Bottom().CloseButton(True).MaximizeButton(False))
+        self._mgr.AddPane(self.panelResults, aui.AuiPaneInfo().Name('Results').Caption('Results').Bottom().CloseButton(True).MaximizeButton(False))
+        #self._mgr.AddPane(self.textCtrlCommandLine, aui.AuiPaneInfo().Name('CommandLine').CaptionVisible(False).Fixed().Bottom().Layer(2).CloseButton(False).MaximizeButton(False))
+        #self._mgr.AddPane(panelBottom, aui.AuiPaneInfo().Name("panelCommandLine").Bottom().Position(1).CloseButton(False).MaximizeButton(False))
+
+        # add the toolbars to the manager
+        self.toolbar=self.CreateToolBar()
+        self.toolbarNavigation=self.CreateToolBarNavigation()
+        self._mgr.AddPane(self.toolbar, aui.AuiPaneInfo().Name('toolbar').Caption('Toolbar').ToolbarPane().Top().Layer(1).Row(1).LeftDockable(False).RightDockable(False))
+        self._mgr.AddPane(self.toolbarNavigation, aui.AuiPaneInfo().Name('toolbarNavigation').Caption('Navigation').ToolbarPane().Top().Layer(1).Row(1).LeftDockable(False).RightDockable(False))
+        # "commit" all changes made to FrameManager
+        self._mgr.Update()
+        #create the menubar after the panes so that the default perspective
+        #is created with all panes open
+        self.CreateMenuBar()
+        self.statusbar = self.CreateStatusBar()
+        self._BindEvents()
+        #TODO: select item on startup (whatever item)
+        #self.listCtrlCommands.Select(0)
+        #self.OnListboxSelect(None)
+        name = self.config['perspectives']['active']
+        menu_item = self.GetPerspectiveMenuItem(name)
+        self.OnRestorePerspective(menu_item)
+        self.playlists = self.panelPlaylists.Playlists
+        #define the list of active drivers
+        self.drivers = []
+        for driver in self.config['drivers']:
+            if self.config['drivers'][driver]:
+                #get the corresponding filename and path
+                filename = ''.join([driver, '.py'])
+                path = lh.get_file_path(filename, ['drivers'])
+                #the driver is active for driver[1] == 1
+                if os.path.isfile(path):
+                    #driver files are located in the 'drivers' subfolder
+                    driver_name = ''.join(['drivers.', driver])
+                    module = __import__(driver_name)
+                    class_file = getattr(drivers, driver)
+                    for command in dir(class_file):
+                        if command.endswith('Driver'):
+                            self.drivers.append(getattr(class_file, command))
+        #import all active plugins and plotmanips
+        #the plotmanip_functions contains: {the name of the plotmanip: [method, class_object]}
+        plotmanip_functions = {}
+        #add 'general.ini' to self.configs (this is not a plugin and thus must be imported seperately)
+        ini_path = lh.get_file_path('general.ini', ['plugins'])
+        plugin_config = ConfigObj(ini_path)
+        #self.config.merge(plugin_config)
+        self.configs['general'] = plugin_config
+        #make sure we execute _plug_init() for every command line plugin we import
+        for plugin in self.config['plugins']:
+            if self.config['plugins'][plugin]:
+                filename = ''.join([plugin, '.py'])
+                path = lh.get_file_path(filename, ['plugins'])
+                if os.path.isfile(path):
+                    #get the corresponding filename and path
+                    plugin_name = ''.join(['plugins.', plugin])
+                    try:
+                        #import the module
+                        module = __import__(plugin_name)
+                        #prepare the ini file for inclusion
+                        ini_path = path.replace('.py', '.ini')
+                        #include ini file
+                        plugin_config = ConfigObj(ini_path)
+                        #self.config.merge(plugin_config)
+                        self.configs[plugin] = plugin_config
+                        #add to plugins
+                        commands = eval('dir(module.' + plugin+ '.' + plugin + 'Commands)')
+                        #keep only commands (ie names that start with 'do_')
+                        commands = [command for command in commands if command.startswith('do_')]
+                        if commands:
+                            self.plugins[plugin] = commands
+                        try:
+                            #initialize the plugin
+                            eval('module.' + plugin+ '.' + plugin + 'Commands._plug_init(self)')
+                        except AttributeError:
+                            pass
+                    except ImportError:
+                        pass
+        #initialize the commands tree
+        commands = dir(HookeFrame)
+        commands = [command for command in commands if command.startswith('do_')]
+        if commands:
+            self.plugins['general'] = commands
+        self.panelCommands.Initialize(self.plugins)
+        for command in dir(self):
+            if command.startswith('plotmanip_'):
+                plotmanip_functions[command] = [command, getattr(self, command)]
+        for name in self.config['plotmanipulators']['names']:
+            if self.config['plotmanipulators'].as_bool(name):
+                command_name = ''.join(['plotmanip_', name])
+                if command_name in plotmanip_functions:
+                    self.plotmanipulators.append(plotmanip_functions[command_name])
+        #load default list, if possible
+        self.do_loadlist(self.config['general']['list'])
+
+    def _BindEvents(self):
+        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
+        self.Bind(wx.EVT_SIZE, self.OnSize)
+        self.Bind(wx.EVT_CLOSE, self.OnClose)
+        # Show How To Use The Closing Panes Event
+        self.Bind(aui.EVT_AUI_PANE_CLOSE, self.OnPaneClose)
+        self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.OnNotebookPageClose)
+        #menu
+        self.Bind(wx.EVT_MENU, self.OnClose, id=wx.ID_EXIT)
+        self.Bind(wx.EVT_MENU, self.OnAbout, id=wx.ID_ABOUT)
+        #view
+        self.Bind(wx.EVT_MENU_RANGE, self.OnView, id=ID_ViewAssistant, id2=ID_ViewResults)
+        #perspectives
+        self.Bind(wx.EVT_MENU, self.OnDeletePerspective, id=ID_DeletePerspective)
+        self.Bind(wx.EVT_MENU, self.OnSavePerspective, id=ID_SavePerspective)
+        self.Bind(wx.EVT_MENU_RANGE, self.OnRestorePerspective, id=ID_FirstPerspective, id2=ID_FirstPerspective+1000)
+        #toolbar
+        self.Bind(wx.EVT_TOOL, self.OnExportImage, id=ID_ExportImage)
+        self.Bind(wx.EVT_TOOL, self.OnNext, id=ID_Next)
+        self.Bind(wx.EVT_TOOL, self.OnPrevious, id=ID_Previous)
+        #self.Bind(.EVT_AUITOOLBAR_TOOL_DROPDOWN, self.OnDropDownToolbarItem, id=ID_DropDownToolbarItem)
+        #dir control
+        treeCtrl = self.panelFolders.GetTreeCtrl()
+        #tree.Bind(wx.EVT_LEFT_UP, self.OnDirCtrl1LeftUp)
+        #tree.Bind(wx.EVT_LEFT_DOWN, self.OnGenericDirCtrl1LeftDown)
+        treeCtrl.Bind(wx.EVT_LEFT_DCLICK, self.OnDirCtrlLeftDclick)
+        #playlist tree
+        self.panelPlaylists.PlaylistsTree.Bind(wx.EVT_LEFT_DOWN, self.OnPlaylistsLeftDown)
+        self.panelPlaylists.PlaylistsTree.Bind(wx.EVT_LEFT_DCLICK, self.OnPlaylistsLeftDclick)
+        #commands tree
+        self.panelCommands.ExecuteButton.Bind(wx.EVT_BUTTON, self.OnExecute)
+        self.panelCommands.CommandsTree.Bind(wx.EVT_LEFT_DOWN, self.OnTreeCtrlCommandsLeftDown)
+        #property editor
+        self.panelProperties.pg.Bind(wxpg.EVT_PG_CHANGED, self.OnPropGridChanged)
+        self.panelProperties.pg.Bind(wxpg.EVT_PG_SELECTED, self.OnPropGridSelect)
+        #results panel
+        self.panelResults.results_list.OnCheckItem = self.OnResultsCheck
+
+    def _GetActiveCurveIndex(self):
+        playlist = self.GetActivePlaylist()
+        #get the selected item from the tree
+        selected_item = self.panelPlaylists.PlaylistsTree.GetSelection()
+        #test if a playlist or a curve was double-clicked
+        if self.panelPlaylists.PlaylistsTree.ItemHasChildren(selected_item):
+            return -1
+        else:
+            count = 0
+            selected_item = self.panelPlaylists.PlaylistsTree.GetPrevSibling(selected_item)
+            while selected_item.IsOk():
+                count += 1
+                selected_item = self.panelPlaylists.PlaylistsTree.GetPrevSibling(selected_item)
+            return count
+
+    def _GetActivePlaylistName(self):
+        #get the selected item from the tree
+        selected_item = self.panelPlaylists.PlaylistsTree.GetSelection()
+        #test if a playlist or a curve was double-clicked
+        if self.panelPlaylists.PlaylistsTree.ItemHasChildren(selected_item):
+            playlist_item = selected_item
+        else:
+            #get the name of the playlist
+            playlist_item = self.panelPlaylists.PlaylistsTree.GetItemParent(selected_item)
+        #now we have a playlist
+        return self.panelPlaylists.PlaylistsTree.GetItemText(playlist_item)
+
+    def _GetPlaylistTab(self, name):
+        for index, page in enumerate(self.plotNotebook._tabs._pages):
+            if page.caption == name:
+                return index
+        return -1
+
+    def _GetUniquePlaylistName(self, name):
+        playlist_name = name
+        count = 1
+        while playlist_name in self.playlists:
+            playlist_name = ''.join([name, str(count)])
+            count += 1
+        return playlist_name
+
+    def _SavePerspectiveToFile(self, name, perspective):
+        filename = ''.join([name, '.txt'])
+        filename = lh.get_file_path(filename, ['perspectives'])
+        perspectivesFile = open(filename, 'w')
+        perspectivesFile.write(perspective)
+        perspectivesFile.close()
+
+    def AddPlaylist(self, playlist=None, name='Untitled'):
+        #TODO: change cursor or progressbar (maybe in statusbar)
+        #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
+        if playlist and playlist.count > 0:
+            playlist.name = self._GetUniquePlaylistName(name)
+            playlist.reset()
+            self.AddToPlaylists(playlist)
+
+    def AddPlaylistFromFiles(self, files=[], name='Untitled'):
+        #TODO: change cursor or progressbar (maybe in statusbar)
+        #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
+        if files:
+            playlist = Playlist.Playlist(self.drivers)
+            for item in files:
+                playlist.add_curve(item)
+        if playlist.count > 0:
+            playlist.name = self._GetUniquePlaylistName(name)
+            playlist.reset()
+            self.AddToPlaylists(playlist)
+
+    def AddToPlaylists(self, playlist):
+        if playlist.has_curves:
+            #setup the playlist in the Playlist tree
+            tree_root = self.panelPlaylists.PlaylistsTree.GetRootItem()
+            playlist_root = self.panelPlaylists.PlaylistsTree.AppendItem(tree_root, playlist.name, 0)
+            #add all curves to the Playlist tree
+            curves = {}
+            for index, curve in enumerate(playlist.curves):
+                ##remove the extension from the name of the curve
+                ##TODO: optional?
+                #item_text, extension = os.path.splitext(curve.name)
+                #curve_ID = self.panelPlaylists.PlaylistsTree.AppendItem(playlist_root, item_text, 1)
+                curve_ID = self.panelPlaylists.PlaylistsTree.AppendItem(playlist_root, curve.name, 1)
+                if index == playlist.index:
+                    self.panelPlaylists.PlaylistsTree.SelectItem(curve_ID)
+            playlist.reset()
+            #create the plot tab and add playlist to the dictionary
+            plotPanel = wxmpl.PlotPanel(self, ID_FirstPlot + len(self.playlists))
+            notebook_tab = self.plotNotebook.AddPage(plotPanel, playlist.name, True)
+            tab_index = self.plotNotebook.GetSelection()
+            figure = plotPanel.get_figure()
+            self.playlists[playlist.name] = [playlist, figure]
+            self.panelPlaylists.PlaylistsTree.Expand(playlist_root)
+            self.statusbar.SetStatusText(playlist.get_status_string(), 0)
+            self.UpdatePlot()
+
+    def AppendToOutput(self, text):
+        self.panelOutput.AppendText(''.join([text, '\n']))
+
+    def CreateApplicationIcon(self):
+        iconFile = 'resources' + os.sep + 'microscope.ico'
+        icon = wx.Icon(iconFile, wx.BITMAP_TYPE_ICO)
+        self.SetIcon(icon)
+
+    def CreateCommandLine(self):
+        return wx.TextCtrl(self, -1, '', style=wx.NO_BORDER|wx.EXPAND)
+
+    def CreatePanelAssistant(self):
+        panel = wx.TextCtrl(self, -1, '', wx.Point(0, 0), wx.Size(150, 90), wx.NO_BORDER|wx.TE_MULTILINE)
+        panel.SetEditable(False)
+        return panel
+
+    def CreatePanelCommands(self):
+        return hookecommands.Commands(self)
+
+    def CreatePanelFolders(self):
+        #set file filters
+        filters = self.config['folders']['filters']
+        index = self.config['folders'].as_int('filterindex')
+        #set initial directory
+        folder = self.config['general']['workdir']
+        return wx.GenericDirCtrl(self, -1, dir=folder, size=(200, 250), style=wx.DIRCTRL_SHOW_FILTERS, filter=filters, defaultFilter=index)
+
+    def CreatePanelOutput(self):
+        return wx.TextCtrl(self, -1, '', wx.Point(0, 0), wx.Size(150, 90), wx.NO_BORDER|wx.TE_MULTILINE)
+
+    def CreatePanelPlaylists(self):
+        return hookeplaylist.Playlists(self)
+
+    def CreatePanelProperties(self):
+        return hookepropertyeditor.PropertyEditor(self)
+
+    def CreatePanelResults(self):
+        return hookeresults.Results(self)
+
+    def CreatePanelWelcome(self):
+        ctrl = wx.html.HtmlWindow(self, -1, wx.DefaultPosition, wx.Size(400, 300))
+        introStr = '<h1>Welcome to Hooke</h1>' + \
+                 '<h3>Features</h3>' + \
+                 '<ul>' + \
+                 '<li>View, annotate, measure force curves</li>' + \
+                 '<li>Worm-like chain fit of force peaks</li>' + \
+                 '<li>Automatic convolution-based filtering of empty curves</li>' + \
+                 '<li>Automatic fit and measurement of multiple force peaks</li>' + \
+                 '<li>Handles force-clamp force experiments (experimental)</li>' + \
+                 '<li>It is extensible by users by means of plugins and drivers</li>' + \
+                 '</ul>' + \
+                 '<p>See the <a href="/p/hooke/wiki/DocumentationIndex">DocumentationIndex</a> for more information</p>'
+        ctrl.SetPage(introStr)
+        return ctrl
+
+    def CreateMenuBar(self):
+        menu_bar = wx.MenuBar()
+        #file
+        file_menu = wx.Menu()
+        file_menu.Append(wx.ID_OPEN, '&Open playlist\tCtrl-O')
+        file_menu.Append(wx.ID_SAVE, 'Save playlist\tCtrl-S')
+        file_menu.AppendSeparator()
+        file_menu.Append(wx.ID_EXIT, 'Exit\tCtrl-Q')
+        #edit
+        edit_menu = wx.Menu()
+        edit_menu.Append(ID_ExportText, 'Export text...')
+        edit_menu.Append(ID_ExportImage, 'Export image...')
+        edit_menu.AppendSeparator();
+        edit_menu.Append(ID_Config, 'Preferences')
+        #view
+        view_menu = wx.Menu()
+        view_menu.AppendCheckItem(ID_ViewFolders, 'Folders\tF5')
+        view_menu.AppendCheckItem(ID_ViewPlaylists, 'Playlists\tF6')
+        view_menu.AppendCheckItem(ID_ViewCommands, 'Commands\tF7')
+        view_menu.AppendCheckItem(ID_ViewProperties, 'Properties\tF8')
+        view_menu.AppendCheckItem(ID_ViewAssistant, 'Assistant\tF9')
+        view_menu.AppendCheckItem(ID_ViewResults, 'Results\tF10')
+        view_menu.AppendCheckItem(ID_ViewOutput, 'Output\tF11')
+        #perspectives
+        self._perspectives_menu = self.CreatePerspectivesMenu()
+        #help
+        help_menu = wx.Menu()
+        help_menu.Append(wx.ID_ABOUT, 'About Hooke')
+        #put it all together
+        menu_bar.Append(file_menu, 'File')
+        menu_bar.Append(edit_menu, 'Edit')
+        menu_bar.Append(view_menu, 'View')
+        menu_bar.Append(self._perspectives_menu, "Perspectives")
+        menu_bar.Append(help_menu, 'Help')
+
+        self.SetMenuBar(menu_bar)
+
+    def CreateNotebook(self):
+        # create the notebook off-window to avoid flicker
+        client_size = self.GetClientSize()
+        ctrl = aui.AuiNotebook(self, -1, wx.Point(client_size.x, client_size.y), wx.Size(430, 200), self._notebook_style)
+        arts = [aui.AuiDefaultTabArt, aui.AuiSimpleTabArt, aui.VC71TabArt, aui.FF2TabArt, aui.VC8TabArt, aui.ChromeTabArt]
+        art = arts[self._notebook_theme]()
+        ctrl.SetArtProvider(art)
+        #uncomment if we find a nice icon
+        #page_bmp = wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, wx.Size(16, 16))
+        ctrl.AddPage(self.CreatePanelWelcome(), "Welcome", False)
+        return ctrl
+
+    def CreatePerspectivesMenu(self):
+        menu = wx.Menu()
+        menu.Append(ID_SavePerspective, "Save Perspective")
+        menu.Append(ID_DeletePerspective, "Delete Perspective")
+        menu.AppendSeparator()
+        #add perspectives to menubar and _perspectives
+        perspectivesDirectory = os.path.join(lh.hookeDir, 'perspectives')
+        if os.path.isdir(perspectivesDirectory):
+            perspectiveFileNames = os.listdir(perspectivesDirectory)
+            for perspectiveFilename in perspectiveFileNames:
+                filename = lh.get_file_path(perspectiveFilename, ['perspectives'])
+                if os.path.isfile(filename):
+                    perspectiveFile = open(filename, 'rU')
+                    perspective = perspectiveFile.readline()
+                    perspectiveFile.close()
+                    if perspective != '':
+                        name, extension = os.path.splitext(perspectiveFilename)
+                        if extension == '.txt':
+                            menuItem = menu.AppendRadioItem(ID_FirstPerspective + len(self._perspectives), name)
+                            self._perspectives[name] = [len(self._perspectives), perspective]
+                            if self.config['perspectives']['active'] == name:
+                                menuItem.Check()
+        #in case there are no perspectives
+        if not self._perspectives:
+            perspective = self._mgr.SavePerspective()
+            self.config['perspectives']['default'] = 'Default'
+            self._perspectives['Default'] = [0, perspective]
+            menuItem = menu.AppendRadioItem(ID_FirstPerspective, 'Default')
+            menuItem.Check()
+            self._SavePerspectiveToFile('Default', perspective)
+        return menu
+
+    def CreateStatusbar(self):
+        statusbar = self.CreateStatusBar(2, wx.ST_SIZEGRIP)
+        statusbar.SetStatusWidths([-2, -3])
+        statusbar.SetStatusText('Ready', 0)
+        welcomeString=u'Welcome to Hooke (version '+__version__+', '+__release_name__+')!'
+        statusbar.SetStatusText(welcomeString, 1)
+        return statusbar
+
+    def CreateToolBar(self):
+        toolbar = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize, wx.TB_FLAT | wx.TB_NODIVIDER)
+        toolbar.SetToolBitmapSize(wx.Size(16,16))
+        toolbar_bmp1 = wx.ArtProvider_GetBitmap(wx.ART_QUESTION, wx.ART_OTHER, wx.Size(16, 16))
+        toolbar_bmpOpen = wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN, wx.ART_OTHER, wx.Size(16, 16))
+        toolbar_bmpSave = wx.ArtProvider_GetBitmap(wx.ART_FILE_SAVE, wx.ART_OTHER, wx.Size(16, 16))
+        toolbar_bmpExportText = wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, wx.Size(16, 16))
+        toolbar_bmpExportImage = wx.ArtProvider_GetBitmap(wx.ART_MISSING_IMAGE, wx.ART_OTHER, wx.Size(16, 16))
+        toolbar.AddLabelTool(101, 'Open', toolbar_bmpOpen)
+        toolbar.AddLabelTool(102, 'Save', toolbar_bmpSave)
+        toolbar.AddSeparator()
+        toolbar.AddLabelTool(ID_ExportText, 'Export text...', toolbar_bmpExportText)
+        toolbar.AddLabelTool(ID_ExportImage, 'Export image...', toolbar_bmpExportImage)
+        toolbar.Realize()
+        return toolbar
+
+    def CreateToolBarNavigation(self):
+        toolbar = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize, wx.TB_FLAT | wx.TB_NODIVIDER)
+        toolbar.SetToolBitmapSize(wx.Size(16,16))
+        toolbar_bmpBack = wx.ArtProvider_GetBitmap(wx.ART_GO_BACK, wx.ART_OTHER, wx.Size(16, 16))
+        toolbar_bmpForward = wx.ArtProvider_GetBitmap(wx.ART_GO_FORWARD, wx.ART_OTHER, wx.Size(16, 16))
+        toolbar.AddLabelTool(ID_Previous, 'Previous', toolbar_bmpBack, shortHelp='Previous curve')
+        toolbar.AddLabelTool(ID_Next, 'Next', toolbar_bmpForward, shortHelp='Next curve')
+        toolbar.Realize()
+        return toolbar
+
+    def DeleteFromPlaylists(self, name):
+        if name in self.playlists:
+            del self.playlists[name]
+        tree_root = self.panelPlaylists.PlaylistsTree.GetRootItem()
+        item, cookie = self.panelPlaylists.PlaylistsTree.GetFirstChild(tree_root)
+        while item.IsOk():
+            playlist_name = self.panelPlaylists.PlaylistsTree.GetItemText(item)
+            if playlist_name == name:
+                try:
+                    self.panelPlaylists.PlaylistsTree.Delete(item)
+                except:
+                    pass
+            item = self.panelPlaylists.PlaylistsTree.GetNextSibling(item)
+        self.OnPlaylistsLeftDclick(None)
+
+    def DeletePlotPage(self, name):
+        index = self._GetPlaylistTab(name)
+        plot = self.playlists[name][1]
+        plot = None
+        self.plotNotebook.RemovePage(index)
+        self.DeleteFromPlaylists(name)
+
+    def GetActiveCurve(self):
+        playlist = self.GetActivePlaylist()
+        if playlist is not None:
+            return playlist.get_active_curve()
+        return None
+
+    def GetActivePlaylist(self):
+        playlist_name = self._GetActivePlaylistName()
+        if playlist_name in self.playlists:
+            return self.playlists[playlist_name][0]
+        return None
+
+    def GetActivePlot(self):
+        curve = self.GetActiveCurve()
+        if curve is not None:
+            return curve.plots[0]
+        return None
+
+    def GetDockArt(self):
+        return self._mgr.GetArtProvider()
+
+    def GetBoolFromConfig(self, *args):
+        if len(args) == 2:
+            plugin = args[0]
+            section = args[0]
+            key = args[1]
+        elif len(args) == 3:
+            plugin = args[0]
+            section = args[1]
+            key = args[2]
+        if self.configs.has_key(plugin):
+            config = self.configs[plugin]
+            return config[section][key].as_bool('value')
+        return None
+
+    def GetFloatFromConfig(self, *args):
+        if len(args) == 2:
+            plugin = args[0]
+            section = args[0]
+            key = args[1]
+        elif len(args) == 3:
+            plugin = args[0]
+            section = args[1]
+            key = args[2]
+        if self.configs.has_key(plugin):
+            config = self.configs[plugin]
+            return config[section][key].as_float('value')
+        return None
+
+    def GetIntFromConfig(self, *args):
+        if len(args) == 2:
+            plugin = args[0]
+            section = args[0]
+            key = args[1]
+        elif len(args) == 3:
+            plugin = args[0]
+            section = args[1]
+            key = args[2]
+        if self.configs.has_key(plugin):
+            config = self.configs[plugin]
+            return config[section][key].as_int('value')
+        return None
+
+    def GetStringFromConfig(self, *args):
+        if len(args) == 2:
+            plugin = args[0]
+            section = args[0]
+            key = args[1]
+        elif len(args) == 3:
+            plugin = args[0]
+            section = args[1]
+            key = args[2]
+        if self.configs.has_key(plugin):
+            config = self.configs[plugin]
+            return config[section][key]['value']
+        return None
+
+    def GetPerspectiveMenuItem(self, name):
+        index = self._perspectives[name][0]
+        perspective_Id = ID_FirstPerspective + index
+        menu_item = self.MenuBar.FindItemById(perspective_Id)
+        return menu_item
+
+    def HasPlotmanipulator(self, name):
+        '''
+        returns True if the plotmanipulator 'name' is loaded, False otherwise
+        '''
+        for plotmanipulator in self.plotmanipulators:
+            if plotmanipulator[0] == name:
+                return True
+        return False
+
+    def OnAbout(self, event):
+        msg = 'Hooke\n\n'+\
+            'A free, open source data analysis platform\n'+\
+            '(c) 2006-2008 Massimo Sandal\n\n'+\
+            '(c) 2009 Dr. Rolf Schmidt\n\n'+\
+            'Released under the GNU GPL v2'
+        dialog = wx.MessageDialog(self, msg, "About Hooke", wx.OK | wx.ICON_INFORMATION)
+        dialog.ShowModal()
+        dialog.Destroy()
+
+    def OnClose(self, event):
+        #apply changes
+        self.config['main']['height'] = str(self.GetSize().GetHeight())
+        self.config['main']['left'] = str(self.GetPosition()[0])
+        self.config['main']['top'] = str(self.GetPosition()[1])
+        self.config['main']['width'] = str(self.GetSize().GetWidth())
+        # Writing the configuration file to 'hooke.ini'
+        self.config.write()
+        self._mgr.UnInit()
+        del self._mgr
+        self.Destroy()
+
+    def OnDeletePerspective(self, event):
+        pass
+
+    def OnDirCtrlLeftDclick(self, event):
+        file_path = self.panelFolders.GetPath()
+        if os.path.isfile(file_path):
+            if file_path.endswith('.hkp'):
+                self.do_loadlist(file_path)
+            else:
+                pass
+        event.Skip()
+
+    def OnEraseBackground(self, event):
+        event.Skip()
+
+    def OnExecute(self, event):
+        item = self.panelCommands.CommandsTree.GetSelection()
+        if item.IsOk():
+            if self.panelCommands.CommandsTree.ItemHasChildren(item):
+                pass
+            else:
+                #get the plugin
+                parent = self.panelCommands.CommandsTree.GetItemParent(item)
+            if not self.panelCommands.CommandsTree.ItemHasChildren(item):
+                parent_text = self.panelCommands.CommandsTree.GetItemText(parent)
+                item_text = self.panelCommands.CommandsTree.GetItemText(item)
+                if item_text in ['genlist', 'loadlist', 'savelist']:
+                    property_values = self.panelProperties.GetPropertyValues()
+                    arg_str = ''
+                    for item in property_values:
+                        arg_str = ''.join([arg_str, item, '=r"', str(property_values[item]), '", '])
+                    command = ''.join(['self.do_', item_text, '(', arg_str, ')'])
+                else:
+                    command = ''.join(['self.do_', item_text, '()'])
+                exec(command)
+        pass
+
+    def OnExit(self, event):
+        self.Close()
+
+    def OnExportImage(self, event):
+        pass
+
+    def OnNext(self, event):
+        '''
+        NEXT
+        Go to the next curve in the playlist.
+        If we are at the last curve, we come back to the first.
+        -----
+        Syntax: next, n
+        '''
+        selected_item = self.panelPlaylists.PlaylistsTree.GetSelection()
+        if self.panelPlaylists.PlaylistsTree.ItemHasChildren(selected_item):
+            #GetFirstChild returns a tuple
+            #we only need the first element
+            next_item = self.panelPlaylists.PlaylistsTree.GetFirstChild(selected_item)[0]
+        else:
+            next_item = self.panelPlaylists.PlaylistsTree.GetNextSibling(selected_item)
+            if not next_item.IsOk():
+                parent_item = self.panelPlaylists.PlaylistsTree.GetItemParent(selected_item)
+                #GetFirstChild returns a tuple
+                #we only need the first element
+                next_item = self.panelPlaylists.PlaylistsTree.GetFirstChild(parent_item)[0]
+        self.panelPlaylists.PlaylistsTree.SelectItem(next_item, True)
+        playlist = self.playlists[self._GetActivePlaylistName()][0]
+        if playlist.count > 1:
+            playlist.next()
+            self.statusbar.SetStatusText(playlist.get_status_string(), 0)
+            self.UpdatePlot()
+
+    def OnNotebookPageClose(self, event):
+        ctrl = event.GetEventObject()
+        playlist_name = ctrl.GetPageText(ctrl._curpage)
+        self.DeleteFromPlaylists(playlist_name)
+
+    def OnPaneClose(self, event):
+        event.Skip()
+
+    def OnPlaylistsLeftDclick(self, event):
+        playlist_name = self._GetActivePlaylistName()
+        #if that playlist already exists
+        #we check if it is the active playlist (ie selected in panelPlaylists)
+        #and switch to it if necessary
+        if playlist_name in self.playlists:
+            index = self.plotNotebook.GetSelection()
+            current_playlist = self.plotNotebook.GetPageText(index)
+            #new_playlist = self.playlists[playlist_name][0]
+            #if current_playlist != new_playlist:
+            if current_playlist != playlist_name:
+                index = self._GetPlaylistTab(playlist_name)
+                self.plotNotebook.SetSelection(index)
+            #if a curve was double-clicked
+            item = self.panelPlaylists.PlaylistsTree.GetSelection()
+            #TODO: fix with get_active_curve
+            if not self.panelPlaylists.PlaylistsTree.ItemHasChildren(item):
+                index = self._GetActiveCurveIndex()
+            else:
+                index = 0
+            if index >= 0:
+                playlist = self.playlists[playlist_name][0]
+                playlist.index = index
+                self.statusbar.SetStatusText(playlist.get_status_string(), 0)
+                self.UpdatePlot()
+        #if you uncomment the following line, the tree will collapse/expand as well
+        #event.Skip()
+
+    def OnPlaylistsLeftDown(self, event):
+        hit_item, hit_flags = self.panelPlaylists.PlaylistsTree.HitTest(event.GetPosition())
+        if (hit_flags & wx.TREE_HITTEST_ONITEM) != 0:
+            #self.SetFocus()
+            self.panelPlaylists.PlaylistsTree.SelectItem(hit_item)
+            playlist_name = self._GetActivePlaylistName()
+            playlist = self.playlists[playlist_name][0]
+            #if a curve was clicked
+            item = self.panelPlaylists.PlaylistsTree.GetSelection()
+            if not self.panelPlaylists.PlaylistsTree.ItemHasChildren(item):
+                #TODO: fix with get_active_curve
+                index = self._GetActiveCurveIndex()
+                if index >= 0:
+                    #playlist = self.playlists[playlist_name][0]
+                    playlist.index = index
+                    #self.playlists[playlist_name][0].index = index
+            #else:
+                ##self.playlists[playlist_name][0].index = 0
+                #playlist.index = index
+            self.playlists[playlist_name][0] = playlist
+        event.Skip()
+
+    def OnPrevious(self, event):
+        '''
+        PREVIOUS
+        Go to the previous curve in the playlist.
+        If we are at the first curve, we jump to the last.
+        -------
+        Syntax: previous, p
+        '''
+        #playlist = self.playlists[self._GetActivePlaylistName()][0]
+        #select the previous curve and tell the user if we wrapped around
+        #self.AppendToOutput(playlist.previous())
+        selected_item = self.panelPlaylists.PlaylistsTree.GetSelection()
+        if self.panelPlaylists.PlaylistsTree.ItemHasChildren(selected_item):
+            previous_item = self.panelPlaylists.PlaylistsTree.GetLastChild(selected_item)
+        else:
+            previous_item = self.panelPlaylists.PlaylistsTree.GetPrevSibling(selected_item)
+            if not previous_item.IsOk():
+                parent_item = self.panelPlaylists.PlaylistsTree.GetItemParent(selected_item)
+                previous_item = self.panelPlaylists.PlaylistsTree.GetLastChild(parent_item)
+        self.panelPlaylists.PlaylistsTree.SelectItem(previous_item, True)
+        playlist = self.playlists[self._GetActivePlaylistName()][0]
+        if playlist.count > 1:
+            playlist.previous()
+            self.statusbar.SetStatusText(playlist.get_status_string(), 0)
+            self.UpdatePlot()
+
+    def OnPropGridChanged (self, event):
+        prop = event.GetProperty()
+        if prop:
+            item_section = self.panelProperties.SelectedTreeItem
+            item_plugin = self.panelCommands.CommandsTree.GetItemParent(item_section)
+            plugin = self.panelCommands.CommandsTree.GetItemText(item_plugin)
+            config = self.configs[plugin]
+            property_section = self.panelCommands.CommandsTree.GetItemText(item_section)
+            property_key = prop.GetName()
+            property_value = prop.GetValue()
+            config[property_section][property_key]['value'] = property_value
+
+    def OnPropGridSelect(self, event):
+        pass
+
+    def OnRestorePerspective(self, event):
+        name = self.MenuBar.FindItemById(event.GetId()).GetLabel()
+        self._mgr.LoadPerspective(self._perspectives[name][1])
+        self.config['perspectives']['active'] = name
+        self._mgr.Update()
+        all_panes = self._mgr.GetAllPanes()
+        for pane in all_panes:
+            if not pane.name.startswith('toolbar'):
+                if pane.name == 'Assistant':
+                    self.MenuBar.FindItemById(ID_ViewAssistant).Check(pane.window.IsShown())
+                if pane.name == 'Folders':
+                    self.MenuBar.FindItemById(ID_ViewFolders).Check(pane.window.IsShown())
+                if pane.name == 'Playlists':
+                    self.MenuBar.FindItemById(ID_ViewPlaylists).Check(pane.window.IsShown())
+                if pane.name == 'Commands':
+                    self.MenuBar.FindItemById(ID_ViewCommands).Check(pane.window.IsShown())
+                if pane.name == 'Properties':
+                    self.MenuBar.FindItemById(ID_ViewProperties).Check(pane.window.IsShown())
+                if pane.name == 'Output':
+                    self.MenuBar.FindItemById(ID_ViewOutput).Check(pane.window.IsShown())
+                if pane.name == 'Results':
+                    self.MenuBar.FindItemById(ID_ViewResults).Check(pane.window.IsShown())
+
+    def OnResultsCheck(self, index, flag):
+        curve = self.GetActiveCurve()
+        result = curve.data['results'][index]['visible'] = flag
+        self.UpdatePlot()
+
+    def OnSavePerspective(self, event):
+        def nameExists(name):
+            for item in self._perspectives_menu.GetMenuItems():
+                if item.GetText() == name:
+                    return True
+            return False
+
+        done = False
+        while not done:
+            dialog = wx.TextEntryDialog(self, 'Enter a name for the new perspective:', 'Save perspective')
+            dialog.SetValue('New perspective')
+            if dialog.ShowModal() != wx.ID_OK:
+                return
+            else:
+                name = dialog.GetValue()
+
+            if nameExists(name):
+                dialogConfirm = wx.MessageDialog(self, 'A file with this name already exists.\n\nDo you want to replace it?', 'Confirm', wx.YES_NO|wx.ICON_QUESTION|wx.CENTER)
+                if dialogConfirm.ShowModal() == wx.ID_YES:
+                    done = True
+            else:
+                done = True
+
+        perspective = self._mgr.SavePerspective()
+
+        if nameExists(name):
+            #check the corresponding menu item
+            menuItem = self.GetPerspectiveMenuItem(name)
+            #replace the perspectiveStr in _pespectives
+            index = self._perspectives[name][0]
+            self._perspectives[name] = [index, perspective]
+        else:
+            #simply add the new perspective to _perspectives
+            index = len(self._perspectives)
+            self._perspectives[name] = [len(self._perspectives), perspective]
+            menuItem = self._perspectives_menu.AppendRadioItem(ID_FirstPerspective + len(self._perspectives), name)
+
+        menuItem.Check()
+        self._SavePerspectiveToFile(name, perspective)
+        #uncheck all perspective menu items
+        #as these are radio items, one item has to be checked at all times
+        #the line 'menuItem.Check()' above actually checks a second item
+        #but does not toggle
+        #so we need to uncheck all other items afterwards
+        #weirdly enough, menuitem.Toggle() doesn't do this properly either
+        for item in self._perspectives_menu.GetMenuItems():
+            if item.IsCheckable():
+                if item.GetLabel() != name:
+                    item.Check(False)
+
+    def OnView(self, event):
+        menu_id = event.GetId()
+        menu_item = self.MenuBar.FindItemById(menu_id)
+        menu_label = menu_item.GetLabel()
+
+        pane = self._mgr.GetPane(menu_label)
+        pane.Show(not pane.IsShown())
+        #if we don't do the following, the Folders pane does not resize properly on hide/show
+        if pane.caption == 'Folders' and pane.IsShown() and pane.IsDocked():
+            #folders_size = pane.GetSize()
+            self.panelFolders.Fit()
+        self._mgr.Update()
+
+    def OnSize(self, event):
+        event.Skip()
+
+    def OnTreeCtrlCommandsLeftDown(self, event):
+        hit_item, hit_flags = self.panelCommands.CommandsTree.HitTest(event.GetPosition())
+        if (hit_flags & wx.TREE_HITTEST_ONITEM) != 0:
+            self.panelCommands.CommandsTree.SelectItem(hit_item)
+            self.panelProperties.SelectedTreeItem = hit_item
+            #if a command was clicked
+            properties = []
+            if not self.panelCommands.CommandsTree.ItemHasChildren(hit_item):
+                item_plugin = self.panelCommands.CommandsTree.GetItemParent(hit_item)
+                plugin = self.panelCommands.CommandsTree.GetItemText(item_plugin)
+                if self.configs.has_key(plugin):
+                    #config = self.panelCommands.CommandsTree.GetPyData(item_plugin)
+                    config = self.configs[plugin]
+                    section = self.panelCommands.CommandsTree.GetItemText(hit_item)
+                    #display docstring in help window
+                    doc_string = eval('self.do_' + section + '.__doc__')
+                    if section in config:
+                        for option in config[section]:
+                            properties.append([option, config[section][option]])
+            else:
+                module = self.panelCommands.CommandsTree.GetItemText(hit_item)
+                if module != 'general':
+                    doc_string = eval('plugins.' + module + '.' + module + 'Commands.__doc__')
+                else:
+                    doc_string = 'The module "general" contains Hooke core functionality'
+            if doc_string is not None:
+                self.panelAssistant.ChangeValue(doc_string)
+            hookepropertyeditor.PropertyEditor.Initialize(self.panelProperties, properties)
+        event.Skip()
+
+    def UpdatePlaylists(self):
+        #setup the playlist in the Playlist tree
+        tree_root = self.panelPlaylists.PlaylistsTree.GetRootItem()
+        playlist_root = self.panelPlaylists.PlaylistsTree.AppendItem(tree_root, playlist.name, 0)
+        #add all curves to the Playlist tree
+        curves = {}
+        for index, curve in enumerate(playlist.curves):
+            ##remove the extension from the name of the curve
+            ##TODO: optional?
+            #item_text, extension = os.path.splitext(curve.name)
+            #curve_ID = self.panelPlaylists.PlaylistsTree.AppendItem(playlist_root, item_text, 1)
+            curve_ID = self.panelPlaylists.PlaylistsTree.AppendItem(playlist_root, curve.name, 1)
+            if index == playlist.index:
+                self.panelPlaylists.PlaylistsTree.SelectItem(curve_ID)
+        #create the plot tab and add playlist to the dictionary
+        plotPanel = wxmpl.PlotPanel(self, ID_FirstPlot + len(self.playlists))
+        notebook_tab = self.plotNotebook.AddPage(plotPanel, playlist.name, True)
+        #tab_index = self.plotNotebook.GetSelection()
+        figure = plotPanel.get_figure()
+        #self.playlists[playlist.name] = [playlist, tab_index, figure]
+        self.playlists[playlist.name] = [playlist, figure]
+        self.panelPlaylists.PlaylistsTree.Expand(playlist_root)
+        self.statusbar.SetStatusText(playlist.get_status_string(), 0)
+        self.UpdatePlot()
+
+#HELPER FUNCTIONS
+#Everything sending an event should be here
+    def _measure_N_points(self, N, whatset=1):
+        '''
+        general helper function for N-points measures
+        '''
+        wx.PostEvent(self.frame,self.list_of_events['measure_points'](num_of_points=N, set=whatset))
+        while 1:
+            try:
+                points=self.frame.events_from_gui.get()
+                break
+            except Empty:
+                pass
+        return points
+
+    def _clickize(self, xvector, yvector, index):
+        '''
+        returns a ClickedPoint() object from an index and vectors of x, y coordinates
+        '''
+        point = lh.ClickedPoint()
+        point.index = index
+        point.absolute_coords = xvector[index], yvector[index]
+        point.find_graph_coords(xvector, yvector)
+        return point
+
+#PLAYLIST INTERACTION COMMANDS
+#-------------------------------
+    def do_genlist(self, folder=lh.hookeDir, filemask='*.*'):
+        '''
+        GENLIST
+        Generates a file playlist.
+        Note it doesn't *save* it: see savelist for this.
+
+        If [input files] is a directory, it will use all files in the directory for playlist.
+        So:
+        genlist dir
+        genlist dir/
+        genlist dir/*.*
+
+        are all equivalent syntax.
+        ------------
+        Syntax: genlist [input files]
+        '''
+        #args list is: input folder, file mask
+        if os.path.isdir(folder):
+            path = os.path.join(folder, filemask)
+            #expanding correctly the input list with the glob module :)
+            files = glob.glob(path)
+            files.sort()
+            #TODO: change cursor or progressbar (maybe in statusbar)
+            #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
+            playlist = playlist.Playlist(self.drivers)
+            for item in files:
+                curve = playlist.add_curve(item)
+                plot = copy.deepcopy(curve.plots[0])
+                #add the 'raw' data
+                curve.add_data('raw', plot.vectors[0][0], plot.vectors[0][1], color=plot.colors[0], style='plot')
+                curve.add_data('raw', plot.vectors[1][0], plot.vectors[1][1], color=plot.colors[1], style='plot')
+                #apply all active plotmanipulators and add the 'manipulated' data
+                for plotmanipulator in self.plotmanipulators:
+                    plot = plotmanipulator[1](plot, curve)
+                    curve.set_data('manipulated', plot.vectors[0][0], plot.vectors[0][1], color=plot.colors[0], style='plot')
+                    curve.add_data('manipulated', plot.vectors[1][0], plot.vectors[1][1], color=plot.colors[1], style='plot')
+            if playlist.count > 0:
+                playlist.name = self._GetUniquePlaylistName(os.path.basename(folder))
+                playlist.reset()
+                self.AddToPlaylists(playlist)
+            self.AppendToOutput(playlist.get_status_string())
+        else:
+            self.AppendToOutput(''.join(['Cannot find folder ', folder]))
+
+    def do_loadlist(self, filename):
+        '''
+        LOADLIST
+        Loads a file playlist
+        -----------
+        Syntax: loadlist [playlist file]
+        '''
+        #TODO: check for duplicate playlists, ask the user for a unique name
+        #if self.playlist_name in self.playlists:
+
+        #add hkp extension if necessary
+        if not filename.endswith('.hkp'):
+            filename = ''.join([filename, '.hkp'])
+        #prefix with 'hookeDir' if just a filename or a relative path
+        filename = lh.get_file_path(filename)
+        if os.path.isfile(filename):
+            #TODO: change cursor
+            #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
+            playlist_new = playlist.Playlist(self.drivers)
+            playlist_new.load(filename)
+            if playlist_new.count > 0:
+                for curve in playlist_new.curves:
+                    plot = copy.deepcopy(curve.plots[0])
+                    for plotmanip in self.plotmanipulators:
+                        #to_plot = plotmanip[1](to_plot, curve)
+                        plot = plotmanip[1](plot, curve)
+                        curve.set_data('manipulated', plot.vectors[0][0], plot.vectors[0][1], color=plot.colors[0], style='plot')
+                        curve.add_data('manipulated', plot.vectors[1][0], plot.vectors[1][1], color=plot.colors[1], style='plot')
+                self.AddToPlaylists(playlist_new)
+            #else:
+                ##TODO: display dialog
+            self.AppendToOutput(playlist_new.get_status_string())
+            #TODO: change cursor
+            #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
+        else:
+            #TODO: display dialog
+            self.AppendToOutput(''.join['File ', filename, ' not found.\n'])
+        pass
+
+    def do_savelist(self, filename):
+        '''
+        SAVELIST
+        Saves the current file playlist on disk.
+        ------------
+        Syntax: savelist [filename]
+        '''
+
+        #self.playlist_generics['pointer'] = self._GetActiveCurveIndex
+        pointer = self._GetActiveCurveIndex()
+        #autocomplete filename if not specified
+        if not filename.endswith('.hkp'):
+            filename = filename.join(['.hkp'])
+
+        playlist = self.GetActivePlaylist()
+        playlist.set_XML()
+        playlist.save(filename)
+
+#PLOT INTERACTION COMMANDS
+#-------------------------------
+    def UpdatePlot(self):
+        def add_plot(plot):
+            if plot['visible'] and plot['x'] and plot['y']:
+                color = plot['color']
+                style = plot['style']
+                if style == 'plot':
+                    axes.plot(plot['x'], plot['y'], color=color, zorder=1)
+                if style == 'scatter':
+                    axes.scatter(plot['x'], plot['y'], color=color, s=0.5, zorder=2)
+
+        def add_plot2(plot):
+            if plot.visible and plot.x and plot.y:
+                if plot.style == 'plot':
+                    axes.plot(plot.x, plot.y, color=plot.color, zorder=1)
+                if plot.style == 'scatter':
+                    axes.scatter(plot.x, plot.y, color=plot.color, s=0.5, zorder=2)
+
+        playlist_name = self._GetActivePlaylistName()
+        index = self._GetActiveCurveIndex()
+        playlist = self.playlists[playlist_name][0]
+        curve = playlist.get_active_curve()
+        plot = playlist.get_active_plot()
+        figure = self.playlists[playlist_name][1]
+
+        figure.clf()
+        exclude = None
+        if curve.data.has_key('manipulated'):
+            exclude = 'raw'
+        elif curve.data.has_key('raw'):
+            exclude = 'manipulated'
+
+        if exclude is not None:
+            #TODO: what is this good for?
+            if not hasattr(self, 'subplot'):
+                axes = figure.add_subplot(111)
+
+            axes.set_title(plot.title)
+            axes.set_xlabel(plot.units[0])
+            axes.set_ylabel(plot.units[1])
+
+            for set_of_plots in curve.data:
+                if set_of_plots != exclude:
+                    plots = curve.data[set_of_plots]
+                    for each_plot in plots:
+                        add_plot(each_plot)
+
+            #TODO: add multiple results support
+            #for fit in curve.fits:
+            if curve.fits.has_key('wlc'):
+                for plot in curve.fits['wlc'].results:
+                    add_plot2(plot)
+                self.panelResults.DisplayResults(curve.fits['wlc'])
+            else:
+                self.panelResults.ClearResults()
+
+            axes.figure.canvas.draw()
+        else:
+            self.AppendToOutput('Not able to plot.')
+
+
+ID_PaneBorderSize = wx.ID_HIGHEST + 1
+ID_SashSize = ID_PaneBorderSize + 1
+ID_CaptionSize = ID_PaneBorderSize + 2
+ID_BackgroundColor = ID_PaneBorderSize + 3
+ID_SashColor = ID_PaneBorderSize + 4
+ID_InactiveCaptionColor =  ID_PaneBorderSize + 5
+ID_InactiveCaptionGradientColor = ID_PaneBorderSize + 6
+ID_InactiveCaptionTextColor = ID_PaneBorderSize + 7
+ID_ActiveCaptionColor = ID_PaneBorderSize + 8
+ID_ActiveCaptionGradientColor = ID_PaneBorderSize + 9
+ID_ActiveCaptionTextColor = ID_PaneBorderSize + 10
+ID_BorderColor = ID_PaneBorderSize + 11
+ID_GripperColor = ID_PaneBorderSize + 12
+
+
+#----------------------------------------------------------------------
+
+if __name__ == '__main__':
+
+    ## now, silence a deprecation warning for py2.3
+    #import warnings
+    #warnings.filterwarnings("ignore", "integer", DeprecationWarning, "wxPython.gdi")
+
+    redirect=True
+    if __debug__:
+        redirect=False
+    app = Hooke(redirect=redirect)
+
+    app.MainLoop()
+
+