#!/usr/bin/env python

from tkFileDialog import *
from Tkinter import *
from   tkSimpleDialog import Dialog
import tkMessageBox
from plotAscii import *
from imageUtil import * 
from view2d import *
from mdaAscii import *

import Pmw
import os, string
import AppShell

global Scan
global SH  # SHARED

class setupPrinter(Dialog):
   "Dialog for setting up printer "
   def body(self,master):

      self.title("Set Printer Dialog")
      Label(master, text='Enter Printer Name:').grid(row=1, sticky=W)
      self.label = StringVar()
      self.label = Entry(master, width = 26 )
      self.label.grid(row=1,column=1)   
      self.label.insert(0,SH['printer'])
      return self.label

   def apply(self):
	SH['printer'] = self.label.get()
	writeSH(SH)

class commandSyntax(Dialog):
   "Dialog for sending a system command or any executable client"
   def body(self,master):

      self.title("Command Dialog")
      self.commandsyntax = Pmw.EntryField(master, labelpos='w',
	label_text='Enter Command:', value='',
	command=self.valuechanged)
      self.commandsyntax.pack(fill='x')
      self.commandsyntax.component('entry').focus_set()

   def valuechanged(self):
	os.system(self.commandsyntax.get()+ ' &')

   def apply(self):
	self.destroy()

class pickDIdialog(Dialog):
   "Dialog for selecting a text line which contains DI names to be used in multiline plot. If blank comment line picked, sequence number is used."
   def body(self,master):

      file = Scan['txtfile']
      data = readArray(file)
      nc = len(data[0])
      self.nc = nc
      fo = open(file,'r')
      lines = fo.read()
      fo.close()
      lines = string.split(lines,'\n')
      self.title("Pick Line where DI Names Resides")
      box = Pmw.ScrolledListBox(master,
	items=(lines),
	labelpos=NW,label_font=SH['font'],
	label_text='Extract column legends from the text window\nSelect the text line which contains\nlegends to be extracted for multi-line plot',
	selectioncommand=self.selectionCommand,
	dblclickcommand=self.selectionCommand,
	usehullsize=1,hull_width=700,hull_height=400)
      box.pack()
      self.box = box

   def selectionCommand(self):
	box = self.box
        sels = box.getcurselection()
        sels = string.split(sels[0])
	no = len(sels)
	dc = no - self.nc
	if dc >= 0:
	  sels = sels[dc:no]
	  ix = SH['ix']
	  sel = sels[ix+1:no]
	else:
	  sel = range(self.nc)
	V = []
	for i in range(85):
	   V.append('')
	for i in range(len(sel)):
	  	V[i] = sel[i]
	fo = open('pvs','w')
	fo.write(str(V))
	fo.close()
	Scan['nc'] = len(V)
	namedialog = GetLegends(self)

   def apply(self):
	self.destroy()

class GetXYVdialog(Dialog):
    "Dialog to set column or line # of X, Y, DATA array located in the opend ascii 2D image file (generated by scanSee/catcher/yviewer)"
    def body(self,master):
      try:
	font=SH['font'] #'Verdana 10 bold'
        self.title("Extract X,Y,DATA array from scanSee ASCII file")
	self.ix = [IntVar(),IntVar(),IntVar(),IntVar()]
	Label(master,text='X and Data column #:',font=font).grid(row=0,column=0,sticky=W)
	Label(master,text='X Vector Column #').grid(row=1,column=1,sticky=W)
	Label(master,text='Data Start Column #').grid(row=2,column=1,sticky=W)

	Label(master,text='Y Vector Defined in:',font=font).grid(row=3,column=0,sticky=W)
	Label(master,text='Y Vector Line #').grid(row=4,column=1,sticky=W)
	Label(master,text='Y Start Column #').grid(row=5,column=1,sticky=W)
	
	Entry(master,width=4,textvariable=self.ix[0]).grid(row=1,column=2,sticky=W)
	Entry(master,width=4,textvariable=self.ix[1]).grid(row=2,column=2,sticky=W)
	Entry(master,width=4,textvariable=self.ix[2]).grid(row=4,column=2,sticky=W)
	Entry(master,width=4,textvariable=self.ix[3]).grid(row=5,column=2,sticky=W)
	
        self.ix[0].set(0)
        self.ix[1].set(2)
        self.ix[2].set(3)
        self.ix[3].set(2)
      except AttributeError:

	return self.ix[0]

    def get(self):
	return [self.ix[0].get(),self.ix[1].get(),self.ix[2].get(),self.ix[3].get()]

    def apply(self):
      ix = self.get()
      Scan['rowcol'] = ix
      file = Scan['txtfile']
      if file != '':
	data  = readArray(file)
	nc = len(data)
	nr = len(data[0]) 
	data = rowreverse(data)
	x = data[ix[0]]
	data = data[ix[1]:nr]
	data = array(data)

	fo = open(file,'r')
	lines = fo.read()
	fo.close
	lines = string.split(lines,'\n')

        if ix[2] >= 0:
	    py = lines[ix[2]]
	    py = string.split(py)
	    y = py[ix[3]:len(py)]
	    for i in range(len(y)):
		y[i] = string.atof(y[i])
	else:
	    y = range(len(data))

	Scan['X'] = x
	Scan['Y'] = y
	file = Scan['txtfile']
        if Scan['updown']:
      	  plot2dUpdown(data,x,y,title=file)
        else: 
      	  plot2d(data,x,y,title=file)
	

