#!/usr/bin/python

# notebook.py

##
## Copyright (C) 2011-2012 Andrew Atkinson
##
##-------------------------------------------------------------------
## This program 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 3 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, see <http://www.gnu.org/licenses/>.
##-------------------------------------------------------------------

#python modules
import os
#import shutil
#import subprocess
#import sys
#import threading
import wx
import wx.gizmos
import wx.grid
import wx.lib.intctrl
import wx.lib.masked
try:
    import cPickle as pickle
except:
    import pickle

#Program modules
#import CheckerCreate
import Defaults
import Process
#import ReadTop
#import relshots
#import Writeth
#import Writeth2
#import Writethconfig


class FStructure(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        gridder = wx.GridBagSizer(5, 5)

        copytop = wx.CheckBox(self, label='Copy top file to Raw Location')
        initiatecheckbox(copytop, 'copytop')
        copytop.Bind(wx.EVT_CHECKBOX, lambda evt,
                    temp='copytop': OnCheckBox(evt, temp))
        introtext = '''File locations'''
        intro_t = wx.StaticText(self, wx.ID_ANY, introtext)

        #PocketTopo file location
        pockettopo_l = wx.StaticText(self, wx.ID_ANY, 'Pockettopo File:')
        self.pockettopo_t = wx.TextCtrl(self)
        initiatetext(self.pockettopo_t, 'pockettopo')
        self.pockettopo_t.Bind(wx.EVT_TEXT, lambda evt,
                                temp='pockettopo': OnTextChange(evt, temp))
        pockettopo_b = wx.Button(self, label='Browse...')
        pockettopo_b.Bind(wx.EVT_BUTTON, self.PocketTopoD)

        #Root directory where all the survey project is compiled from
        ProjectRootL = wx.StaticText(self, wx.ID_ANY, 'Project Directory:')
        self.projectroot_t = wx.TextCtrl(self)
        initiatetext(self.projectroot_t, 'projectroot')
        self.projectroot_t.Bind(wx.EVT_TEXT, lambda evt,
                                temp='projectroot': OnTextChange(evt, temp))
        projectroot_b = wx.Button(self, label='Browse...')
        projectroot_b.Bind(wx.EVT_BUTTON, self.ProjectRootD)

        # Directory where all the new survey is to live
        surveydir_l = wx.StaticText(self, wx.ID_ANY, 'Survey Directory:')
        self.surveydir_t = wx.TextCtrl(self)
        initiatetext(self.surveydir_t, 'surveydir')
        self.surveydir_t.Bind(wx.EVT_TEXT, lambda evt,
                                temp='surveydir': OnTextChange(evt, temp))
        surveydir_b = wx.Button(self, label='Browse...')
        surveydir_b.Bind(wx.EVT_BUTTON, self.SurveyDirD)
        addnamedir = wx.CheckBox(self,
                                label='Add a subdirectory same as top name')
        initiatecheckbox(addnamedir, 'addnamedir')
        addnamedir.Bind(wx.EVT_CHECKBOX, lambda evt,
                        temp='addnamedir': OnCheckBox(evt, temp))

        # Raw directory for new survey
        rawdir_l = wx.StaticText(self, wx.ID_ANY,
                                    'Raw (XVI and top) Directory:')
        self.rawdir_t = wx.TextCtrl(self)
        initiatetext(self.rawdir_t, 'rawdir')
        self.rawdir_t.Bind(wx.EVT_TEXT, lambda evt,
                            temp='rawdir': OnTextChange(evt, temp))
        rawdir_b = wx.Button(self, label='Browse...')
        rawdir_b.Bind(wx.EVT_BUTTON, self.RawDirD)
        insurveydir = wx.CheckBox(self, wx.ID_ANY,
                                    'Raw Directory is in the Survey Directory')
        initiatecheckbox(insurveydir, 'insurveydir')
        insurveydir.Bind(wx.EVT_CHECKBOX, lambda evt,
                        temp='insurveydir': OnCheckBox(evt, temp))

        # overwrite and open therion/aven
        overwrite = wx.CheckBox(self, label='Overwrite files without asking!!!')
        initiatecheckbox(overwrite, 'overwrite')
        overwrite.Bind(wx.EVT_CHECKBOX, lambda evt,
                       temp='overwrite': OnCheckBox(evt, temp))

        # Open, process files and add to a repository
        process = wx.CheckBox(self, wx.ID_ANY,
                                'Process data with thconfig file')
        initiatecheckbox(process, 'process')
        process.Bind(wx.EVT_CHECKBOX, lambda evt,
                    temp='process': OnCheckBox(evt, temp))
        open3d = wx.CheckBox(self, wx.ID_ANY, 'Open 3d file with:')
        initiatecheckbox(open3d, 'open3d')
        open3d.Bind(wx.EVT_CHECKBOX, lambda evt,
                    temp='open3d': OnCheckBox(evt, temp))

        aven = wx.RadioButton(self, wx.ID_ANY, 'aven', style=wx.RB_GROUP)
        loch = wx.RadioButton(self, wx.ID_ANY, 'loch')
        aven.Bind(wx.EVT_RADIOBUTTON, lambda evt,
                    temp='aven': OnRadioButton(evt, temp))
        loch.Bind(wx.EVT_RADIOBUTTON, lambda evt,
                    temp='loch': OnRadioButton(evt, temp))
        try:
            settings['viewer']
        except:
            settings['viewer'] = D.viewer
        if settings['viewer'] == 'aven':
            aven.SetValue(True)
        else:
            loch.SetValue(True)

        dsuffix_l = wx.StaticText(self, wx.ID_ANY, '3d Suffix:')
        dsuffix_t = wx.TextCtrl(self)
        initiatetext(dsuffix_t, 'dsuffix')
        dsuffix_t.Bind(wx.EVT_TEXT, lambda evt,
                        temp='dsuffix': OnTextChange(evt, temp))

        openfiles = wx.CheckBox(self, wx.ID_ANY, 'Open xtherion, prefering:')
        initiatecheckbox(openfiles, 'openfiles')
        openfiles.Bind(wx.EVT_CHECKBOX, lambda evt,
                        temp='openfiles': OnCheckBox(evt, temp))
        xplan = wx.RadioButton(self, wx.ID_ANY, 'plan', style=wx.RB_GROUP)
        xelev = wx.RadioButton(self, wx.ID_ANY, 'elevation')
        try:
            settings['th2edit']
        except:
            settings['th2edit'] = D.th2edit
        if settings['th2edit'] == 'xplan':
            xplan.SetValue(True)
        else:
            xelev.SetValue(True)
        xplan.Bind(wx.EVT_RADIOBUTTON, lambda evt,
                    temp='xplan': OnRadioButton(evt, temp))
        xelev.Bind(wx.EVT_RADIOBUTTON, lambda evt,
                    temp='xelev': OnRadioButton(evt, temp))

        add2rep = wx.CheckBox(self, wx.ID_ANY, 'Add to repository using:')
        initiatecheckbox(add2rep, 'add2rep')
        add2rep.Bind(wx.EVT_CHECKBOX, lambda evt,
                    temp='add2rep': OnCheckBox(evt, temp))

        svn = wx.RadioButton(self, wx.ID_ANY, 'svn', style=wx.RB_GROUP)
        hg = wx.RadioButton(self, wx.ID_ANY, 'mercurial')
        git = wx.RadioButton(self, wx.ID_ANY, 'git')
        try:
            settings['repository']
        except:
            settings['repository'] = D.repository
        if settings['repository'] == 'svn':
            svn.SetValue(True)
        elif settings['repository'] == 'hg':
            hg.SetValue(True)
        else:
            git.SetValue(True)
        svn.Bind(wx.EVT_RADIOBUTTON, lambda evt,
                    temp='svn': OnRadioButton(evt, temp))
        hg.Bind(wx.EVT_RADIOBUTTON, lambda evt,
                    temp='hg': OnRadioButton(evt, temp))
        git.Bind(wx.EVT_RADIOBUTTON, lambda evt,
                    temp='git': OnRadioButton(evt, temp))

        # Put the grid together
        gridder.Add(intro_t, pos=(0, 1), span=(1, 3))
        gridder.Add(copytop, (2, 2), span=(1, 3))

        gridder.Add(pockettopo_l, pos=(1, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.pockettopo_t, pos=(1, 2), span=(1, 4),
                    flag=wx.EXPAND)
        gridder.Add(pockettopo_b, pos=(1, 6))

        gridder.Add(ProjectRootL, pos=(3, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.projectroot_t, pos=(3, 2), span=(1, 4),
                    flag=wx.EXPAND)
        gridder.Add(projectroot_b, pos=(3, 6))
        gridder.Add(surveydir_l, pos=(4, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.surveydir_t, pos=(4, 2), span=(1, 4),
                    flag=wx.EXPAND)
        gridder.Add(surveydir_b, pos=(4, 6))
        gridder.Add(addnamedir, pos=(5, 2), span=(1, 4))
        gridder.Add(rawdir_l, pos=(6, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.rawdir_t, pos=(6, 2), span=(1, 4),
                    flag=wx.EXPAND)
        gridder.Add(rawdir_b, pos=(6, 6))
        gridder.Add(insurveydir, pos=(7, 2), span=(1, 4))
        gridder.Add(overwrite, pos=(9, 1))
        gridder.AddGrowableCol(5)
        gridder.Add(process, pos=(10, 1))
        gridder.Add(open3d, pos=(11, 1))
        gridder.Add(aven, pos=(11, 2))
        gridder.Add(loch, pos=(11, 3))
        gridder.Add(dsuffix_l, pos=(11, 4),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(dsuffix_t, pos=(11, 5))
        gridder.Add(openfiles, pos=(12, 1))
        gridder.Add(xplan, pos=(12, 2))
        gridder.Add(xelev, pos=(12, 3))
        gridder.Add(add2rep, pos=(13, 1))
        gridder.Add(svn, pos=(13, 2))
        gridder.Add(hg, pos=(13, 3))
        gridder.Add(git, pos=(13, 4))

        self.SetSizer(gridder)

    def PocketTopoD(self, event):
        dp = self.PathExists(os.path.dirname(settings['pockettopo']))
        dlg = wx.FileDialog(self, "Select PocketTopo File:",
                            wildcard='top files (*.top)|*.top|All files|*',
                            defaultDir=dp,
                            style=wx.DD_DEFAULT_STYLE)
        if dlg.ShowModal() == wx.ID_OK:
            self.pockettopo_t.SetValue(dlg.GetPath())
        dlg.Destroy()

    def ProjectRootD(self, event):
        dp = self.PathExists(settings['projectroot'])

        dlg = wx.DirDialog(self, "Select Project Directory:",
                            defaultPath=dp, style=wx.DD_DEFAULT_STYLE)
        if dlg.ShowModal() == wx.ID_OK:
            self.projectroot_t.SetValue(dlg.GetPath())
        dlg.Destroy()

    def SurveyDirD(self, event):
        #print(settings['surveydir'])
        surveydir = os.path.join(settings['projectroot'], settings['surveydir'])

        if os.path.exists(surveydir):
            dp = surveydir
        else:
            dp = self.PathExists(settings['projectroot'])
        dlg = wx.DirDialog(self, "Select Survey Directory:",
                            defaultPath=dp, style=wx.DD_DEFAULT_STYLE)
        if dlg.ShowModal() == wx.ID_OK:
            settings['surveydir'] = os.path.relpath(dlg.GetPath(),
                                                    settings['projectroot'])
            self.surveydir_t.SetValue(settings['surveydir'])
        dlg.Destroy()

    def RawDirD(self, event):
        #Cascade down through directory -> survey location -> Project
        if settings['insurveydir']:
            rawdir = os.path.join(settings['projectroot'],
                                    settings['surveydir'])
        else:
            rawdir = settings['projectroot']
        if os.path.exists(rawdir):
            dp = rawdir
        else:
            dp = self.PathExists(settings['projectroot'])
        dlg = wx.DirDialog(self, "Select Raw Directory:",
                            defaultPath=dp, style=wx.DD_DEFAULT_STYLE)
        if dlg.ShowModal() == wx.ID_OK:
            if settings['insurveydir']:
                settings['rawdir'] = os.path.relpath(dlg.GetPath(),
                                                        settings['surveydir'])
            else:
                settings['rawdir'] = os.path.relpath(dlg.GetPath(),
                                                        settings['projectroot'])
            self.rawdir_t.ChangeValue(settings['rawdir'])
            #print(settings['rawdir'])
        dlg.Destroy()

    def PathExists(self, path):
        '''If path does not exist, make it blank'''
        if os.path.exists(path):
            dp = path
        else:
            dp = ""
        return dp


class thFile(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        gridder = wx.GridBagSizer(5, 5)
        dothfile = wx.CheckBox(self, wx.ID_ANY, label='Produce th File')
        initiatecheckbox(dothfile, 'dothfile')
        dothfile.Bind(wx.EVT_CHECKBOX, lambda evt,
                        temp='dothfile': OnCheckBox(evt, temp))
        dosvxfile = wx.CheckBox(self, label='Produce svx File')
        initiatecheckbox(dosvxfile, 'dosvxfile')
        dosvxfile.Bind(wx.EVT_CHECKBOX, lambda evt,
                        temp='dosvxfile': OnCheckBox(evt, temp))
        addlrud = wx.CheckBox(self, label='Calculate LRUD from splays within')
        initiatecheckbox(addlrud, 'addlrud')
        addlrud.Bind(wx.EVT_CHECKBOX, lambda evt,
                        temp='addlrud': OnCheckBox(evt, temp))
        introtext = 'Controls the elements of the th file'
        intro_t = wx.StaticText(self, label=introtext)
        lrudangle_l = wx.StaticText(self, wx.ID_ANY,
                                    'degrees of x-section plane')
        lrudangle = wx.TextCtrl(self)
        initiatetext(lrudangle, 'lrudangle')
        lrudangle.Bind(wx.EVT_TEXT, lambda evt,
                        temp='lrudangle': OnTextChange(evt, temp))
        gridder.Add(intro_t, pos=(0, 1), span=(1, 4))
        gridder.Add(dothfile, (1, 1), span=(1, 2))
        gridder.Add(dosvxfile, (1, 3), span=(1, 2))
        gridder.Add(addlrud, (1, 5), span=(1, 2))
        gridder.Add(lrudangle, (1, 7), span=(1, 1), flag=wx.ALIGN_RIGHT)
        gridder.Add(lrudangle_l, (1, 8), span=(1, 1))

        #Data order and import th2 files
        dataorder_l = wx.StaticText(self, wx.ID_ANY, 'dataorder:')
        self.DO = ""
        try:
            settings['dataorder']
        except:
            settings['dataorder'] = D.dataorder
        for d in settings['dataorder']:
            self.DO += d + '    '
        self.dataorder = wx.StaticText(self, wx.ID_ANY, self.DO)
        changeorder = wx.Button(self, label='Change order')
        changeorder.Bind(wx.EVT_BUTTON, self.onchangeorder)

        addroll = wx.CheckBox(self, label='Roll Angle')
        initiatecheckbox(addroll, 'addroll')
        addroll.Bind(wx.EVT_CHECKBOX, lambda evt,
                            temp='addroll': OnCheckBox(evt, temp))

        importth2text = 'Add an import line for:'
        Importth2 = wx.StaticText(self, wx.ID_ANY, importth2text)
        importth2plan = wx.CheckBox(self, label='Plan')
        initiatecheckbox(importth2plan, 'importth2plan')
        importth2plan.Bind(wx.EVT_CHECKBOX, lambda evt,
                            temp='importth2plan': OnCheckBox(evt, temp))
        importth2elev = wx.CheckBox(self, wx.ID_ANY, 'Elevation')
        initiatecheckbox(importth2elev, 'importth2elev')
        importth2elev.Bind(wx.EVT_CHECKBOX, lambda evt,
                            temp='importth2elev': OnCheckBox(evt, temp))
        importth2proj = wx.CheckBox(self, wx.ID_ANY, 'Projection')
        initiatecheckbox(importth2proj, 'importth2proj')
        importth2proj.Bind(wx.EVT_CHECKBOX, lambda evt,
                            temp='importth2proj': OnCheckBox(evt, temp))
        docopyright = wx.CheckBox(self, label='Add copyright information')
        initiatecheckbox(docopyright, 'docopyright')
        docopyright.Bind(wx.EVT_CHECKBOX, lambda evt,
                            temp='docopyright': OnCheckBox(evt, temp))
        cright = wx.TextCtrl(self)
        initiatetext(cright, 'cright')
        cright.Bind(wx.EVT_TEXT, lambda evt,
                        temp='cright': OnTextChange(evt, temp))
        gridder.Add(dataorder_l, (2, 1), span=(1, 2),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.dataorder, (2, 3), span=(1, 4),
                    flag=wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(changeorder, (2, 7), flag=wx.ALIGN_CENTER_VERTICAL)

        gridder.Add(addroll, (2, 8), flag=wx.ALIGN_CENTER_VERTICAL)

        gridder.Add(Importth2, (3, 1), span=(1, 2), flag=wx.ALIGN_RIGHT)
        gridder.Add(importth2plan, (3, 3))
        gridder.Add(importth2elev, (3, 4), span=(1, 2), flag=wx.ALIGN_CENTER)
        gridder.Add(importth2proj, (3, 6))
        gridder.Add(docopyright, (4, 1), span=(1, 3))
        gridder.Add(cright, (4, 4), span=(1, 4), flag=wx.EXPAND)

        #Surveyors
        # Build information
        try:
            settings['caverlist']
        except:
            settings['caverlist'] = D.caverlist
        peoplelist = self.buildpeoplelist(settings['caverlist'])
        docavers = wx.CheckBox(self, label='Add surveying information')
        initiatecheckbox(docavers, 'docavers')
        docavers.Bind(wx.EVT_CHECKBOX, lambda evt,
                        temp='docavers': OnCheckBox(evt, temp))
        notes_l = wx.StaticText(self, wx.ID_ANY, 'Notes:')
        inst_l = wx.StaticText(self, wx.ID_ANY, 'Instruments:')
        dog_l = wx.StaticText(self, wx.ID_ANY, 'Dogs:')
        self.notes_p = wx.StaticText(self, wx.ID_ANY, peoplelist['Notes'])
        self.inst_p = wx.StaticText(self, wx.ID_ANY, peoplelist['Instruments'])
        self.dog_p = wx.StaticText(self, wx.ID_ANY, peoplelist['Dog'])
        instused_l = wx.StaticText(self, wx.ID_ANY, 'Instrument used:')
        instrument = wx.TextCtrl(self)
        initiatetext(instrument, 'instrument')
        instrument.Bind(wx.EVT_TEXT, lambda evt,
                        temp='instrument': OnTextChange(evt, temp))
        gridder.Add(docavers, pos=(5, 1), span=(1, 3))
        gridder.Add(notes_l, pos=(6, 2),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.notes_p, pos=(6, 3), span=(1, 4),
                    flag=wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(inst_l, pos=(7, 1), span=(1, 2),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.inst_p, pos=(7, 3), span=(1, 4),
                    flag=wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(dog_l, pos=(8, 2),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.dog_p, pos=(8, 3), span=(1, 4),
                    flag=wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(instused_l, pos=(9, 1), span=(1, 2),
                        flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(instrument, pos=(9, 3), span=(1, 4), flag=wx.EXPAND)

        #Exploration
        doexplo = wx.CheckBox(self, label='Add exploration information')
        initiatecheckbox(doexplo, 'doexplo')
        explordate_l = wx.StaticText(self, wx.ID_ANY, 'Date:')
        explodateastrip = wx.RadioButton(self, wx.ID_ANY,
                            'as trip', style=wx.RB_GROUP)
        explodateother = wx.RadioButton(self, wx.ID_ANY,)
        explodateastrip.Bind(wx.EVT_RADIOBUTTON, lambda evt,
                             temp='explodateastrip': OnRadioButton(evt, temp))
        explodateother.Bind(wx.EVT_RADIOBUTTON, lambda evt,
                            temp='explodateother': OnRadioButton(evt, temp))
        try:
            settings['samedate']
        except:
            settings['samedate'] = D.samedate
        if settings['samedate']:
            explodateastrip.SetValue(True)
        else:
            explodateother.SetValue(True)
        explodate_t = wx.TextCtrl(self)
        initiatetext(explodate_t, 'explodate')
        explodate_t.Bind(wx.EVT_TEXT, lambda evt,
                        temp='explodate': OnTextChange(evt, temp))
        initiatecheckbox(doexplo, 'doexplo')
        doexplo.Bind(wx.EVT_CHECKBOX, lambda evt,
                        temp='doexplo': OnCheckBox(evt, temp))

        explorpeople_l = wx.StaticText(self, wx.ID_ANY, 'People:')
        self.explorpeople_p = wx.StaticText(self, wx.ID_ANY,
                                            peoplelist['Explorer'])
        changecavers = wx.Button(self, label='Change Cavers')
        changecavers.Bind(wx.EVT_BUTTON, self.onchangecavers)
        gridder.Add(doexplo, pos=(10, 1), span=(1, 3))
        gridder.Add(explordate_l, pos=(11, 2),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(explodateastrip, pos=(11, 3),
                    flag=wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(explodateother, pos=(11, 4),
                    flag=wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(explodate_t, pos=(11, 5),
                    flag=wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(explorpeople_l, pos=(12, 2),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.explorpeople_p, pos=(12, 3), span=(1, 4),
                    flag=wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(changecavers, pos=(13, 7), span=(1, 2))

        #Map output
            #Plan
        addplanmap = wx.CheckBox(self, label='Include Plan Map')
        initiatecheckbox(addplanmap, 'addplanmap')
        addplanmap.Bind(wx.EVT_CHECKBOX, lambda evt, temp='addplanmap': OnCheckBox(evt, temp))
        pmapsuffix_l = wx.StaticText(self, wx.ID_ANY, 'Map Suffix Plan:')
        pmapsuffix_t = wx.TextCtrl(self)
        initiatetext(pmapsuffix_t, 'pmapsuffix')
        pmapsuffix_t.Bind(wx.EVT_TEXT, lambda evt,
                            temp='pmapsuffix': OnTextChange(evt, temp))
        pscraps_l = wx.StaticText(self, wx.ID_ANY, 'Number Scraps:')
        self.pscraps_t = wx.lib.intctrl.IntCtrl(self, min=0, max=999,
                                                limited=True, size=(40, -1))
        initiatetext(self.pscraps_t, 'pscraps')
        self.pscraps_t.Bind(wx.lib.intctrl.EVT_INT, lambda evt,
                            temp='pscraps': OnTextChange(evt, temp))
        gridder.Add(addplanmap, pos=(14, 1), span=(1, 2))
        gridder.Add(pmapsuffix_l, pos=(16, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(pmapsuffix_t, pos=(16, 2), span=(1, 2))
        gridder.Add(pscraps_l, pos=(15, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.pscraps_t, (15, 2))

            #Elevation
        addelevmap = wx.CheckBox(self, label='Include Elevation Map')
        initiatecheckbox(addelevmap, 'addelevmap')
        addelevmap.Bind(wx.EVT_CHECKBOX, lambda evt,
                        temp='addelevmap': OnCheckBox(evt, temp))
        emapsuffix_l = wx.StaticText(self, wx.ID_ANY, 'Map Suffix Elevation:')
        emapsuffix_t = wx.TextCtrl(self)
        initiatetext(emapsuffix_t, 'emapsuffix')
        emapsuffix_t.Bind(wx.EVT_TEXT, lambda evt,
                            temp='emapsuffix': OnTextChange(evt, temp))
        escraps_l = wx.StaticText(self, wx.ID_ANY, 'Number of Scraps:')
        self.escraps_t = wx.lib.intctrl.IntCtrl(self,
                                                min=0,
                                                max=999,
                                                limited=True,
                                                size=(40, -1))
        initiatetext(self.escraps_t, 'escraps')
        self.escraps_t.Bind(wx.lib.intctrl.EVT_INT, lambda evt,
                            temp='escraps': OnTextChange(evt, temp))
        gridder.Add(addelevmap, pos=(14, 4), span=(1, 3))
        gridder.Add(emapsuffix_l, pos=(16, 4), span=(1, 2),
                        flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(emapsuffix_t, pos=(16, 6))
        gridder.Add(escraps_l, pos=(15, 4), span=(1, 2),
                        flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.escraps_t, (15, 6))

            #Projected Elevation
        addprojmap = wx.CheckBox(self, label='Include Projection Map')
        initiatecheckbox(addprojmap, 'addprojmap')
        addprojmap.Bind(wx.EVT_CHECKBOX, lambda evt,
                        temp='addprojmap': OnCheckBox(evt, temp))
        pemapsuffix_l = wx.StaticText(self, wx.ID_ANY, 'Map Suffix Elevation:')
        pemapsuffix_t = wx.TextCtrl(self)
        initiatetext(pemapsuffix_t, 'pemapsuffix')
        pemapsuffix_t.Bind(wx.EVT_TEXT, lambda evt,
                            temp='pemapsuffix': OnTextChange(evt, temp))
        pescraps_l = wx.StaticText(self, wx.ID_ANY, 'Number of Scraps:')
        self.pescraps_t = wx.lib.intctrl.IntCtrl(self,
                                                min=0,
                                                max=999,
                                                limited=True,
                                                size=(40, -1))
        initiatetext(self.pescraps_t, 'pescraps')
        self.pescraps_t.Bind(wx.lib.intctrl.EVT_INT, lambda evt,
                            temp='pescraps': OnTextChange(evt, temp))
        pemapangle_l = wx.StaticText(self, wx.ID_ANY,
                                        'Use ### to include angle')
        #pemapsuffixangle = wx.CheckBox(self, label='add the angle')
        #initiatecheckbox(pemapsuffixangle, 'pemapsuffixangle')
        #pemapsuffixangle.Bind(wx.EVT_CHECKBOX, lambda evt,
                        #temp='pemapsuffixangle': OnCheckBox(evt, temp))
        gridder.Add(addprojmap, pos=(14, 7), span=(1, 2))
        gridder.Add(pemapsuffix_l, pos=(16, 7),
                        flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(pemapsuffix_t, pos=(16, 8))
        gridder.Add(pescraps_l, pos=(15, 7),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.pescraps_t, (15, 8))
        gridder.Add(pemapangle_l, (17, 8))

        self.SetSizer(gridder)

    def onchangeorder(self, event):
        dia = OrderChanger(self, 'Data Order', 0, settings['dataorder'])
        dia.ShowModal()
        settings['dataorder'] = dia.elb.GetStrings()
        DO = ""
        for d in settings['dataorder']:
            DO += d + '   '
        self.dataorder.SetLabel(DO)
        dia.Destroy()

    def onchangecavers(self, event):
        #caversframe = CaversFrame(wx.GetApp().TopWindow, settings['caverlist'])
        CaversFrame(wx.GetApp().TopWindow, settings['caverlist'])

    def buildpeoplelist(self, plist):
        for r in rolls:
            cavers[r] = []
        for person in plist:
            for r in rolls:
                if person[r]:
                    cavers[r].append(person['Name'])
        #Make a printable list of up to 40 char
        peoplelist = {}
        for r in rolls:
            peoplelist[r] = ', '.join(cavers[r])
            if len(peoplelist[r]) > 40:
                peoplelist[r] = peoplelist[r][0:32] + ' more...'
        return peoplelist


##############
class TickGrid(wx.grid.Grid):
    def __init__(self, parent, cl):
        wx.grid.Grid.__init__(self, parent, -1, pos=(10, 10), size=(290, 450))

        self.caverlist = cl
        self.CreateGrid(len(self.caverlist), 4)
        self.RowLabelSize = 200
        self.ColLabelSize = 100
        self.DefaultColSize = 20
        self.DefaultEditor = wx.grid.GridCellBoolEditor()
        self.DefaultRenderer = wx.grid.GridCellBoolRenderer()
        self.SetColLabelTextOrientation(wx.VERTICAL)
        self.SetColLabelAlignment(wx.ALIGN_LEFT, wx.ALIGN_CENTER)
        self.SetRowLabelAlignment(wx.ALIGN_LEFT, wx.ALIGN_CENTER)

        for n, rolllabel in enumerate(rolls):
            self.SetColLabelValue(n, rolllabel)
            for m, personjob in enumerate(self.caverlist):
                #Setting the cell to false leads to first click not working!!!!
                if personjob[rolllabel]:
                    self.SetCellValue(m, n, str(int(personjob[rolllabel])))
        for m, personname in enumerate(self.caverlist):
            self.SetRowLabelValue(m, personname['Name'])

        self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.onMouse)
        self.Bind(wx.grid.EVT_GRID_SELECT_CELL, self.onCellSelected)
        self.Bind(wx.grid.EVT_GRID_EDITOR_CREATED, self.onEditorCreated)

    def onMouse(self, evt):
        wx.CallLater(100, self.toggleCheckBox)
        evt.Skip()

    def toggleCheckBox(self):
        self.cb.Value = not self.cb.Value
        self.afterCheckBox(self.cb.Value)

    def onCellSelected(self, evt):
        wx.CallAfter(self.EnableCellEditControl)
        evt.Skip()

    def onEditorCreated(self, evt):
        self.cb = evt.Control
        self.cb.WindowStyle |= wx.WANTS_CHARS
        self.cb.Bind(wx.EVT_KEY_DOWN, self.onKeyDown)
        self.cb.Bind(wx.EVT_CHECKBOX, self.onCheckBox)
        evt.Skip()

    def onKeyDown(self, evt):
        if evt.KeyCode == wx.WXK_UP:
            if self.GridCursorRow > 0:
                self.DisableCellEditControl()
                self.MoveCursorUp(False)
        elif evt.KeyCode == wx.WXK_DOWN:
            if self.GridCursorRow < (self.NumberRows - 1):
                self.DisableCellEditControl()
                self.MoveCursorDown(False)
        elif evt.KeyCode == wx.WXK_LEFT:
            if self.GridCursorCol > 0:
                self.DisableCellEditControl()
                self.MoveCursorLeft(False)
        elif evt.KeyCode == wx.WXK_RIGHT:
            if self.GridCursorCol < (self.NumberCols - 1):
                self.DisableCellEditControl()
                self.MoveCursorRight(False)
        else:
            evt.Skip()

    def onCheckBox(self, evt):
        self.afterCheckBox(evt.IsChecked())

    def afterCheckBox(self, state):
        '''Set the new state of the roll'''
        self.caverlist[self.GridCursorRow][rolls[self.GridCursorCol]] = state
###########


class th2Plan(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        gridder = wx.GridBagSizer(5, 5)

        #intro and whether to do it
        doplan = wx.CheckBox(self, wx.ID_ANY, 'Produce Plan th2 File')
        initiatecheckbox(doplan, 'doplan')
        doplan.Bind(wx.EVT_CHECKBOX, lambda evt,
                    temp='doplan': OnCheckBox(evt, temp))
        introtext = '''Controls the elements of the th2 file to be output'''
        intro_t = wx.StaticText(self, wx.ID_ANY, introtext)
        gridder.Add(intro_t, pos=(0, 1), span=(1, 3))
        gridder.Add(doplan, (1, 1), span=(1, 2))

        plansuffix_l = wx.StaticText(self, wx.ID_ANY, 'th2 Suffix:')
        plansuffix_t = wx.TextCtrl(self)
        initiatetext(plansuffix_t, 'plansuffix')
        plansuffix_t.Bind(wx.EVT_TEXT, lambda evt,
                            temp='plansuffix': OnTextChange(evt, temp))
        gridder.Add(plansuffix_l, pos=(3, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(plansuffix_t, (3, 2))

        #Insert blanks scraps
        ins_pscraps = wx.CheckBox(self, wx.ID_ANY, 'Insert scaled plan scraps')
        initiatecheckbox(ins_pscraps, 'ins_pscraps')
        ins_pscraps.Bind(wx.EVT_CHECKBOX, lambda evt,
                            temp='ins_pscraps': OnCheckBox(evt, temp))
        pscrapsuffix_l = wx.StaticText(self, wx.ID_ANY, 'Plan Scrap Suffix:')
        pscrapsuffix_t = wx.TextCtrl(self)
        initiatetext(pscrapsuffix_t, 'pscrapsuffix')
        pscrapsuffix_t.Bind(wx.EVT_TEXT, lambda evt,
                            temp='pscrapsuffix': OnTextChange(evt, temp))
        pscraps_l = wx.StaticText(self, wx.ID_ANY, 'Number of Plan Scraps:')
        self.pscraps_t = wx.lib.intctrl.IntCtrl(self, min=0, max=999,
                                                limited=True, size=(40, -1))
        self.pscraps_t.ChangeValue(settings['pscraps'])
        self.pscraps_t.Bind(wx.lib.intctrl.EVT_INT, lambda evt,
                            temp='pscraps': OnTextChange(evt, temp))
        gridder.Add(ins_pscraps, pos=(5, 1), span=(1, 2))
        gridder.Add(pscrapsuffix_l, pos=(6, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(pscrapsuffix_t, (6, 2))
        gridder.Add(pscraps_l, pos=(7, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.pscraps_t, (7, 2))

        #Insert Xsection scraps
        ins_pxscraps = wx.CheckBox(self, wx.ID_ANY,
                                    'Insert scaled X-section scraps')
        initiatecheckbox(ins_pxscraps, 'ins_pxscraps')
        ins_pxscraps.Bind(wx.EVT_CHECKBOX, lambda evt,
                            temp='ins_pxscraps': OnCheckBox(evt, temp))
        planxsuffix_l = wx.StaticText(self, wx.ID_ANY, 'Plan X-Section Suffix:')
        planxsuffix_t = wx.TextCtrl(self)
        initiatetext(planxsuffix_t, 'planxsuffix')
        planxsuffix_t.Bind(wx.EVT_TEXT, lambda evt,
                            temp='planxsuffix': OnTextChange(evt, temp))
        planxsuffix_comment = wx.StaticText(self, wx.ID_ANY,
                                    'The station name is added to the suffix')
        gridder.Add(ins_pxscraps, pos=(5, 4), span=(1, 2))
        gridder.Add(planxsuffix_l, pos=(6, 4),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(planxsuffix_t, (6, 5))
        gridder.Add(planxsuffix_comment, (7, 4), span=(1, 2))

        #XVI scale, DPI, grid

        planscale_l = wx.StaticText(self, wx.ID_ANY, 'Scale 1:')
        #must be at least 1 to stop division by zero error
        planscale_t = wx.lib.intctrl.IntCtrl(self,
                                             value=1,
                                             min=1,
                                             max=999,
                                             limited=True,
                                             size=(40, -1))
        initiatetext(planscale_t, 'planscale')
        planscale_t.Bind(wx.lib.intctrl.EVT_INT,
                         lambda evt, temp='planscale': OnTextChange(evt, temp))
        planDPI_l = wx.StaticText(self, wx.ID_ANY, 'DPI:')
        #must be at least 1 to stop division by zero error
        planDPI_t = wx.lib.intctrl.IntCtrl(self,
                                           value=1,
                                           min=1,
                                           max=999,
                                           limited=True,
                                           size=(40, -1))
        initiatetext(planDPI_t, 'planDPI')
        planDPI_t.Bind(wx.lib.intctrl.EVT_INT,
                       lambda evt, temp='planDPI': OnTextChange(evt, temp))
        plangrid_l = wx.StaticText(self, wx.ID_ANY, 'Grid Size (metres):')
        plangrid_t = wx.lib.masked.NumCtrl(
                                    self,
                                    integerWidth=3,
                                    fractionWidth=1,
                                    allowNegative=False)
        initiatetext(plangrid_t, 'plangrid')
        plangrid_t.Bind(wx.lib.masked.EVT_NUM, lambda evt,
                        temp='plangrid': OnTextChange(evt, temp))
        gridder.Add(planscale_l, pos=(9, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(planscale_t, (9, 2))
        gridder.Add(planDPI_l, pos=(9, 3),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(planDPI_t, (9, 4))
        gridder.Add(plangrid_l, pos=(9, 5),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(plangrid_t, (9, 6))

        self.SetSizer(gridder)


class th2Elevation(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        gridder = wx.GridBagSizer(5, 5)

        #intro and whether to do it
        doelevation = wx.CheckBox(self, wx.ID_ANY,
                                    'Produce extended elevation th2 file')
        initiatecheckbox(doelevation, 'doelevation')
        doelevation.Bind(wx.EVT_CHECKBOX, lambda evt,
                            temp='doelevation': OnCheckBox(evt, temp))

        introtext = '''Controls the elements of the th2 file to be output'''
        intro_t = wx.StaticText(self, wx.ID_ANY, introtext)
        gridder.Add(intro_t, pos=(0, 1), span=(1, 3))
        gridder.Add(doelevation, (1, 1), span=(1, 2))

        elevsuffix_l = wx.StaticText(self, wx.ID_ANY, 'th2 Suffix:')
        elevsuffix_t = wx.TextCtrl(self)
        initiatetext(elevsuffix_t, 'elevsuffix')
        elevsuffix_t.Bind(wx.EVT_TEXT, lambda evt,
                            temp='elevsuffix': OnTextChange(evt, temp))
        gridder.Add(elevsuffix_l, pos=(3, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(elevsuffix_t, (3, 2))

        #Insert blanks scraps
        ins_escraps = wx.CheckBox(self, wx.ID_ANY,
                                    'Insert scaled Elevation scraps')
        initiatecheckbox(ins_escraps, 'ins_escraps')
        ins_escraps.Bind(wx.EVT_CHECKBOX, lambda evt,
                         temp='ins_escraps': OnCheckBox(evt, temp))
        escrapsuffix_l = wx.StaticText(self, wx.ID_ANY,
                                        'Elevation Scrap Suffix:')
        escrapsuffix_t = wx.TextCtrl(self)
        initiatetext(escrapsuffix_t, 'escrapsuffix')
        escrapsuffix_t.Bind(wx.EVT_TEXT, lambda evt,
                            temp='escrapsuffix': OnTextChange(evt, temp))
        escraps_l = wx.StaticText(self, wx.ID_ANY,
                                    'Number of Elevation Scraps:')
        self.escraps_t = wx.lib.intctrl.IntCtrl(self, min=0, max=999,
                                                limited=True, size=(40, -1))
        self.escraps_t.ChangeValue((settings['escraps']))
        self.escraps_t.Bind(wx.lib.intctrl.EVT_INT, lambda evt,
                            temp='escraps': OnTextChange(evt, temp))
        gridder.Add(ins_escraps, pos=(5, 1), span=(1, 2))
        gridder.Add(escrapsuffix_l, pos=(6, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(escrapsuffix_t, (6, 2))
        gridder.Add(escraps_l, pos=(7, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.escraps_t, (7, 2))

        #Insert Xsection scraps
        ins_exscraps = wx.CheckBox(self, wx.ID_ANY,
                                    'Insert scaled X-section scraps')
        initiatecheckbox(ins_exscraps, 'ins_exscraps')
        ins_exscraps.Bind(wx.EVT_CHECKBOX, lambda evt,
                          temp='ins_exscraps': OnCheckBox(evt, temp))
        elevpxsuffix_l = wx.StaticText(self, wx.ID_ANY,
                                        'Plan X-Section Suffix:')
        elevpxsuffix_t = wx.TextCtrl(self)
        initiatetext(elevpxsuffix_t, 'elevpxsuffix')
        elevpxsuffix_t.Bind(wx.EVT_TEXT, lambda evt,
                            temp='elevpxsuffix': OnTextChange(evt, temp))
        elevvxsuffix_l = wx.StaticText(self, wx.ID_ANY,
                                        'Verticall X-Section Suffix:')
        elevvxsuffix_t = wx.TextCtrl(self)
        initiatetext(elevvxsuffix_t, 'elevvxsuffix')
        elevvxsuffix_t.Bind(wx.EVT_TEXT, lambda evt,
                            temp='elevvxsuffix': OnTextChange(evt, temp))
        gridder.Add(ins_exscraps, pos=(5, 4), span=(1, 2))
        gridder.Add(elevpxsuffix_l, pos=(6, 4),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(elevpxsuffix_t, (6, 5))
        gridder.Add(elevvxsuffix_l, pos=(7, 4),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(elevvxsuffix_t, (7, 5))

        #XVI scale, DPI, grid

        elevscale_l = wx.StaticText(self, wx.ID_ANY, 'Scale 1:')
        #must be at least 1 to stop division by zero error
        elevscale_t = wx.lib.intctrl.IntCtrl(self,
                                             value=1,
                                             min=1,
                                             max=999,
                                             limited=True,
                                             size=(40, -1))
        initiatetext(elevscale_t, 'elevscale')
        elevscale_t.Bind(wx.lib.intctrl.EVT_INT,
                         lambda evt, temp='elevscale': OnTextChange(evt, temp))
        elevDPI_l = wx.StaticText(self, wx.ID_ANY, 'DPI:')
        #must be at least 1 to stop division by zero error
        elevDPI_t = wx.lib.intctrl.IntCtrl(self,
                                            value=1,
                                            min=1,
                                            max=999,
                                            limited=True,
                                            size=(40, -1))
        initiatetext(elevDPI_t, 'elevDPI')
        elevDPI_t.Bind(wx.lib.intctrl.EVT_INT,
                       lambda evt, temp='elevDPI': OnTextChange(evt, temp))
        elevgrid_l = wx.StaticText(self, wx.ID_ANY, 'Grid Size (metres):')
        elevgrid_t = wx.lib.masked.NumCtrl(self,
                                        integerWidth=3,
                                        fractionWidth=1,
                                        allowNegative=False)
        initiatetext(elevgrid_t, 'elevgrid')
        elevgrid_t.Bind(wx.lib.masked.EVT_NUM, lambda evt,
                        temp='elevgrid': OnTextChange(evt, temp))
        gridder.Add(elevscale_l, pos=(9, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(elevscale_t, (9, 2))
        gridder.Add(elevDPI_l, pos=(9, 3),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(elevDPI_t, (9, 4))
        gridder.Add(elevgrid_l, pos=(9, 5),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(elevgrid_t, (9, 6))

        self.SetSizer(gridder)
########################################################


class th2Projected(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        gridder = wx.GridBagSizer(5, 5)

        #intro and whether to do it
        doprojection = wx.CheckBox(self, wx.ID_ANY,
                                    'Produce projected elevation th2 file')
        initiatecheckbox(doprojection, 'doprojection')
        doprojection.Bind(wx.EVT_CHECKBOX, lambda evt,
                            temp='doprojection': OnCheckBox(evt, temp))

        introtext = '''Imports the legs and stations as a projected Elevation'''
        intro_t = wx.StaticText(self, wx.ID_ANY, introtext)

        projangle_l = wx.StaticText(self, wx.ID_ANY,
                                    'Looking Towards (degrees):')
        self.projangle_t = wx.lib.intctrl.IntCtrl(self,
                                                 min=0,
                                                 max=359,
                                                 limited=True,
                                                 name="Number of Scraps",
                                                 size=(40, -1))
        try:
            self.projangle_t.ChangeValue((settings['projangle']))
        except:
            self.projangle_t.ChangeValue((D.projangle))
            (settings['projangle']) = D.projangle
        self.projangle_t.Bind(wx.lib.intctrl.EVT_INT, lambda evt,
                            temp='projangle': OnTextChange(evt, temp))

        projsuffix_l = wx.StaticText(self, wx.ID_ANY, 'th2 Suffix:')
        projsuffix_t = wx.TextCtrl(self)
        initiatetext(projsuffix_t, 'projsuffix')
        projsuffix_t.Bind(wx.EVT_TEXT, lambda evt,
                            temp='projsuffix': OnTextChange(evt, temp))
        projaddangle_l = wx.StaticText(self, wx.ID_ANY,
                                        'Use ### to include the angle')
        #anglesuffixfile = wx.CheckBox(self, wx.ID_ANY, 'add the angle')
        #initiatecheckbox(anglesuffixfile, 'anglesuffixfile')
        #anglesuffixfile.Bind(wx.EVT_CHECKBOX, lambda evt,
                         #temp='anglesuffixfile': OnCheckBox(evt, temp))

        #Insert blanks scraps
        ins_pescraps = wx.CheckBox(self, wx.ID_ANY,
                                    'Insert scaled Projected Elevation scraps')
        initiatecheckbox(ins_pescraps, 'ins_pescraps')
        ins_pescraps.Bind(wx.EVT_CHECKBOX, lambda evt,
                         temp='ins_pescraps': OnCheckBox(evt, temp))
        pescrapsuffix_l = wx.StaticText(self, wx.ID_ANY,
                                        'Projected Elevation Scrap Suffix:')
        pescrapsuffix_t = wx.TextCtrl(self)
        initiatetext(pescrapsuffix_t, 'pescrapsuffix')
        pescrapsuffix_t.Bind(wx.EVT_TEXT, lambda evt,
                            temp='pescrapsuffix': OnTextChange(evt, temp))
        pescraps_l = wx.StaticText(self, wx.ID_ANY,
                                    'Number of Projected Elevation Scraps:')
        self.pescraps_t = wx.lib.intctrl.IntCtrl(self,
                                                 min=0,
                                                 max=999,
                                                 limited=True,
                                                 name="Number of Scraps",
                                                 size=(40, -1))
        try:
            self.pescraps_t.ChangeValue((settings['pescraps']))
        except:
            self.pescraps_t.ChangeValue('1')
        self.pescraps_t.Bind(wx.lib.intctrl.EVT_INT, lambda evt,
                            temp='pescraps': OnTextChange(evt, temp))
        scrapaddangle_l = wx.StaticText(self, wx.ID_ANY,
                                        'Use ### to include the angle')

        #anglesuffixscrap = wx.CheckBox(self, wx.ID_ANY, 'add the angle')
        #initiatecheckbox(anglesuffixscrap, 'anglesuffixscrap')
        #anglesuffixscrap.Bind(wx.EVT_CHECKBOX, lambda evt,
                         #temp='anglesuffixscrap': OnCheckBox(evt, temp))

        #XVI scale, DPI, grid
        projscale_l = wx.StaticText(self, wx.ID_ANY, 'Scale 1:')
        #must be at least 1 to stop division by zero error

        projscale_t = wx.lib.intctrl.IntCtrl(
                                    self,
                                    value=100,
                                    min=1,
                                    max=999,
                                    limited=True,
                                    size=(40, -1))
        initiatetext(projscale_t, 'projscale')
        projscale_t.Bind(wx.lib.intctrl.EVT_INT,
                       lambda evt, temp='projscale': OnTextChange(evt, temp))
        projDPI_l = wx.StaticText(self, wx.ID_ANY, 'DPI:')
        #must be at least 1 to stop division by zero error
        projDPI_t = wx.lib.intctrl.IntCtrl(
                                        self,
                                        value=200,
                                        min=1,
                                        max=999,
                                        limited=True,
                                        size=(40, -1))
        initiatetext(projDPI_t, 'projDPI')
        projDPI_t.Bind(wx.lib.intctrl.EVT_INT,
                       lambda evt, temp='projDPI': OnTextChange(evt, temp))

        projgrid_l = wx.StaticText(self, wx.ID_ANY, 'Grid Size (metres):')
        projgrid_t = wx.lib.masked.NumCtrl(
                                    self,
                                    value=1,
                                    integerWidth=3,
                                    fractionWidth=1,
                                    allowNegative=False)
        initiatetext(projgrid_t, 'projgrid')
        projgrid_t.Bind(wx.lib.intctrl.EVT_INT,
                       lambda evt, temp='projgrid': OnTextChange(evt, temp))

        gridder.Add(intro_t, pos=(0, 1), span=(1, 3))
        gridder.Add(doprojection, (1, 1), span=(1, 2))
        gridder.Add(projangle_l, (3, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.projangle_t, (3, 2), span=(1, 2))
        gridder.Add(projaddangle_l, (4, 3), span=(1, 2))
        gridder.Add(projsuffix_l, pos=(4, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(projsuffix_t, (4, 2))
        gridder.Add(ins_pescraps, pos=(6, 1), span=(1, 2))
        gridder.Add(pescrapsuffix_l, pos=(7, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(pescrapsuffix_t, (7, 2))
        gridder.Add(scrapaddangle_l, (7, 3))
        gridder.Add(pescraps_l, pos=(8, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.pescraps_t, (8, 2))
        gridder.Add(projscale_l, pos=(10, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(projscale_t, (10, 2))
        gridder.Add(projDPI_l, pos=(10, 3),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(projDPI_t, (10, 4))
        gridder.Add(projgrid_l, pos=(10, 5),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(projgrid_t, (10, 6))

        self.SetSizer(gridder)
########################################################


class thconfig(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        panelbox = wx.BoxSizer(wx.VERTICAL)
        layoutbox = wx.GridBagSizer(5, 5)
        dothconfig = wx.CheckBox(self, wx.ID_ANY, label='Produce thconfig File')
        initiatecheckbox(dothconfig, 'dothconfig')
        dothconfig.Bind(wx.EVT_CHECKBOX, lambda evt,
                        temp='dothconfig': OnCheckBox(evt, temp))
        introtext = '''Controls the elements of the thconfig file to output'''
        intro_t = wx.StaticText(self, label=introtext)
        #Layout location
        layout_l = wx.StaticText(self, label='Layout File:')
        self.layout_t = wx.TextCtrl(self)
        initiatetext(self.layout_t, 'layout')
        self.layout_t.Bind(wx.EVT_TEXT, lambda evt,
                            temp='layout': OnTextChange(evt, temp))
        layout_b = wx.Button(self, label='Browse...')
        layout_b.Bind(wx.EVT_BUTTON, self.layout)
        layoutbox.Add(layout_l, pos=(0, 0),
                        flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        layoutbox.Add(self.layout_t, pos=(0, 1), span=(1, 2), flag=wx.EXPAND)
        layoutbox.Add(layout_b, pos=(0, 3))
        #thconfig file name
        cofigname_l = wx.StaticText(self, label='Config file name: ')
        cofigname_t = wx.TextCtrl(self)
        initiatetext(cofigname_t, 'configname')
        cofigname_t.Bind(wx.EVT_TEXT, lambda evt,
                            temp='configname': OnTextChange(evt, temp))
        layoutbox.Add(cofigname_l, pos=(1, 0),
                        flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        layoutbox.Add(cofigname_t, pos=(1, 1))
        layoutbox.AddGrowableCol(2)
        #thconfig text editor
        thconfigintro = '''Write the standard config below, using the following wildcards
    ##NAME## = name of the top file
    ##LAYOUT## = the layoutfile indicated above
'''
        thconfig_l = wx.StaticText(self, wx.ID_ANY, thconfigintro)
        thconfig_t = wx.TextCtrl(self, style=wx.TE_MULTILINE)
        initiatetext(thconfig_t, 'thconfigtext')
        thconfig_t.Bind(wx.EVT_TEXT, lambda evt,
                        temp='thconfigtext': OnTextChange(evt, temp))
        panelbox.Add(intro_t)
        panelbox.Add(dothconfig)
        panelbox.Add(layoutbox, flag=wx.EXPAND)
        panelbox.Add(thconfig_l)
        panelbox.Add(thconfig_t, flag=wx.EXPAND, proportion=1)
        self.SetSizer(panelbox)

    def layout(self, event):
        #print(settings['layout'])
        layout = os.path.join(settings['projectroot'], settings['layout'])
        if os.path.exists(os.path.dirname(layout)):
            dp = os.path.dirname(layout)
        elif os.path.exists(settings['projectroot']):
            dp = settings['projectroot']
        else:
            dp = ''
        dlg = wx.FileDialog(self, "Select the layout File:",
                            wildcard='th files (*.th)|*.th|txt files (*.txt)|*.txt|All files|*',
                            defaultDir=dp,
                            style=wx.DD_DEFAULT_STYLE)
        if dlg.ShowModal() == wx.ID_OK:
            settings['layout'] = os.path.relpath(dlg.GetPath(),
                                                    settings['projectroot'])
            self.layout_t.SetValue(settings['layout'])
        dlg.Destroy()
        return


class variables(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        #get the variables

        self.var = Defaults.variables()

        gridder = wx.GridBagSizer(5, 4)

        introtext = '''Sets the method of running the parts of survex and therion
The examples given are probably the defaults, but mileage may vary.'''
        intro_t = wx.StaticText(self, wx.ID_ANY, introtext)
        gridder.Add(intro_t, pos=(1, 1), span=(1, 5))

        xtherion_l = wx.StaticText(self, wx.ID_ANY, 'Therion GUI (xtherion)')
        self.xtherion_t = wx.TextCtrl(self)
        initiatetext(self.xtherion_t, 'xtherion')
        self.xtherion_t.Bind(wx.EVT_TEXT, lambda evt,
                                temp='xtherion': OnTextChange(evt, temp))
        xtherion_ll = wx.StaticText(self, wx.ID_ANY, 'Linux: ')
        xtherion_wl = wx.StaticText(self, wx.ID_ANY, 'Windows: ')
        xtherion_linux = wx.StaticText(self, wx.ID_ANY,
                                        self.var['xtherion_linux'])
        xtherion_win = wx.StaticText(self, wx.ID_ANY, self.var['xtherion_win'])
        gridder.Add(xtherion_l, pos=(3, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.xtherion_t, pos=(3, 2), span=(1, 5),
                    flag=wx.EXPAND)
        gridder.Add(xtherion_ll, pos=(4, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(xtherion_linux, pos=(4, 2),
                    flag=wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(xtherion_wl, pos=(4, 4),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(xtherion_win, pos=(4, 5),
                    flag=wx.ALIGN_CENTER_VERTICAL)

        therion_l = wx.StaticText(self, wx.ID_ANY, 'Therion')
        self.therion_t = wx.TextCtrl(self)
        initiatetext(self.therion_t, 'therion')
        self.therion_t.Bind(wx.EVT_TEXT, lambda evt,
                            temp='therion': OnTextChange(evt, temp))
        therion_ll = wx.StaticText(self, wx.ID_ANY, 'Linux: ')
        therion_wl = wx.StaticText(self, wx.ID_ANY, 'Windows: ')
        therion_linux = wx.StaticText(self, wx.ID_ANY,
                                        self.var['therion_linux'])
        therion_win = wx.StaticText(self, wx.ID_ANY, self.var['therion_win'])
        gridder.Add(therion_l, pos=(5, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.therion_t, pos=(5, 2), span=(1, 5),
                    flag=wx.EXPAND)
        gridder.Add(therion_ll, pos=(6, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(therion_linux, pos=(6, 2),
                    flag=wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(therion_wl, pos=(6, 4),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(therion_win, pos=(6, 5), flag=wx.ALIGN_CENTER_VERTICAL)

        loch_l = wx.StaticText(self, wx.ID_ANY, 'loch')
        self.loch_t = wx.TextCtrl(self)
        initiatetext(self.loch_t, 'loch')
        self.loch_t.Bind(wx.EVT_TEXT, lambda evt,
                            temp='loch': OnTextChange(evt, temp))
        loch_ll = wx.StaticText(self, wx.ID_ANY, 'Linux: ')
        loch_wl = wx.StaticText(self, wx.ID_ANY, 'Windows: ')
        loch_linux = wx.StaticText(self, wx.ID_ANY, self.var['loch_linux'])
        loch_win = wx.StaticText(self, wx.ID_ANY, self.var['loch_win'])
        gridder.Add(loch_l, pos=(7, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.loch_t, pos=(7, 2), span=(1, 5),
                    flag=wx.EXPAND)
        gridder.Add(loch_ll, pos=(8, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(loch_linux, pos=(8, 2),
                    flag=wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(loch_wl, pos=(8, 4),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(loch_win, pos=(8, 5),
                    flag=wx.ALIGN_CENTER_VERTICAL)

        aven_l = wx.StaticText(self, wx.ID_ANY, 'aven')
        self.aven_t = wx.TextCtrl(self)
        initiatetext(self.aven_t, 'aven')
        self.aven_t.Bind(wx.EVT_TEXT, lambda evt,
                            temp='aven': OnTextChange(evt, temp))
        aven_ll = wx.StaticText(self, wx.ID_ANY, 'Linux: ')
        aven_wl = wx.StaticText(self, wx.ID_ANY, 'Windows: ')
        aven_linux = wx.StaticText(self, wx.ID_ANY, self.var['aven_linux'])
        aven_win = wx.StaticText(self, wx.ID_ANY, self.var['aven_win'])
        gridder.Add(aven_l, pos=(9, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.aven_t, pos=(9, 2), span=(1, 5), flag=wx.EXPAND)
        gridder.Add(aven_ll, pos=(10, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(aven_linux, pos=(10, 2),
                    flag=wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(aven_wl, pos=(10, 4),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(aven_win, pos=(10, 5), flag=wx.ALIGN_CENTER_VERTICAL)

        cavern_l = wx.StaticText(self, wx.ID_ANY, 'cavern')
        self.cavern_t = wx.TextCtrl(self)
        initiatetext(self.cavern_t, 'cavern')
        self.cavern_t.Bind(wx.EVT_TEXT, lambda evt,
                            temp='cavern': OnTextChange(evt, temp))
        cavern_ll = wx.StaticText(self, wx.ID_ANY, 'Linux: ')
        cavern_wl = wx.StaticText(self, wx.ID_ANY, 'Windows: ')
        cavern_linux = wx.StaticText(self, wx.ID_ANY, self.var['cavern_linux'])
        cavern_win = wx.StaticText(self, wx.ID_ANY, self.var['cavern_win'])
        gridder.Add(cavern_l, pos=(11, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(self.cavern_t, pos=(11, 2), span=(1, 5),
                    flag=wx.EXPAND)
        gridder.Add(cavern_ll, pos=(12, 1),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(cavern_linux, pos=(12, 2),
                    flag=wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(cavern_wl, pos=(12, 4),
                    flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(cavern_win, pos=(12, 5),
                    flag=wx.ALIGN_CENTER_VERTICAL)

        linux_b = wx.Button(self, label='Set to Linux')
        linux_b.Bind(wx.EVT_BUTTON, lambda evt,
                        temp='linux': self.setOS(evt, temp))
        win_b = wx.Button(self, label='Set to Windows')
        win_b.Bind(wx.EVT_BUTTON, lambda evt, temp='win': self.setOS(evt, temp))

        gridder.Add(linux_b, pos=(14, 2), flag=wx.ALIGN_CENTER_VERTICAL)
        gridder.Add(win_b, pos=(14, 5), flag=wx.ALIGN_CENTER_VERTICAL)

        self.SetSizer(gridder)

    def setOS(self, event, OS):
        self.xtherion_t.SetValue(self.var['xtherion_' + OS])
        self.therion_t.SetValue(self.var['therion_' + OS])
        self.loch_t.SetValue(self.var['loch_' + OS])
        self.aven_t.SetValue(self.var['aven_' + OS])
        self.cavern_t.SetValue(self.var['cavern_' + OS])


class OrderChanger(wx.Dialog):
    def __init__(self, parent, title, style, list):
        wx.Dialog.__init__(self, parent, title=title)
        self.elb = wx.gizmos.EditableListBox(self, label="Edit order",
                                             size=(350, 300), style=style)
                #style=wx.EL_ALLOW_NEW | wx.EL_ALLOW_EDIT | wx.EL_ALLOW_DELETE)
        self.elb.SetStrings(list)


class NameChanger(wx.Dialog):

    def __init__(self):
        wx.Dialog.__init__(self)


#############
class CaversFrame(wx.Dialog):
    def __init__(self, parent, caverlist):
        wx.Dialog.__init__(self, parent, -1, "Caver Rolls", size=(500, 500))
        self.c = caverlist
        self.tmplist = []
        for per in self.c:
            self.tmplist.append(dict(per))

        vbox = wx.BoxSizer(wx.HORIZONTAL)
        box1 = wx.BoxSizer(wx.VERTICAL)
        tg = TickGrid(self, self.c)
        box1.Add(tg, proportion=1, flag=wx.EXPAND)
        vbox.Add(box1, proportion=1, border=10)
        box2 = wx.BoxSizer(wx.VERTICAL)
        btnadd = wx.Button(self, label='Add/Delete', size=(110, 30))
        btnadd.Bind(wx.EVT_BUTTON, self.caveradd)
        box2.Add(btnadd)
        box2.Add((-1, 100))
        btncancel = wx.Button(self, wx.ID_CANCEL, size=(110, 30))
        btncancel.Bind(wx.EVT_BUTTON, self.OnCancel)
        box2.Add(btncancel)
        btnquit = wx.Button(self, wx.ID_APPLY, size=(110, 30))
        btnquit.Bind(wx.EVT_BUTTON, self.onapply)
        box2.Add(btnquit)

        vbox.Add(box2)

        self.SetSizer(vbox)
        self.ShowModal()

    def onapply(self, event):
        pl = convertpt.data.buildpeoplelist(self.c)
        convertpt.data.notes_p.SetLabel(pl['Notes'])
        convertpt.data.inst_p.SetLabel(pl['Instruments'])
        convertpt.data.dog_p.SetLabel(pl['Dog'])
        convertpt.data.explorpeople_p.SetLabel(pl['Explorer'])
        settings['caverlist'] = self.c
        self.Destroy()

    def OnCancel(self, event):
        settings['caverlist'] = list(self.tmplist)
        self.Destroy()

    def caveradd(self, event):
        #list = []
        people = []
        for n in (self.c):
            #list.append(n['Name'])
            people.append(n['Name'])
        c = OrderChanger(self, 'Cavers',
                            wx.gizmos.EL_ALLOW_NEW | wx.gizmos.EL_ALLOW_DELETE
                            | wx.gizmos.EL_ALLOW_EDIT,
                            people)
        #c = OrderChanger(self, 'Cavers',
                            #wx.gizmos.EL_ALLOW_NEW | wx.gizmos.EL_ALLOW_DELETE
                            #| wx.gizmos.EL_ALLOW_EDIT,
                            #list)
        c.ShowModal()
        cavernameorder = c.elb.GetStrings()
        name_indexer = dict((p['Name'], i) for i, p in enumerate(self.c))
        caverswithrolls = []
        for cn in cavernameorder:
            try:
                ind = name_indexer[cn]
                caverswithrolls.append(self.c[ind])
            except:
                caverswithrolls.append({'Name': cn,
                                        'Notes': False,
                                        'Instruments': False,
                                        'Dog': False,
                                        'Explorer': False})
        settings['caverlist'] = caverswithrolls
        self.Destroy()
        convertpt.data.onchangecavers(self)


class TabbedMain(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(800, 600))

        favicon = wx.Icon(Defaults.ProgramInfo().icon, wx.BITMAP_TYPE_ICO)
        wx.Frame.SetIcon(self, favicon)

        #Menubar
        menubar = wx.MenuBar()
        filem = wx.Menu()
        filem.Append(wx.ID_ANY, 'Quit', '')
        menubar.Append(filem, '&File')
        self.Bind(wx.EVT_MENU, self.OnQuit)

        helpm = wx.Menu()
        helpm.Append(wx.ID_ANY, '&About')
        menubar.Append(helpm, '&Help')
        self.Bind(wx.EVT_MENU, self.OnAboutBox)
        self.SetMenuBar(menubar)

        #Split frame vertically to get tabs with ButtonBar below
        mframe = wx.BoxSizer(wx.VERTICAL)

        #Add in the tabs
        tabs = wx.Notebook(self)
        self.filelocation = FStructure(tabs)
        self.data = thFile(tabs)
        self.plan = th2Plan(tabs)
        self.elevation = th2Elevation(tabs)
        self.projected = th2Projected(tabs)
        self.config = thconfig(tabs)
        self.variables = variables(tabs)

        tabs.AddPage(self.filelocation, 'Files')
        tabs.AddPage(self.data, 'Data')
        tabs.AddPage(self.plan, 'Plan')
        tabs.AddPage(self.elevation, 'Extended Elevation')
        tabs.AddPage(self.projected, 'Projected Elevation')
        tabs.AddPage(self.config, 'thconfig')
        tabs.AddPage(self.variables, 'Variables')

        #Buttons under tabbed windows to show all the time
        leave = wx.Button(self, wx.ID_EXIT)
        defaults = wx.Button(self, label='Save as Defaults')
        run = wx.Button(self, label='Run')
        #Arrange buttons horizontally, quit on left, config and run right
        buttonbox = wx.GridBagSizer(5, 5)
        buttonbox.Add(leave, pos=(0, 0))
        buttonbox.Add(defaults, pos=(0, 2))
        buttonbox.Add(run, pos=(0, 3))
        buttonbox.AddGrowableCol(1)
        #Events for buttons
        leave.Bind(wx.EVT_BUTTON, self.OnQuit)

        defaults.Bind(wx.EVT_BUTTON, self.OnDefaults)
        #run.Bind (wx.EVT_BUTTON, OnRun.Run(settings))
        run.Bind(wx.EVT_BUTTON, self.OnRun)

        mframe.Add(tabs, wx.ID_ANY, wx.EXPAND | wx.ALL, 5)
        mframe.Add(buttonbox, flag=wx.EXPAND)

        self.SetSizer(mframe)

        self.Centre()
        self.Show(True)

    def OnQuit(self, event):
        self.Close()

    def OnAboutBox(self, e):
        try:
            from wx import adv
        except ImportError:
            adv = wx

        info = Defaults.ProgramInfo()
        dialoginfo = adv.AboutDialogInfo()
        dialoginfo.SetIcon(wx.Icon(info.icon, wx.BITMAP_TYPE_ICO))
        dialoginfo.SetName(info.name)
        dialoginfo.SetVersion(info.version)
        dialoginfo.SetDescription(info.description)
        dialoginfo.SetCopyright(info.copyright)
        dialoginfo.SetWebSite(info.website)
        dialoginfo.SetLicence(info.licence)
        dialoginfo.AddDeveloper(info.developer)
        dialoginfo.AddDocWriter(info.docwriter)
##        dialoginfo.AddArtist('')
##        dialoginfo.AddTranslator('')

        adv.AboutBox(dialoginfo)

    def OnDefaults(self, event):
        pickle.dump(settings, open(os.path.expanduser("~/.Ttop"), "wb"))
        return

    def OnRun(self, event):
        """Call the different parts to do the work"""
        Process.Run(settings, cavers)
        return


def OnRadioButton(event, radiobutton):
    if radiobutton in ['aven', 'loch']:
        settings['viewer'] = radiobutton
    elif radiobutton in ['xplan', 'xelev']:
        settings['th2edit'] = radiobutton
    elif radiobutton in ['svn', 'hg', 'git']:
        settings['repository'] = radiobutton
    elif radiobutton in ['explodateastrip', 'explodateother']:
        if radiobutton == 'explodateastrip':
            settings['samedate'] = True
        else:
            settings['samedate'] = False


def OnCheckBox(event, CheckBox):
    settings[CheckBox] = event.IsChecked()


def OnTextChange(event, TextCtrlName):
    '''When a text box is changed, set the Associated Variable'''
    try:
        settings[TextCtrlName] = event.GetValue()
        #number of plan and elevation scraps appear on 2 pages each,
        #so update both fields
        #Currently also updates the field you are typing in -
        #does this cause problems?
        if TextCtrlName == 'pscraps':
            convertpt.data.pscraps_t.ChangeValue((settings['pscraps']))
            convertpt.plan.pscraps_t.ChangeValue((settings['pscraps']))
        elif TextCtrlName == 'escraps':
            convertpt.data.escraps_t.ChangeValue((settings['escraps']))
            convertpt.elevation.escraps_t.ChangeValue((settings['escraps']))
        elif TextCtrlName == 'pescraps':
            convertpt.data.pescraps_t.ChangeValue((settings['pescraps']))
            convertpt.projected.pescraps_t.ChangeValue((settings['pescraps']))
    except:
        settings[TextCtrlName] = event.GetString()


def initiatecheckbox(field, value):
    try:
        field.SetValue(settings[value])
    except:
        field.SetValue(getattr(D, value))
        settings[value] = getattr(D, value)


def initiatetext(field, value):
    '''Fills in the value and binds to function to detect change'''
    try:
        field.ChangeValue((settings[value]))
    except:
        field.ChangeValue((getattr(D, value)))
        settings[value] = getattr(D, value)


# Load personal setting if they exist or get defaults
try:
    settings = pickle.load(open(os.path.expanduser("~/.Ttop"), "rb"))
except:
    settings = {}


rolls = 'Notes', 'Instruments', 'Dog', 'Explorer'
cavers = {'Notes': [], 'Instruments': [], 'Dog': [], 'Explorer': []}
D = Defaults.Defaults()

app = wx.App(redirect=True, filename=None)
#app = wx.App(redirect=False, filename=None)
#app.RedirectStdio(filename=None)
convertpt = TabbedMain(None, 'Converting top file to Therion')

#import wx.lib.inspection
#wx.lib.inspection.InspectionTool().Show()

app.MainLoop()
