#  Programmer: Daniel Pozmanter, Franz Steinhaeusler
#  Copyright 2003-2007 Daniel Pozmanter, Franz Steinhaeusler
#
#  Distributed under the terms of the GPL (GNU Public License)
#
#  DrPython is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#Plugin
#SessionsLight

#Version 0.0.1: initial Version
#
#Version 0.0.2
#   (01.03.2007): changes for DrPython 1.65 (changed paths, where files are stored)

import sys
import os.path
import wx
import drPrefsFile

def OnAbout(DrFrame):
    """Shows the SessionsLight about dialog."""
    AboutString = "SessionsLight 0.0.2"
    DrFrame.ShowMessage(AboutString, "About")

class SessionPrefsDialog(wx.Dialog):

    def __init__(self, parent, id):
        """Creates SessionsLight preferences dialog."""
        wx.Dialog.__init__(self, parent, id, "SessionsLight Preferences", wx.Point(50, 50), wx.Size(350, 250),
                           wx.DEFAULT_DIALOG_STYLE | wx.MAXIMIZE_BOX | wx.THICK_FRAME | wx.RESIZE_BORDER)

        self.parent = parent

        self.theSizer = wx.FlexGridSizer(8, 3, 5, 10)

        self.ID_RECENT = parent.GetNewId()
        self.ID_FIND = parent.GetNewId()

        self.ID_CLOSE = 101

        self.ID_SAVE = 105

        self.txtRecent = wx.TextCtrl(self, self.ID_RECENT, str(self.parent.SessionsLight_Pref_Recentsessions),
                                     wx.Point(225, 215), wx.Size(35, -1))

        self.txtFind = wx.TextCtrl(self, self.ID_FIND, str(self.parent.SessionsLight_Pref_FindHistory),
                                   wx.Point(225, 215), wx.Size(35, -1))

        self.chkAutoFind = wx.CheckBox(self, -1, "")
        self.chkAutoFind.SetValue(self.parent.SessionsLight_Pref_AutoSaveFind)

        self.chkAutoFiles = wx.CheckBox(self, -1, "")
        self.chkAutoFiles.SetValue(self.parent.SessionsLight_Pref_AutoSaveFilesRecentsessions)

        #Buffer
        self.theSizer.Add(wx.StaticText(self, -1, "   "), 0, wx.SHAPED)
        self.theSizer.Add(wx.StaticText(self, -1, "   "), 0, wx.SHAPED)
        self.theSizer.Add(wx.StaticText(self, -1, "   "), 0, wx.SHAPED)

        self.theSizer.Add(wx.StaticText(self, -1, "   "), 0, wx.SHAPED)
        self.theSizer.Add(wx.StaticText(self, -1, "Recent Sessions Limit:"), 0, wx.SHAPED)
        self.theSizer.Add(self.txtRecent, 1, wx.SHAPED)

        self.theSizer.Add(wx.StaticText(self, -1, "   "), 0, wx.SHAPED)
        self.theSizer.Add(wx.StaticText(self, -1, "Find History Length:"), 0, wx.SHAPED)
        self.theSizer.Add(self.txtFind, 1, wx.SHAPED)

        self.theSizer.Add(wx.StaticText(self, -1, "   "), 0, wx.SHAPED)
        self.theSizer.Add(wx.StaticText(self, -1, "AutoSave Find History:"), 0, wx.SHAPED)
        self.theSizer.Add(self.chkAutoFind, 1, wx.SHAPED)

        self.theSizer.Add(wx.StaticText(self, -1, "   "), 0, wx.SHAPED)
        self.theSizer.Add(wx.StaticText(self, -1, "AutoSave File List:"), 0, wx.SHAPED)
        self.theSizer.Add(self.chkAutoFiles, 1, wx.SHAPED)

        self.buttonSizer = wx.BoxSizer(wx.HORIZONTAL)

        self.btnCancel = wx.Button(self, self.ID_CLOSE, "&Close")

        self.btnCancel.SetDefault()

        self.btnSave = wx.Button(self, self.ID_SAVE, "&Save And Update")

        self.buttonSizer.Add(self.btnCancel, 0, wx.SHAPED)
        self.buttonSizer.Add(self.btnSave, 0, wx.SHAPED)

        self.theSizer.Add(wx.StaticText(self, -1, "   "), 0, wx.SHAPED | wx.ALIGN_CENTER)
        self.theSizer.Add(self.buttonSizer, 0, wx.SHAPED | wx.ALIGN_CENTER)

        self.SetAutoLayout(True)
        self.SetSizer(self.theSizer)

        self.Bind(wx.EVT_BUTTON,  self.OnbtnClose, id=self.ID_CLOSE)
        self.Bind(wx.EVT_BUTTON,  self.OnbtnSave, id=self.ID_SAVE)
        self.Bind(wx.EVT_TEXT,  self.OnTextChange, id=self.ID_RECENT)
        self.Bind(wx.EVT_TEXT,  self.OnTextChange, id=self.ID_FIND)

    def OnbtnClose(self, event):
        """Closes SessionsLight preferences."""
        self.EndModal(0)

    def OnbtnSave(self, event):
        """Saves SessionsLight preferences."""
        rs = self.txtRecent.GetValue()
        if not rs:
            rs = self.parent.SessionsLight_Pref_Recentsessions
        self.parent.SessionsLight_Pref_Recentsessions = int(rs)
        fh = self.txtFind.GetValue()
        if not fh:
            fh = self.parent.SessionsLight_Pref_FindHistory
        self.parent.SessionsLight_Pref_FindHistory = int(fh)
        self.parent.SessionsLight_Pref_AutoSaveFind = int(self.chkAutoFind.GetValue())
        self.parent.SessionsLight_Pref_AutoSaveFilesRecentsessions = int(self.chkAutoFiles.GetValue())

        if self.parent.SessionsLight_Pref_AutoSaveFind or self.parent.SessionsLight_Pref_AutoSaveFilesRecentsessions:
            self.parent.Bind(wx.EVT_CLOSE, self.parent.OnCloseAutoSave)

        preffile = self.parent.pluginspreferencesdirectory + "/Sessions.preferences.dat"
        f = file(preffile, 'w')

        f.write("<sessions.max.recent.sessions>" + str(self.parent.SessionsLight_Pref_Recentsessions) +
                "</sessions.max.recent.sessions>\n")
        f.write("<sessions.max.find.history>" + str(self.parent.SessionsLight_Pref_FindHistory) +
                "</sessions.max.find.history>\n")
        f.write("<sessions.auto.save.find.history>" + str(self.parent.SessionsLight_Pref_AutoSaveFind) +
                "</sessions.auto.save.find.history>\n")
        f.write("<sessions.auto.save.open.files>" + str(self.parent.SessionsLight_Pref_AutoSaveFilesRecentsessions) +
                "</sessions.auto.save.open.files>\n")

        f.close()
        if self.parent.prefs.enablefeedback:
            self.parent.ShowMessage("Succesfully wrote to: '%s'."  % preffile, "Saved Preferences")

    def OnTextChange(self, event):
        """Evaluates textctrl entries."""
        eid = event.GetId()
        if eid == self.SESSIONSLIGHT_ID_RECENT:
            txtctrl = self.txtRecent
            old = self.parent.SessionsLight_Pref_Recentsessions
        elif eid == self.SESSIONSLIGHT_ID_FIND:
            txtctrl = self.txtFind
            old = self.parent.SessionsLight_Pref_FindHistory
        else:
            return
        x = txtctrl.GetValue()
        if not x:
            return
        try:
            y = int(x)
        except ValueError:
            self.parent.ShowMessage("Please enter a valid number!", "Value Error")
            txtctrl.SetValue(str(old))
            return
        except TypeError:
            self.parent.ShowMessage("\"" + y + "\" is not a valid number.", "Type Error")
            txtctrl.SetValue(str(old))
            return
        if y > 256:
            self.parent.ShowMessage("DrPython does not recommend going this high.", "Number very high")