class defineXYdialog(Dialog):
    "Dialog for entering Xmin,Xmax,Ymin,Ymax ranges"
    def body(self,master):
      try:
	file = Scan['txtfile']
        data = readArray(file)
	data = rowreverse(data)
        data = array(data)
	nc = data.shape[1]
	nr = data.shape[0]
	Scan['im'] = data

	font=SH['font'] #'Verdana 10 bold'
        self.title("Set X, Y Ranges for Image Plot")
	self.ix = [StringVar(),StringVar(),StringVar(),StringVar()]
	Label(master,text='Enter X Plot Range',font=font).grid(row=0,column=0,sticky=W)
	Label(master,text='Xmin').grid(row=1,column=1,sticky=W)
	Label(master,text='Xmax').grid(row=2,column=1,sticky=W)
	Label(master,text='Enter Y Plot Range',font=font).grid(row=3,column=0,sticky=W)
	Label(master,text='Ymin').grid(row=4,column=1,sticky=W)
	Label(master,text='Ymax').grid(row=5,column=1,sticky=W)
	
	Entry(master,width=14,textvariable=self.ix[0]).grid(row=1,column=2,sticky=W)
	Entry(master,width=14,textvariable=self.ix[1]).grid(row=2,column=2,sticky=W)
	Entry(master,width=14,textvariable=self.ix[2]).grid(row=4,column=2,sticky=W)
	Entry(master,width=14,textvariable=self.ix[3]).grid(row=5,column=2,sticky=W)
        self.ix[0].set(1.)
        self.ix[1].set(float(nc))
        self.ix[2].set(1.)
        self.ix[3].set(float(nr))
      except AttributeError:

	return self.ix[0]

    def get(self):
	return [self.ix[0].get(),self.ix[1].get(),self.ix[2].get(),self.ix[3].get()]

    def apply(self):
      ix = self.get()
      ix = [string.atof(ix[0]),string.atof(ix[1]),string.atof(ix[2]),
		string.atof(ix[3])]
      data = Scan['im']
      nr = data.shape[0]
      nc = data.shape[1]
      x = []
      dx = (ix[1]-ix[0])/(nc-1)
      for i in range(nc):
		x.append(ix[0]+dx*i)
      y = []
      dy = (ix[3]-ix[2])/(nr-1)
      for i in range(nr):
		y.append(ix[2]+dy*i)
      if Scan['updown']:
      	plot2dUpdown(data,x,y,title=Scan['txtfile'])
      else: 
      	plot2d(data,x,y,title=Scan['txtfile'])
	
class GetXYdialog(Dialog):
    "Dialog for define X,Y vector line and column #"
    def body(self,master):
      try:
	font=SH['font'] #'Verdana 10 bold'
        self.title("Get X, Y Vectors from ASCII file")
	self.ix = [IntVar(),IntVar(),IntVar(),IntVar()]
	Label(master,text='X Vector Defined in:',font=font).grid(row=0,column=0,sticky=W)
	Label(master,text='Line #').grid(row=1,column=1,sticky=W)
	Label(master,text='Start Column #').grid(row=2,column=1,sticky=W)
	Label(master,text='Y Vector Defined in:',font=font).grid(row=3,column=0,sticky=W)
	Label(master,text='Line #').grid(row=4,column=1,sticky=W)
	Label(master,text='Start Column #').grid(row=5,column=1,sticky=W)
	
	Entry(master,width=4,textvariable=self.ix[0]).grid(row=1,column=2,sticky=W)
	Entry(master,width=4,textvariable=self.ix[1]).grid(row=2,column=2,sticky=W)
	Entry(master,width=4,textvariable=self.ix[2]).grid(row=4,column=2,sticky=W)
	Entry(master,width=4,textvariable=self.ix[3]).grid(row=5,column=2,sticky=W)
	
#	cl = Scan['rowcol']
	cl = [3,2,4,2]
        self.ix[0].set(cl[0])
        self.ix[1].set(cl[1])
        self.ix[2].set(cl[2])
        self.ix[3].set(cl[3])
      except AttributeError:

	return self.ix[0]

    def get(self):
	return [self.ix[0].get(),self.ix[1].get(),self.ix[2].get(),self.ix[3].get()]

    def apply(self):
      ix = self.get()
      Scan['rowcol'] = ix
      file = Scan['txtfile']
      if file != '':
	fo = open(file,'r')
	lines = fo.read()
	fo.close
	lines = string.split(lines,'\n')
	px = lines[ix[0]]
	px = string.split(px)
	x = px[ix[1]:len(px)]
	for i in range(len(x)):
		x[i] = string.atof(x[i])
	py = lines[ix[2]]
	py = string.split(py)
	y = py[ix[3]:len(py)]
	for i in range(len(y)):
		y[i] = string.atof(y[i])
	Scan['X'] = x
	Scan['Y'] = y
	file = Scan['txtfile']
	data = readArray(file)
	data = rowreverse(data)
	data = array(data)
        if Scan['updown']:
      	  plot2dUpdown(data,x,y,title=file)
        else: 
      	  plot2d(data,x,y,title=file)
	

class GetXdialog(Dialog):
    "Dialog for defining X column # in text file"
    def body(self,master):
	font=SH['font'] #'Verdana 10 bold'
        self.title("1D Multi-Line Plot")
        self.ix = IntVar()
	Label(master,text='Defined valid X column # from text file:',font=font).pack(anchor=NW)
	Label(master,text=Scan['txtfile'],font=font).pack(anchor=NW)
	Label(master,text='-1 - No X column defined ').pack(anchor=NW)
	Label(master,text=' 0 - X defined at First column').pack(anchor=NW)
	Label(master,text=' 1 - X defined at Second column').pack(anchor=NW)
        Label(master,text='Enter X Column Index #:',font=font).pack(side=LEFT)
        self.ix =  Entry(master, width = 4)
        self.ix.pack(side=LEFT)
	v = self.get()
        self.ix.insert(0,v)
        return self.ix

    def get(self):
#        fo.close()
	SH = readSH()
	ix = SH['ix']
	return ix

    def apply(self):
        ix = self.ix.get()
	SH['ix'] = string.atoi(ix)
	writeSH(SH)
	os.system('plotAscii.py '+Scan['txtfile']+' '+str(ix) +' &')

class pick2Ddetector(Dialog):
   "Dialog to pick any detector from the MDA 2D detector list and plot the selected 2D detector image"

   def body(self,master):
      self.title("Select 2D Detector")
      box = Pmw.ScrolledListBox(master,
	items=('1','2','3','4'),
	labelpos=NW,label_text='Pick Detector',
	selectioncommand=self.selectionCommand,
	dblclickcommand=self.selectionCommand,
	usehullsize=1,hull_width=200,hull_height=200)
      box.pack()
      self.box = box

   def selectionCommand(self):
	box = self.box
        sels = box.getcurselection()
        sels = string.split(sels[0])
	sel = string.atoi(sels[0])
	Scan['2d'] = sel
	d = Scan['data']
	pick2d(d,sel,updown=Scan['updown'])

   def apply(self):
	self.destroy()


class pviewer(AppShell.AppShell):
   usecommandarea=1
   balloonhelp=1
   appversion   = '1.0'
   appname	= 'pviewer'
   copyright    = 'Copyright ANL-APS-AOD-BCDA. All Rights Reserved'
   contactname  = 'Ben-chin K Cha'
   contactphone = '(630) 252-8653'
   contactemail  = 'cha@aps.anl.gov'
   frameWidth = 800
   frameHeight = 500

   def unimplemented(self):
        pass

   def messageMDA(self):
	box = Pmw.Dialog(self.interior(),
		defaultbutton='OK',title='Info')
	w = Label(box.interior(),
		text='You need to use  File->Open MDA...\n to load in an MDA file first',
		padx=10,pady=10).pack()
	box.activate()

   def messageAscii(self):
		box = Pmw.Dialog(self.interior(),
			defaultbutton='OK',title='Info')
		w = Label(box.interior(),
			text='You need to use  File->Open Ascii...\n to load in an ASCII file first',
			padx=10,pady=10).pack()
		box.activate()

   def savepvs(self):
	file = 'pvs'
	V = self.apply()
	fd = open(file,'w')
        fd.write(str(V))
        fd.close()

   
   def createButtons(self):
        self.buttonAdd('Exit',
                helpMessage='Exit pviewer',
                statusMessage='Exit pviewer',
                command=self.closeup)

   def startup(self):
     if os.path.isfile('pviewer.config'):
	lines = readST('pviewer.config')	
	self.mdapath = lines[0]
	self.txtpath = lines[1]
	print 'self.mdapath=', self.mdapath
	print 'self.txtpath=', self.txtpath
     else:
	self.mdapath = os.curdir 
	self.txtpath = os.curdir 

   def closeup(self):
	fo = open('pviewer.config','w')
	st = [ self.mdapath,self.txtpath]