def OnPreferences(DrFrame):
    """SessionsLight Preferences."""
    d = SessionPrefsDialog(DrFrame, -1)
    d.ShowModal()
    d.Destroy()


def Plugin(DrFrame):

    def CreateRecentSessionMenu():
        """Creates recent SessionsLight menu."""
        x = 0
        while x < len(DrFrame.SessionsLight_recentsessions):
            DrFrame.SessionsLight_recentsessionmenu.Append(DrFrame.SESSIONSLIGHT_ID_RECENT_SESSIONS[x],
                                                           DrFrame.SessionsLight_recentsessions[x],
                                                           "Open " + DrFrame.SessionsLight_recentsessions[x])
            DrFrame.Bind(wx.EVT_MENU, OnLoadRecentSession, id=DrFrame.SESSIONSLIGHT_ID_RECENT_SESSIONS[x])
            x += 1

    def DestroyRecentSessionMenu():
        """Destroys recent SessionsLight menu."""
        #You need to call this function BEFORE you update the list of recent sessions.
        x = 0
        mnuitems = DrFrame.SessionsLight_recentsessionmenu.GetMenuItems()
        while x < len(mnuitems):
            DrFrame.SessionsLight_recentsessionmenu.Remove(DrFrame.SESSIONSLIGHT_ID_RECENT_SESSIONS[x])
            mnuitems[x].Destroy()
            x = x + 1

    def LoadRecentSessions():
        """Loads recent sessions."""
        f = DrFrame.SessionsLight_PrefsDir + "/recent_sessions.log"
        if not os.path.exists(f):
            try:
                t = open(f, 'w')
                t.close()
            except IOError:
                DrFrame.ShowMessage(("Error Creating: " + f), "Recent Sessions Error")
                return
        try:
            fin = open(f, 'r')
            s = fin.readline()
            last = DrFrame.SESSIONSLIGHT_ID_RECENT_SESSIONS_BASE
            x = 0
            while s and x < DrFrame.SessionsLight_Pref_Recentsessions:
                s = s.rstrip()
                if s:
                    DrFrame.SESSIONSLIGHT_ID_RECENT_SESSIONS.append(last)
                    DrFrame.SessionsLight_recentsessions.append(s)
                last = last + 1
                x = x + 1
                s = fin.readline()
            fin.close()
        except IOError:
            DrFrame.ShowMessage(("Error Reading: " + f), "Recent Sessions Error")

    def LoadSession(sessionfile, ignoreAuto = True):
        """Loads secified session."""
        try:
            DrFrame.OnCloseAllDocuments(None)
            origsessionfile = sessionfile
            if not os.path.exists(sessionfile):
                sessionfile = DrFrame.SessionsLight_PrefsDir + "/Default.dsf"
                if not os.path.exists(sessionfile):
                    DrFrame.SessionsLight_CurrentSession = sessionfile
                    wx.MessageBox("No Session file found.\nCreated Default Session File.", "Sessions", wx.ICON_EXCLAMATION)
                    return
                else:
                    wx.MessageBox("Session File: %s not found.\nLoaded Default Session."\
                                  % os.path.split(origsessionfile)[1], "Sessions", wx.ICON_EXCLAMATION)
            f = file(sessionfile, 'r')
            text = f.read()
            f.close()
            DrFrame.SessionsLight_CurrentSession = sessionfile

            if ignoreAuto or DrFrame.SessionsLight_Pref_AutoSaveFind:
                #Load Find History
                findchunk = drPrefsFile.ExtractPreferenceFromText(text, "Find History")

                DrFrame.FindHistory = []
                fh = drPrefsFile.ExtractPreferenceFromText(text, "Find").strip().split('\n\n\r\r\r\n')
                x = 0
                l = len(fh)
                if l > DrFrame.SessionsLight_Pref_FindHistory:
                    l = DrFrame.SessionsLight_Pref_FindHistory
                while x < l:
                    DrFrame.FindHistory.append(fh[x])
                    x = x + 1

                rh = drPrefsFile.ExtractPreferenceFromText(text, "Replace").strip().split('\n\n\r\r\r\n')

                DrFrame.ReplaceHistory = []
                x = 0
                l = len(rh)
                if l > DrFrame.SessionsLight_Pref_FindHistory:
                    l = DrFrame.SessionsLight_Pref_FindHistory
                while x < l:
                    DrFrame.ReplaceHistory.append(rh[x])
                    x = x + 1

            filenames = drPrefsFile.ExtractPreferenceFromText(text, "Files").rstrip().split('\n')
            if len(sys.argv) > 1:
                cmdlineactivedoc = None
                # Add Files from command line.  Let's not forget those!
                testfilenames = {}
                for fidx in xrange(0,len(filenames)):
                    testfilename = filenames[fidx].strip().replace('\\','/').lower()
                    # Store document position of session files...
                    testfilenames[testfilename]=fidx
                cmdlinefiles=[]
                # When commandline filenames are specified, we assume the last file is
                # the document we want active.  The following loop will check to see
                # if the document(s) specified in the command line are in the session,
                # and remember the active position.  Documents not in the session will
                # be loaded after the session files, and the active document will be
                # set appropriately.
                cmdlineactivedoc=None
                for clidx in xrange(1,len(sys.argv)):
                    cmdfile = sys.argv[clidx].strip().replace("\\","/")
                    if os.path.exists(cmdfile):
                        comparetosessionfile = cmdfile.lower()
                        if testfilenames.has_key(comparetosessionfile):
                            cmdlineactivedoc=testfilenames[comparetosessionfile]
                        else:
                            cmdlinefiles.append(cmdfile)
                            cmdlineactivedoc = -1

                filenames = filenames + cmdlinefiles
                # /Add Files from command line.

            if ignoreAuto or DrFrame.SessionsLight_Pref_AutoSaveFilesRecentsessions:

                #check for existing files
                if filenames and filenames[0] != '':
                    fnames = []
                    ActiveDocument = drPrefsFile.GetPrefFromText(0, text, "Active.Document", True)
                    docpositions = drPrefsFile.ExtractPreferenceFromText(text, "Document.Positions").rstrip().split('\n')
                    dpositions = []

                    for i in range(len(filenames)):
                        if os.path.exists(filenames[i]):
                            fnames.append(filenames[i])
                            dpositions.append(docpositions[i])
                        else:
                            ActiveDocument -= 1
                            DrFrame.ShowMessage("File does not exist: " + filenames[i], "Sessions")

                    filenames = fnames
                    docpositions = dpositions

                    #Load the Files
                    l = len(filenames)
                    #Bug-Report With Fix, Franz Steinhausler


                    if l > 0 and filenames[0]:
                    #/Bug-Report With Fix, Franz Steinhausler
                        old = DrFrame.txtDocument.filename
                        x = 1
                        if l > 1:
                            filename = filenames[0].replace("\\", "/")
                            DrFrame.OpenFile(filename, len(old) > 0)
                        while x < l:
                            filename = filenames[x].replace("\\", "/")
                            DrFrame.OpenFile(filename, True)
                            x = x + 1
                        if l <= 1:
                            filename = filenames[0].replace("\\", "/")
                            if old or DrFrame.txtDocument.GetModify():
                                DrFrame.OpenFile(filename, True)
                            else:
                                DrFrame.OpenFile(filename, False)
                    #/Load the Files

                    #Load the Active Document, taking into consideration documents loaded from commandline.
                else:
                    DrFrame.ShowMessage("No File in Session: " + sessionfile, "Sessions")
                    ActiveDocument = 0

                if len(sys.argv) > 1:

                    if cmdlineactivedoc==-1:
                        ActiveDocument = len(filenames)-1
                    elif cmdlineactivedoc==None:
                        ActiveDocument = drPrefsFile.GetPrefFromText(0, text, "Active.Document", True)
                    else:
                        ActiveDocument = cmdlineactivedoc
                if ActiveDocument >= len(DrFrame.txtDocumentArray) or ActiveDocument < 0:
                    ActiveDocument = 0
                try:
                    DrFrame.setDocumentTo(ActiveDocument)
                except:
                    pass
                #/Load the Active Document

                #Document Positions
                x = 0
                l = len(DrFrame.txtDocumentArray)
                while x < l:
                    try:
                        ipos = int(docpositions[x])
                    except:
                        ipos = 0
                    DrFrame.txtDocumentArray[x].GotoPos(ipos)
                    DrFrame.txtDocumentArray[x].ScrollToLine(DrFrame.txtDocumentArray[x].LineFromPosition(ipos))
                    DrFrame.txtDocumentArray[x].ScrollToColumn(0)
                    x = x + 1
                #/Document Positions

                DrFrame.txtDocument.SetFocus()

            if ignoreAuto:
                if DrFrame.SessionsLight_recentsessions.count(sessionfile) != 0:
                    DrFrame.SESSIONSLIGHT_ID_RECENT_SESSIONS.pop()
                    DrFrame.SessionsLight_recentsessions.remove(sessionfile)
                if len(DrFrame.SessionsLight_recentsessions) == DrFrame.prefs.recentfileslimit:
                    DrFrame.SessionsLight_recentsessions.pop()
                    DrFrame.SESSIONSLIGHT_ID_RECENT_SESSIONS.pop()
                ti = len(DrFrame.SESSIONSLIGHT_ID_RECENT_SESSIONS) - 1
                if ti > -1:
                    DrFrame.SESSIONSLIGHT_ID_RECENT_SESSIONS.append(DrFrame.SESSIONSLIGHT_ID_RECENT_SESSIONS[ti] + 1)
                else:
                    DrFrame.SESSIONSLIGHT_ID_RECENT_SESSIONS.append(DrFrame.SESSIONSLIGHT_ID_RECENT_SESSIONS_BASE)
                while sessionfile in DrFrame.SessionsLight_recentsessions:
                    DrFrame.SessionsLight_recentsessions.remove(sessionfile)
                DrFrame.SessionsLight_recentsessions.insert(0, sessionfile)
                WriteRecentSessions()
        except:
            DrFrame.ShowMessage("Error Loading Session: " + sessionfile, "DrPython Error")

    def OnClearRecentSessions(event):
        """Clears recent sessions menu entries."""
        answer = wx.MessageBox("This will clear all recent sessions.\nAre you sure you want to do this?",
                                "DrPython", wx.YES_NO | wx.ICON_QUESTION)
        if answer == wx.YES:
            DrFrame.SessionsLight_recentsessions = []
            DestroyRecentSessionMenu()
            CreateRecentSessionMenu()

    def OnCloseAutoSave(event):
        """This is called on exiting DrPython."""
        if not DrFrame.SessionsLight_CurrentSession:
            DrFrame.SessionsLight_CurrentSession = DrFrame.SessionsLight_PrefsDir + "/Default.dsf"
        SaveSession(DrFrame.SessionsLight_CurrentSession, False)
        #if not exist, create
        if not os.path.exists(DrFrame.SessionsLight_PrefsDir):
            os.mkdir(DrFrame.SessionsLight_PrefsDir)
        f = file(DrFrame.SessionsLight_PrefsDir + "/LastSession.ses", 'w')
        f.write(DrFrame.SessionsLight_CurrentSession)
        f.close()
        event.Skip()

    def OnLoadRecentSession(event):
        """Load recent session."""
        recentmenuindex = event.GetId() - DrFrame.SESSIONSLIGHT_ID_RECENT_SESSIONS_BASE
        filename = DrFrame.SessionsLight_recentsessions[recentmenuindex]
        OnLoadSession(None, filename)

    def OnLoadSession(event, filename = ""):
        """Manually Load session."""
        if not filename:
            dlg = wx.FileDialog(DrFrame, "Load Session: [Current: %s]" % os.path.split(DrFrame.SessionsLight_CurrentSession) [1],
                                "", "", DrFrame.sessionwildcard, wx.OPEN|wx.HIDE_READONLY)
            try:

                dlg.SetDirectory(DrFrame.SessionsLight_PrefsDir)
            except:
                DrFrame.ShowMessage("Error Setting Default Directory To: " + DrFrame.SessionsLight_PrefsDir, "DrPython Error")
        else:
            dlg = None
        if not dlg or dlg.ShowModal() == wx.ID_OK:
            if dlg:
                filename = dlg.GetPath().replace("\\", '/')

            if filename == DrFrame.SessionsLight_CurrentSession:
                wx.MessageBox("This session is already active", "Sessions", wx.ICON_EXCLAMATION)
                return

            answer = wx.MessageBox("Save Session: %s" % os.path.split(DrFrame.SessionsLight_CurrentSession) [1],
                                   "Sessions", wx.YES_NO | wx.ICON_QUESTION)
            if answer == wx.YES:
                SaveSession(DrFrame.SessionsLight_CurrentSession)
                DestroyRecentSessionMenu()
                WriteRecentSessions()
                CreateRecentSessionMenu()

            DestroyRecentSessionMenu()
            LoadSession(filename)
            WriteRecentSessions()
            CreateRecentSessionMenu()
        if dlg:
            dlg.Destroy()

    def OnSaveSession(event):
        """Manually save session."""
        dlg = wx.FileDialog(DrFrame, "Save Session As [Current: %s]" % os.path.split(DrFrame.SessionsLight_CurrentSession) [1],
                            "", "", DrFrame.sessionwildcard, wx.SAVE|wx.OVERWRITE_PROMPT)
        try:
            dlg.SetDirectory(DrFrame.SessionsLight_PrefsDir)
        except:
            DrFrame.ShowMessage(("Error Setting Default Directory To: " + DrFrame.SessionsLight_PrefsDir), "DrPython Error")
        if dlg.ShowModal() == wx.ID_OK:
            sessionfilename = dlg.GetPath().replace("\\", "/")
            try:
                SaveSession(sessionfilename)
                DestroyRecentSessionMenu()
                WriteRecentSessions()
                CreateRecentSessionMenu()
            except:
                DrFrame.ShowMessage(("Error Saving: " + sessionfilename), "DrPython Error")
            dlg.Destroy()

    def SaveSession(sessionfilename, ignoreAuto = True):
        """Saves specified Session."""
        try:
            path = os.path.split(sessionfilename)[0]
            if not os.path.exists(path):
                os.mkdir(path)

            f = file(sessionfilename, 'w')

            if ignoreAuto or DrFrame.SessionsLight_Pref_AutoSaveFind:
                f.write("<Find History>\n<Find>")
                DrFrame.FindHistory = DrFrame.FindHistory[-DrFrame.SessionsLight_Pref_FindHistory:]
                for x in DrFrame.FindHistory:
                    f.write(x + '\n\n\r\r\r\n')
                f.write("</Find>\n<Replace>")

                DrFrame.ReplaceHistory = DrFrame.ReplaceHistory[-DrFrame.SessionsLight_Pref_FindHistory:]
                for x in DrFrame.ReplaceHistory:
                    f.write(x + '\n\n\r\r\r\n')

                f.write("</Replace></Find History>\n")

            if ignoreAuto or DrFrame.SessionsLight_Pref_AutoSaveFilesRecentsessions:
                #Files
                f.write("<Files>")
                x = 0
                for document in DrFrame.txtDocumentArray:
                    if document.filename:
                        f.write(document.filename + '\n')
                f.write("</Files>\n")

                #Active Document
                f.write("<Active.Document>")
                f.write(str(DrFrame.docPosition))
                f.write("</Active.Document>\n")

                #Document Positions
                f.write("<Document.Positions>")
                for document in DrFrame.txtDocumentArray:
                    if document.filename:
                        f.write(str(document.GetCurrentPos()) + '\n')
                f.write("</Document.Positions>\n")

            f.close()
        except:
            DrFrame.ShowMessage(("Error Writing To: " + sessionfilename), "DrPython Error")

    def WriteRecentSessions():
        """Stores Recent Sessios."""
        try:
            fin = open(DrFrame.SessionsLight_PrefsDir + "/recent_sessions.log", 'w')
            x = 0
            length = len(DrFrame.SessionsLight_recentsessions)
            while x < DrFrame.SessionsLight_Pref_Recentsessions and x < length:
                fin.write(DrFrame.SessionsLight_recentsessions[x] + '\n')
                x = x + 1
            fin.close()
        except IOError:
            DrFrame.ShowMessage(("Error Writing: " + f), "Recent Sessions Error")

    
    DrFrame.sessionwildcard = "DrPython Session File (*.dsf)|*.dsf|All Files (*)|*"

    SESSIONSLIGHT_ID_LOAD_SESSION = DrFrame.GetNewId()
    SESSIONSLIGHT_ID_SAVE_SESSION = DrFrame.GetNewId()

    SESSIONSLIGHT_ID_CLEAR = DrFrame.GetNewId()

    #Preferences (Defaults):
    DrFrame.SessionsLight_Pref_Recentsessions = 10
    DrFrame.SessionsLight_Pref_FindHistory = 10
    DrFrame.SessionsLight_Pref_AutoSaveFind = 0
    DrFrame.SessionsLight_Pref_AutoSaveFilesRecentsessions = 0
    DrFrame.SessionsLight_CurrentSession = ''
    DrFrame.SessionsLight_PrefsDir = DrFrame.pluginsuserdatadirectory + "/SessionsLight"
    if not os.path.exists(DrFrame.SessionsLight_PrefsDir):
        os.mkdir(DrFrame.SessionsLight_PrefsDir)

    preffile = DrFrame.pluginspreferencesdirectory + "/Sessions.preferences.dat"
    if os.path.exists(preffile):
        f = file(preffile, 'r')
        text = f.read()
        f.close()
        DrFrame.SessionsLight_Pref_Recentsessions = drPrefsFile.GetPrefFromText(DrFrame.SessionsLight_Pref_Recentsessions,
                                                    text, "sessions.max.recent.sessions", True)
        DrFrame.SessionsLight_Pref_FindHistory = drPrefsFile.GetPrefFromText(DrFrame.SessionsLight_Pref_FindHistory,
                                          text, "sessions.max.find.history", True)
        DrFrame.SessionsLight_Pref_AutoSaveFind = drPrefsFile.GetPrefFromText(DrFrame.SessionsLight_Pref_AutoSaveFind,
                                           text, "sessions.auto.save.find.history", True)
        DrFrame.SessionsLight_Pref_AutoSaveFilesRecentsessions =\
                                            drPrefsFile.GetPrefFromText(DrFrame.SessionsLight_Pref_AutoSaveFilesRecentsessions,
                                            text, "sessions.auto.save.open.files", True)

    #AutoLoad:
    if DrFrame.SessionsLight_Pref_AutoSaveFind or DrFrame.SessionsLight_Pref_AutoSaveFilesRecentsessions:
        prefslast = DrFrame.SessionsLight_PrefsDir + "/LastSession.ses"
        if os.path.exists(prefslast):
            f = file(prefslast, 'r')
            text = f.read()
            f.close()
            LoadSession(text, False)
        else:
            LoadSession(DrFrame.SessionsLight_PrefsDir + "/Default.dsf", False)

    DrFrame.SESSIONSLIGHT_ID_RECENT_SESSIONS_BASE = 8330

    DrFrame.SESSIONSLIGHT_ID_RECENT_SESSIONS = []
    DrFrame.SessionsLight_recentsessions = []

    DrFrame.OnCloseAutoSave = OnCloseAutoSave

    if DrFrame.SessionsLight_Pref_AutoSaveFind or DrFrame.SessionsLight_Pref_AutoSaveFilesRecentsessions:
        DrFrame.Bind(wx.EVT_CLOSE, DrFrame.OnCloseAutoSave)

    DrFrame.Bind(wx.EVT_MENU,  OnLoadSession, id=SESSIONSLIGHT_ID_LOAD_SESSION)
    DrFrame.Bind(wx.EVT_MENU,  OnSaveSession, id=SESSIONSLIGHT_ID_SAVE_SESSION)
    DrFrame.Bind(wx.EVT_MENU,  OnClearRecentSessions, id=SESSIONSLIGHT_ID_CLEAR)

    DrFrame.AddPluginFunction('SessionsLight', "Load Session", OnLoadSession)
    DrFrame.AddPluginFunction('SessionsLight', "Save Session", OnSaveSession)
    DrFrame.AddPluginFunction('SessionsLight', "Clear Recent Sessions", OnClearRecentSessions)

    DrFrame.SessionsLight_recentsessionmenu = wx.Menu()
    LoadRecentSessions()
    CreateRecentSessionMenu()

    DrFrame.LoadPluginShortcuts('SessionsLight')
    
    DrFrame.sessionmenu = wx.Menu()

    DrFrame.sessionmenu.Append(SESSIONSLIGHT_ID_LOAD_SESSION,
                               DrFrame.GetPluginMenuLabel('SessionsLight', 'Load Session', 'Load Session...'))
    DrFrame.sessionmenu.Append(SESSIONSLIGHT_ID_SAVE_SESSION,
                               DrFrame.GetPluginMenuLabel('SessionsLight', 'Save Session', 'Save Session...'))
    DrFrame.sessionmenu.AppendMenu(DrFrame.GetNewId(),
                                   "Load Recent Session", DrFrame.SessionsLight_recentsessionmenu)
    DrFrame.sessionmenu.AppendSeparator()
    DrFrame.sessionmenu.Append(SESSIONSLIGHT_ID_CLEAR,
                               DrFrame.GetPluginMenuLabel('SessionsLight', 'Clear Recent Sessions', 'Clear Recent Sessions'))

    DrFrame.filemenu.InsertSeparator(5)

    DrFrame.filemenu.InsertMenu(6, DrFrame.GetNewId(), "Sessions", DrFrame.sessionmenu)