#	print str(st)
	fo.write(str(st))
	fo.close()
	self.quit()

#   def addmenuBar(self):
#	self.menuBar.addmenu('Setup','Fields for plot legend')

   def addMoremenuBar(self):
	self.menuBar.addmenuitem('File', 'command', 'Quit this application',
		label='Quit',
		command=self.closeup)
	self.menuBar.addmenuitem('File', 'command', '', label='--------------')
	self.menuBar.addmenuitem('File', 'command', 
		'Setup Printer ...',
		label='Printer...',
		command=self.printerDialog)
	self.menuBar.addmenuitem('File', 'command', '', label='--------------')
	self.menuBar.addmenuitem('File', 'command', 
		'File Selection dialog for Ascii File ...',
		label='Open Ascii ...',
		command=self.openAscii)
	self.menuBar.addmenuitem('File', 'command', '', label='--------------')
	self.menuBar.addmenuitem('File', 'command', 
		'File Selection dialog for MDA File ...',
		label='Open MDA ...',
		command=self.openMDA)

	self.menuBar.addmenuitem('Help', 'command', 
		'Online help about this application ...',
		label='pviewer_help.txt ...',
		command=self.openHelpText)
	
	self.menuBar.addmenuitem('Setup','command',
		'Pick and load Color Table for 2D image plot ',
		label='Color Table...',
		command=self.setCTdialog)
	self.menuBar.addmenuitem('Setup','command',
		'Modify legend field names used in multiline plot',
		label='Name Legends...',
		command=self.legenddialog)
	self.toggleUpdownVar=IntVar()
	self.toggleUpdownVar.set(1)
	self.menuBar.addmenuitem('Setup','checkbutton',
		'Toggle plot2d updown mode',
		label='Image Upside Down',
		variable=self.toggleUpdownVar,
		command=self.updownImage)

        self.menuBar.addmenu('MDAView','Various MDAView features')
	self.menuBar.addmenuitem('MDAView','command',
		'Access 1D Array and pass to multiline plotter...',
		label='Multi-line 1D Plot...',
		command=self.mda1DRptPlot)
	self.menuBar.addmenuitem('MDAView', 'command', '', 
		label='--------------')
	self.menuBar.addmenuitem('MDAView','command',
		'Access panimage window',
		label='PanImages...',
		command=self.getpanimage)
	self.menuBar.addmenuitem('MDAView','command',
		'Display 2D image for the select detector',
		label='Pick Di Image...',
		command=self.get2Ddetector)

        self.menuBar.addmenu('MDAReports','Various Report features')
	self.menuBar.addmenuitem('MDAReports','command',
		'Generate MDA 1D/2D reports',
		label='MDA 1D/2D Reports...',
		command=self.mdaReport)
	self.menuBar.addmenuitem('MDAReports','command',
		'Generate sequential MDA 1D report from 2D array',
		label='MDA 2D->1D Report...',
		command=self.mda2D1DRpt)
	self.menuBar.addmenuitem('MDAReports', 'command', '', 
		label='--------------')
	self.menuBar.addmenuitem('MDAReports','command',
		'Generate MDA report for current MDA directory',
		label='Generate All MDA Report...',
		command=self.mdaAllRpt)
	self.menuBar.addmenuitem('MDAReports', 'command', '', 
		label='--------------')
	self.menuBar.addmenuitem('MDAReports','command',
		'Generate MDA 2D report in IGOR format',
		label='MDA to IGOR Report...',
		command=self.mdaIGORRpt)
	self.menuBar.addmenuitem('MDAReports', 'command', '', 
		label='--------------')
	self.menuBar.addmenuitem('MDAReports','command',
		'Show ASCII Report Files',
		label='View ASCII Report...',
		command=self.showAscii)
	self.menuBar.addmenuitem('MDAReports', 'command', '', 
		label='--------------')
	self.menuBar.addmenuitem('MDAReports','command',
		'Clear All Files in ASCII directory',
		label='Remove All Reports...',
		command=self.removeAscii)

        self.menuBar.addmenu('AsciiView','Various AsciiView features')
	self.menuBar.addmenuitem('AsciiView', 'command', '', 
		label='--------------')
	self.menuBar.addmenuitem('AsciiView','command',
		'Enter the zero based X column # in ASCII file',
		label='Multi-line Plotter...',
		command=self.XcolDialog)
	self.menuBar.addmenuitem('AsciiView','command',
		'Pick line of DI legend name from the ascii file',
		label='Extract & Modify Legend...',
		command=self.DIlinedialog)
	self.menuBar.addmenuitem('AsciiView', 'command', '', 
		label='--------------')
	self.menuBar.addmenuitem('AsciiView', 'command', 
		'Pass ascii text data to image plot ...',
		label='TV Image ...',
		command=self.imageAscii)

        self.menuBar.addmenu('Ascii2Image','Plot2D Ascii Image features')
	self.menuBar.addmenuitem('Ascii2Image', 'command', 
		'No X,Y vector defined in ascii file',
		label='Plot2d...',
		command=self.plot2ddialog)
	self.menuBar.addmenuitem('Ascii2Image', 'command', 
		'User set X,Y ranges dialog',
		label='X,Y Range for image...',
		command=self.XYrangeDialog)
	self.menuBar.addmenuitem('Ascii2Image', 'command', '', 
		label='--------------')
	self.menuBar.addmenuitem('Ascii2Image', 'command', 
		'Extract the X,Y line vectors from mdaAscii generated file',
		label='X,Y Line vector from mdaAscii file...',
		command=self.XYrowcolDialog)
	self.menuBar.addmenuitem('Ascii2Image', 'command', '', 
		label='--------------')
	self.menuBar.addmenuitem('Ascii2Image', 'command', 
		'Extract X,Y,Data from scanSee/catcher/yviewer generated file',
		label='X column, Y line, DATA column from ascii file...',
		command=self.XYVDialog)

        self.menuBar.addmenu('ScanTools','Various scan programs')
	self.menuBar.addmenuitem('ScanTools','command',
		'Run plot.py python program',
		label='Python plot.py ...',
		command=self.runPlot)
	self.menuBar.addmenuitem('ScanTools', 'command', '', 
		label='--------------')
	self.menuBar.addmenuitem('ScanTools','command',
		'Run idlvm sscan (scanSee) program',
		label='idlvm sscan ...',
		command=self.runSscan)
	self.menuBar.addmenuitem('ScanTools','command',
		'Run idlvm catcher (catcher) program',
		label='idlvm catcher ...',
		command=self.runCatcher)
	self.menuBar.addmenuitem('ScanTools','command',
		'Run idlvm mca (MCA) program',
		label='idlvm mca ...',
		command=self.runMCA)

        self.menuBar.addmenu('Tools','Various system tools')
	self.menuBar.addmenuitem('Tools','command',
		'Run start_epics program',
		label='start_epics ...',
		command=self.runMedm)
	self.menuBar.addmenuitem('Tools', 'command', '', 
		label='--------------')
	self.menuBar.addmenuitem('Tools', 'command', 
		'Enter any valid command syntax ...',
		label='Command Dialog...',
		command=self.commandDialog)

   def runPlot(self):
	os.system('plot.py & ')

   def runSscan(self):
	os.system('idlvm sscan & ')

   def runCatcher(self):
	os.system('idlvm catcher & ')

   def runMCA(self):
	os.system('idlvm mca & ')

   def runMedm(self):
	h = os.getenv('HOME')
	os.system(h +'/start_epics & ')

   def commandDialog(self):
	cmd = commandSyntax(self.interior())

   def printerDialog(self):
	setupPrinter(self.interior())

   def removeAscii(self):
        from Dialog import *
#        dir = os.getcwd() +os.sep+'ASCII'+os.sep+'*.txt'
	dir = self.txtpath+os.sep+'*.txt'
        dir = 'rm -fr '+dir
        pa = {'title': 'Remove ASCII files',
                'text': dir + '\n\n'
			'All ascii text files will be removed\n'
                        'from the sub-directory ASCII.\n'
                        'Is it OK to remove all files ?\n ',
                'bitmap': DIALOG_ICON,
                'default': 1,
                'strings': ('OK','Cancel')}
        dialog = Dialog(self.interior(),pa)
        ans = dialog.num
        if ans == 0:
          print dir
          os.system(dir)

   def showAscii(self):
	fname = tkFileDialog.askopenfilename(initialdir=self.txtpath,initialfile="*txt*")
	if fname == (): return
	xdisplayfile(fname)

   def mdaIGORRpt(self):
     if Scan['open']:
	d  = self.MDA
	if d[0]['rank'] < 2:
		return
	fname = self.mdafile
        ofname = mdaAscii_IGOR(d)
	if self.textWid != None:
		self.textWid.destroy()
		self.textWid = None
	st = Pmw.ScrolledText(self.interior(),borderframe=1,labelpos=N,
		label_text=ofname,usehullsize=1,
		hull_width=800,hull_height=400,
		text_padx=10,text_pady=10,
		text_wrap='none')
	fo = open(ofname,'r')
	st_text = fo.read()
	fo.close()
	st.settext(st_text)
	st.pack(fill=BOTH, expand=1, padx=5, pady=5)
	self.textWid = st
	self.textfile = ofname
	SH['ix'] = -1
	writeSH(SH)
	(self.txtpath,fn) = os.path.split(ofname)
     else:
	self.messageMDA()

   def mdaAllRpt(self):
	if self.textWid != None:
		self.textWid.destroy()
		self.textWid = None
	st = Pmw.ScrolledText(self.interior(),borderframe=1,labelpos=N,
		label_text='MDA file from: '+self.mdapath,usehullsize=1,
		hull_width=800,hull_height=400,
		text_padx=10,text_pady=10,
		text_wrap='none')
	st.pack()
	st.settext('Reports saved in: '+os.getcwd()+os.sep+'ASCII')
	self.textWid=st
	mdaAscii_all(self.mdapath)

   def mda2D1DRpt(self):
#	d = readMDA.readMDA(fname, 1, 0, 0)
     if Scan['open']:
	d  = self.MDA
	if d[0]['rank'] < 2: return
	if d[2].nd == 0: return
	fname = self.mdafile
        ofname = mdaAscii_2D1D(d)
	if self.textWid != None:
		self.textWid.destroy()
		self.textWid = None
	st = Pmw.ScrolledText(self.interior(),borderframe=1,labelpos=N,
		label_text=ofname,usehullsize=1,
		hull_width=800,hull_height=400,
		text_padx=10,text_pady=10,
		text_wrap='none')
	fo = open(ofname,'r')
	st_text = fo.read()
	fo.close()
	st.settext(st_text)
	st.pack(fill=BOTH, expand=1, padx=5, pady=5)
	self.textWid = st
	self.textfile = ofname
	Scan['txtfile'] = ofname
	SH['ix'] = 0
	(self.txtpath,fn) = os.path.split(ofname)

   def mda2DRpt(self):
#	d = readMDA.readMDA(fname, 1, 0, 0)
     if Scan['open']:
	d  = self.MDA
	fname = self.mdafile
	if d[1].nd > 0 :
        	ofname = mdaAscii_1D(d)
	if d[0]['rank'] < 2: return
	if d[2].nd == 0 : return
        ofname = mdaAscii_2D(d)
	py = d[1].p[0].data
        px = d[2].p[0].data
        px = px[0]
	Scan['X'] = px
	Scan['Y'] = py
	Scan['txtfile'] = ofname 
	if self.textWid != None:
		self.textWid.destroy()
		self.textWid = None
	st = Pmw.ScrolledText(self.interior(),borderframe=1,labelpos=N,
		label_text=ofname,usehullsize=1,
		hull_width=800,hull_height=400,
		text_padx=10,text_pady=10,
		text_wrap='none')
	fo = open(ofname,'r')
	st_text = fo.read()
	fo.close()
	st.settext(st_text)
	st.pack(fill=BOTH, expand=1, padx=5, pady=5)
	self.textWid = st
	self.textfile = ofname
	SH['ix'] = -1
	writeSH(SH)
	(self.txtpath,fn) = os.path.split(ofname)
     else:
	self.messageMDA()

   def mda1DRptPlot(self):
	self.mda1DRpt()
	self.plotAscii()

   def mdaReport(self):
	d = self.MDA
	if d[0]['rank'] == 1:
		self.mda1DRpt()
	if d[0]['rank'] >= 2:
		self.mda2DRpt()

   def mda1DRpt(self):
#	d = readMDA.readMDA(fname, 1, 0, 0)
     if Scan['open']:
	d  = self.MDA
	fname = self.mdafile
        ofname = mdaAscii_1D(d)
	if self.textWid != None:
		self.textWid.destroy()
		self.textWid = None
	st = Pmw.ScrolledText(self.interior(),borderframe=1,labelpos=N,
		label_text=ofname,usehullsize=1,
		hull_width=800,hull_height=400,
		text_padx=10,text_pady=10,
		text_wrap='none')
	fo = open(ofname,'r')
	st_text = fo.read()
	fo.close()
	st.settext(st_text)
	st.pack(fill=BOTH, expand=1, padx=5, pady=5)
	self.textWid = st
	self.textfile = ofname
	Scan['txtfile'] = ofname
	SH['ix'] = 0
	(self.txtpath,fn) = os.path.split(ofname)
     else:
	self.messageMDA()

   def colorbar(self):
        W = 256
        clrbar =[]
        for j in range(10):
            clrbar.append(range(W))
        clrbar = array(clrbar)
        imagebar = PNGImage(self.canvas,clrbar,(2,2))
        imagebar.pack(side='top')
	self.imagebar = imagebar

   def executeCT(self):
	sels = self.textWid.getcurselection()
	sels = string.split(sels[0])
	CT_id = string.atoi(sels[0])
	ps = str(CT[CT_id])
	fo = open('pal.dat','wb')
	fo.write(ps)
	fo.close()
	self.imagebar.destroy()	
	self.colorbar()

   def setCTdialog(self):
	if self.textWid != None:
		self.textWid.destroy()
		self.textWid = None
	CT = readCT()
 	CT_id=39
	frame = self.interior()
        self.canvas = Canvas(frame,width=300,height=50)
        self.canvas.pack()
        self.colorbar()
	dname=('0 B-W LINEAR','1 BLUE/WHITE','2 GRN-RED-BLU-WHT',
	'3 RED TEMPERATURE','4 BLUE/GREEN/RED/YELLOW','5 STD GAMMA-II',
	'6 PRISM','7 RED-PURPLE','8 GREEN/WHITE LINEAR',
	'9 GRN/WHT EXPONENTIAL','10 GREEN-PINK','11 BLUE-RED',
	'12 16-LEVEL','13 RAINBOW','14 STEPS',
	'15 STERN SPECIAL','16 Haze','17 Blue-Pastel-Red',
	'18 Pastels','19 Hue Sat Lightness1','20  Hue Sat Lightness2',
	'21 Hue Sat Value 1','22 Hue Sat Value 2','23 Purple-Red + Stripes',
	'24 Beach','25 Mac Style','26 Eos A',
	'27 Eos B','28 Hardcandy','29 Nature',
	'30 Ocean','31 Peppermint','32 Plasma',
	'33 Blue-Red','34 Rainbow',
	'35 Blue Waves','36 Volcano','37 Waves',
	'38 Rainbow18','39 Rainbow + white','40 Rainbow + black')
        box = Pmw.ScrolledListBox(frame,
                labelpos=N,label_text='Color Table #',
                items=dname,
                listbox_height=5,vscrollmode='static',
                selectioncommand= self.executeCT,
                dblclickcommand= self.executeCT,
                usehullsize=1, hull_width=400, hull_height=200)
#        box.pack(fill=BOTH,expand=1,padx=10,pady=10)
        box.pack()
	self.textWid = box

   def selectionCommand(self):
	box = self.textWid
        sels = box.getcurselection()
        sels = string.split(sels[0])
	sel = string.atoi(sels[0])
	Scan['2d'] = sel
	d = self.MDA
	pick2d(d,sel,updown=Scan['updown'])


   def get2Ddetector(self):
	if self.mdafile == '':
		self.messageMDA()
		return
	if self.textWid != None:
		self.textWid.destroy()
		self.textWid = None
	root = self.interior()
	d = self.MDA
        nd = d[2].nd
        dname =[]
        for i in range(nd):
		lst = str(i) + ' '+d[2].d[i].fieldName +' ' + d[2].d[i].name +' '+ d[2].d[i].desc +' '+d[2].d[i].unit
                dname.append(lst)
        box = Pmw.ScrolledListBox(root,
                labelpos=N,label_text='2D Image Seq #',
                items=(dname[0:nd]),
                listbox_height=5,vscrollmode='static',
                selectioncommand= self.selectionCommand,
                dblclickcommand= self.selectionCommand,
                usehullsize=1, hull_width=500, hull_height=200)
#        box.pack(fill=BOTH,expand=1,padx=10,pady=10)
        box.pack()
	self.textWid = box

   def getpanimage(self):
	file = self.mdafile
	if file != '':
		d = self.MDA
		pal = readPalette()
		if d[0]['rank'] > 1:
		    det2D(d[2].d[0:d[2].nd],scale=(1,1),columns=5,file=file,pal=pal)
	else:
		self.messageMDA()

   def headerMDA(self,d,J,st_text):
        try:
	  if d[J].nd > 0: 
	    st_text = st_text+d[J].scan_name+'\n'
	    st_test = st_text+'NPTS: '+str(d[J].npts)+'\n'
	    st_test = st_text+'CURR_PT: '+str(d[J].curr_pt)+'\n'
	    st_text = st_text + '**'+str(J)+'D detectors**\n'
	    for i in range(d[J].nd):
		st_text=st_text+d[J].d[i].fieldName+' : '+d[J].d[i].name+', '+d[J].d[i].desc+', '+d[J].d[i].unit+'\n'
        except IndexError:
	    pass
	return st_text

   def openMDA(self):
	fname = askopenfilename( initialdir=self.mdapath,
		filetypes=[("MDA File", '.mda'),
                ("All Files","*")])
	if fname =='':
		return
	self.mdafile = fname
	(self.mdapath, fn) = os.path.split(fname)
	d = readMDA(fname)
	self.MDA = d
	Scan['data'] = d
	Scan['open'] = 1
	st_text = 'Please use ViewMDA menu to access MDA 1D/2D data array\n\n'
        try:
	  if d[1].nd > 0: 
	    st_text = self.headerMDA(d,1,st_text)
            if d[1].nd > 0:
	      V=[]
	      for i in range(85):
		V.append('')
	      for i in range(d[1].nd):
	  	V[i] = d[1].d[i].fieldName
	    file='pvs'
	    fd = open(file,'w')
	    fd.write(str(V))
	    fd.close()
        except IndexError:
	    pass
        try:
	  if d[2].nd > 0: 
	    st_text = self.headerMDA(d,2,st_text)
        except IndexError:
	    pass
        try:
	  if d[3].nd > 0: 
	    st_text = self.headerMDA(d,3,st_text)
        except IndexError:
	    pass
	if self.textWid != None: 
		self.textWid.destroy()
		self.textWid = None
	st = Pmw.ScrolledText(self.interior(),borderframe=1,labelpos=N,
		label_text=fname,usehullsize=1,
		hull_width=800,hull_height=400,
		text_padx=10,text_pady=10,
		text_wrap='none')
	st.settext(st_text)
	st.pack(fill=BOTH, expand=1, padx=1, pady=1)
	self.textWid = st

   def openHelpText(self):
	if self.textWid != None:
		self.textWid.destroy()
		self.textWid = None
	fname = os.environ['PYTHONSTARTUP']+os.sep+'pviewer_help.txt'
	st = Pmw.ScrolledText(self.interior(),borderframe=1,labelpos=N,
		label_text=fname,usehullsize=1,
		hull_width=800,hull_height=400,
		text_padx=10,text_pady=10,
		text_wrap='none')
	st.importfile(fname)
	st.pack(fill=BOTH, expand=1, padx=1, pady=1)
	self.textWid = st
	
   def openAscii(self):
	fname = askopenfilename(initialdir=self.txtpath,
		filetypes=[("ASCII Data", '.txt'),
                ("Image Files","*im*"),
                ("Data Files",".dat"),
                ("All Files","*")])
	if fname == '':
		return
	(self.txtpath,fn) = os.path.split(fname)

	Scan['txtfile'] = fname
	self.textfile = fname
	if self.textWid != None:
		self.textWid.destroy()
		self.textWid = None
	st = Pmw.ScrolledText(self.interior(),borderframe=1,labelpos=N,
		label_text=fname,usehullsize=1,
		hull_width=800,hull_height=400,
		text_padx=10,text_pady=10,
		text_wrap='none')
	st.importfile(fname)
	st.pack(fill=BOTH, expand=1, padx=1, pady=1)
	self.textWid = st


   def imageAscii(self):
      if self.textfile != '':
	file = self.textfile
	data = readArray(file)
	data = rowreverse(data)
	TV(data)	
      else:
	self.messageAscii()

   def plot2ddialog(self):
      if self.textfile != '':
	file = self.textfile
	data = readArray(file)
	data = rowreverse(data)
	nr = len(data)
	nc = len(data[0])
	x = range(nc)
	y = range(nr)
	data = array(data)
        if Scan['updown']:
      	  plot2dUpdown(data,x,y,title=file)
        else: 
      	  plot2d(data,x,y,title=file)
      else:
	self.messageAscii()


   def plotAscii(self):
      if self.textfile == '':
	self.messageAscii()
	return
      try:
	os.system('plotAscii.py '+self.textfile+' &')
      except AttributeError:
	pass

   def XYrowcolDialog(self):
	file = Scan['txtfile']
	if file == '':
		self.messageAscii()
		return
	ix = GetXYdialog(self.interior())

   def XYVDialog(self):
	file = Scan['txtfile']
	if file == '':
		self.messageAscii()
		return
	ix = GetXYVdialog(self.interior())

   def XYrangeDialog(self):
	file = Scan['txtfile']
	if file == '':
		self.messageAscii()
		return
	ix = defineXYdialog(self.interior())

   def XcolDialog(self):
      if self.textfile == '':
	self.messageAscii()
      else:
	Scan['txtfile'] = self.textfile
	ix=GetXdialog(self.interior())

   def legenddialog(self):
#	dialog=GetLegends(self.interior())
	GetLegends(self.interior())

   def DIlinedialog(self):
        file = Scan['txtfile']
        if file == '': return
	dialog=pickDIdialog(self.interior())

   def updownImage(self):
	Scan['updown'] = self.toggleUpdownVar.get()

   def pick2Ddialog(self):
	if Scan['open']:
		dialog=pick2Ddetector(self.interior())

   def createInterface(self):
	AppShell.AppShell.createInterface(self)
	self.addMoremenuBar()
#	self.createButtons()
	self.textWid = None
	self.mdafile = ''
	self.textfile = ''
	self.startup()

if __name__ == '__main__':
	SH = {'ix': 0, 'printer': '', 'font': 'Verdana 10 bold', }
	if os.path.isfile('SH'): 
		SH = readSH()
	else:
		writeSH(SH)
	Scan = { 'open': 0,
	'2d': 0,
	'updown': 1,
	'1d': 0,
	'nc': 0,
	'CT': 39,
	'rowcol': [3,2,4,2],
	'txtfile': '',
	'pvs1': None,
	'pvs2': None,
	'pvs3': None,
	'X': None,
	'Y': None,
	'im': None,
	'data': None }

	CT = readCT()
	pt = pviewer()
	pt.run()
