/******************************************************************************
* Copyright 1996-2014 United States Government as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All Rights Reserved.
******************************************************************************/

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.datatransfer.*;
import java.net.URL;
import gsfc.nssdc.cdf.*;
import gsfc.nssdc.cdf.util.*;

/** CDFEdit allows a CDF and its contents to be created and edited.
 */

public class CDFEdit extends JFrame implements ActionListener, ItemListener,
						MouseListener, FocusListener, 
						CDFConstants, Runnable {

    private CDFEdit cdfedit;
    protected JDialog dialog;
    public  MYEditor aCDFEditor = null;
    protected JFrame parentDriver;
    protected CDF sourceCDF = null;
    private String channelFile;
    private boolean cdfHandling = false;

    private boolean MacOS = false;
    private boolean WindowsOS = false;

    private ButtonGroup selectgp;
    private JRadioButton select1;
    private JRadioButton select2;
    private JRadioButton select3;

    private JButton entrb;
    private JButton helpb;
    private JButton quitb;

    private JButton slt1;
    private JButton slt2;
    private JButton slt3;
    private JCheckBox abc;

    protected JTextArea info;
    private JTextField cdf1;
    private JTextField cdf2;
    private JTextField cdf3;

    private JScrollPane scroller; 

    protected String cdfspec;
    private int editSelection = -1;
    private String currentdir = System.getProperty("user.dir");

    private String[] cdfs = {"cdf", "CDF"};
    private SimpleFileFilter cdffilter = new SimpleFileFilter(cdfs, " CDF files (*.cdf, *.CDF)");

    private JTextField focused = null;
    private JTextField prevfocused = null;

    protected int ROWS = 26;
    protected int COLUMNS = 9;

    private JMenuBar menuBar;
    private JMenu menuFile;
    private JMenu menuEdit;
    private JMenu menuHelp;
    private JMenuItem menuEditCopy;
    private JMenuItem menuEditCut;
    private JMenuItem menuEditPaste;
    private JMenuItem menuFileOpen;
    private JMenuItem menuFileCreate1, menuFileCreate2;
    private JMenuItem menuFileExit;
    private JMenuItem menuHelpHelp;
    private int istart = -1;
    private int iend = -1;
    private int backwardEnvVar;
    private long backwardFlag;

    private GridBagLayout gbl = new GridBagLayout();
    private GridBagConstraints gbc = new GridBagConstraints();

    Dimension hpad5 = new Dimension(5,1);
    Dimension hpad10 = new Dimension(10,1);
    Dimension hpad20 = new Dimension(20,1);
    Dimension hpad25 = new Dimension(25,1);
    Dimension hpad30 = new Dimension(30,1);
    Dimension hpad40 = new Dimension(40,1);
    Dimension hpad80 = new Dimension(80,1);
    Dimension vpad5 = new Dimension(1,5);
    Dimension vpad10 = new Dimension(1,10);
    Dimension vpad20 = new Dimension(1,20);
    Dimension vpad25 = new Dimension(1,25);
    Dimension vpad30 = new Dimension(1,30);
    Dimension vpad40 = new Dimension(1,40);
    Dimension vpad80 = new Dimension(1,80);

    Font  defaultFont = new Font("Dialog", Font.PLAIN, 12);
    Font  boldFont = new Font("Dialog", Font.BOLD, 12);
    Font  bigFont = new Font("Dialog", Font.PLAIN, 18);
    Font  bigboldFont = new Font("Dialog", Font.BOLD, 18);
    static int INITIAL_WIDTH = 400;
    static int INITIAL_HEIGHT = 200;
    static boolean defaultModal = false;
    boolean modal;
    int frommain = 0;
    static String osName = System.getProperty("os.name");

    static final long serialVersionUID = 1L;

    CDFEdit() {
        this(null, defaultModal);
    }

    CDFEdit(JFrame parentDriver) {
        this(parentDriver, defaultModal);
    }

    CDFEdit(JFrame parentDriver, boolean modal) {
	cdfedit = this;
	this.parentDriver = parentDriver;
	dialog = new JDialog(this, modal);
        this.modal = modal;
	if (osName.indexOf("Mac OS") != -1) {
	  if (osName.indexOf("Mac OS X") == -1)
            MacOS = true;
	}
	if (osName.indexOf("Windows") != -1)
	  WindowsOS = true;

	try {
	  backwardEnvVar = CDF.getFileBackwardEnvVar();
	} catch (Exception ee) {
	  System.out.println("Error getting Env Var..."+ ee);
	}  
	RepaintManager.currentManager(null).setDoubleBufferingEnabled(true);

    }

/** Implement the run method for Runabout interface.
 */

    public void run() {
	buildDailog();

	dialog.pack();
        Dimension ps = dialog.getSize();
        Dimension ss = Toolkit.getDefaultToolkit().getScreenSize();
        dialog.setLocation(ss.width/2 - ps.width/2,
                           ss.height/2 - ps.height/2);

        dialog.setVisible(true);
	if (parentDriver != null) parentDriver.setVisible(false);
    }

/** Reenter from the main toolkit driver. Reset the dialog to visible.
 */

    public void reEnter() {
	dialog.setVisible(true);
	if (parentDriver != null) parentDriver.setVisible(false);
    }

/** Set up the dialog items.
 */

    private void buildDailog() {

        WindowListener l = new WindowAdapter() {
           public void windowClosing(WindowEvent e) {
	     if (frommain == 0) {
		if (modal) dialog.dispose();
		else dialog.setVisible(false);
		if (parentDriver != null) parentDriver.setVisible(true);
	     } else { // run CDFEdit directly...
                System.exit(1);
            }
	  }
        };
        dialog.addWindowListener(l);
        dialog.setTitle("Enter   Selections  for  CDFEdit");

        dialog.setSize(INITIAL_WIDTH, INITIAL_HEIGHT);

	dialog.getContentPane().setLayout(new BorderLayout()); 
        buildMenu();
	buildGUIs();

        JPanel panelx = new JPanel(new BorderLayout(), true);
	// Panel 1
        JPanel panel1 = new JPanel(new GridLayout(5, 1), true);

        JPanel panel11 = new JPanel(new GridLayout(2,1), true);
        JPanel panel11x = new JPanel(new BorderLayout(), true);
        JPanel panel11xx = new JPanel(new BorderLayout(), true) ;

	JLabel OUTF1 = new JLabel("    File Name: ");

        panel11.add(select1);
        panel11xx.add(OUTF1, BorderLayout.WEST);        
        panel11xx.add(cdf1, BorderLayout.EAST);
        panel11x.add(panel11xx, BorderLayout.WEST);        
        panel11x.add(slt1, BorderLayout.EAST);        
        panel11.add(panel11x);        

        JPanel panel12 = new JPanel(new GridLayout(2,1), true);
        JPanel panel12x = new JPanel(new BorderLayout(), true);
        JPanel panel12xx = new JPanel(new BorderLayout(), true);
        JPanel panel13 = new JPanel(new GridLayout(2,1), true);
        JPanel panel13x = new JPanel(new BorderLayout(), true);
        JPanel panel13xx = new JPanel(new BorderLayout(), true);


        JLabel OUTF2 = new JLabel("    File Name: ");
	JLabel OUTF3 = new JLabel("    File Name: ");

	if (backwardEnvVar == 1) {
          panel12.add(select3);
          panel12xx.add(OUTF3, BorderLayout.WEST);
          panel12xx.add(cdf3, BorderLayout.EAST);
          panel12x.add(panel12xx, BorderLayout.WEST);
          panel12x.add(slt3, BorderLayout.EAST);
          panel12.add(panel12x);
	} else {
          panel12.add(select2);
          panel12xx.add(OUTF2, BorderLayout.WEST);
          panel12xx.add(cdf2, BorderLayout.EAST);
          panel12x.add(panel12xx, BorderLayout.WEST);
          panel12x.add(slt2, BorderLayout.EAST);
          panel12.add(panel12x);
          panel13.add(select3);
          panel13xx.add(OUTF3, BorderLayout.WEST);
          panel13xx.add(cdf3, BorderLayout.EAST);
          panel13x.add(panel13xx, BorderLayout.WEST);
          panel13x.add(slt3, BorderLayout.EAST);
          panel13.add(panel13x);
	}

        panel1.add(panel11);
        panel1.add(panel12);
	if (backwardEnvVar == 0) 
	  panel1.add(panel13);
        panel1.add(Box.createRigidArea(vpad5));

	JPanel panel14 = new JPanel(new GridLayout(1,5), true);
        panel14.add(abc);
	panel14.add(Box.createRigidArea(hpad10));
        panel14.add(Box.createRigidArea(hpad10));
        panel14.add(Box.createRigidArea(hpad10));
        panel14.add(Box.createRigidArea(hpad10));

        panel1.add(panel14);

//        dialog.getContentPane().add(panel1,BorderLayout.CENTER);
        panelx.add(panel1,BorderLayout.CENTER);

        // Panel 2 (buttons and text area)

        JPanel panel2 = new JPanel(new BorderLayout(), true);
        JPanel panel21 = new JPanel(new GridLayout(1, 5, 50, 20), true);

        panel21.add(Box.createRigidArea(new Dimension(10,1)));
        panel21.add(entrb);
        panel21.add(helpb);
        panel21.add(quitb);
        panel21.add(Box.createRigidArea(new Dimension(10,1)));
        panel2.add(panel21, BorderLayout.NORTH);

//        panel2.add(scroller, BorderLayout.SOUTH);
        panel2.add(scroller, BorderLayout.SOUTH);

//        dialog.getContentPane().add(panel2, BorderLayout.SOUTH);
        panelx.add(panel2, BorderLayout.SOUTH);

        dialog.getContentPane().add(panelx, BorderLayout.NORTH);
        dialog.getContentPane().add(scroller, BorderLayout.CENTER);

    }

/** Build the GUIs for the main dialog
 */

    private void buildGUIs() {

	slt1 = new JButton("Select");
        slt1.addActionListener(this);
        slt1.setToolTipText("Select an existing CDF file for editing");

	cdf1 = new JTextField("", 30);
        cdf1.addActionListener(this);
        cdf1.addMouseListener(this);
        cdf1.addFocusListener(this);
	cdf1.setToolTipText("Enter an existing CDF (without extension) for editing");

        slt2 = new JButton("Select");
        slt2.addActionListener(this);
        slt2.setToolTipText("Select a directory/file for creating a new V3.* CDF file");

        cdf2 = new JTextField("", 30);
        cdf2.addActionListener(this);
        cdf2.addMouseListener(this);
        cdf2.addFocusListener(this);
	cdf2.setToolTipText("Enter a new CDF file name (without extension) to create");

        slt3 = new JButton("Select");
        slt3.addActionListener(this);
        slt3.setToolTipText("Select a directory/file for creating a new V2.7 CDF file");

        cdf3 = new JTextField("", 30);
        cdf3.addActionListener(this);
        cdf3.addMouseListener(this);
        cdf3.addFocusListener(this);
        cdf3.setToolTipText("Enter a new CDF file name (without extension) to create");

        // Initialize the selection radio button.
	
        selectgp = new ButtonGroup();
        select1 = new JRadioButton("Open an existing CDF file");
	select2 = new JRadioButton("Create a new V3.* CDF file");
	select3 = new JRadioButton("Create a new V2.7 CDF file");

        SelectListener forSelect = new SelectListener();
        select1.setActionCommand("1");
	select1.addActionListener(forSelect);
	select1.setSelected(true);
	select1.setToolTipText("Edit an existing CDF");
	selectgp.add(select1);

	if (backwardEnvVar == 0) {
          select2.setActionCommand("2");
          select2.addActionListener(forSelect);
          selectgp.add(select2);
	  select2.setToolTipText("Create a new V3 CDF and edit its contents");
	} 
        select3.setActionCommand("3");
        select3.addActionListener(forSelect);
        selectgp.add(select3);
        select3.setToolTipText("Create a new V2 CDF and edit its contents");
	
        abc = new JCheckBox("About");
        abc.addItemListener(this);
	abc.setToolTipText("Check the CDF library version");

        entrb = new JButton(" Enter ");
        helpb = new JButton(" Help ");
        quitb = new JButton(" Quit ");

        entrb.addActionListener(this);
        helpb.addActionListener(this);
        quitb.addActionListener(this);
        entrb.setToolTipText("Continue processing...");
        helpb.setToolTipText("Get the help information");
        quitb.setToolTipText("Exit CDFEdit");

        // Text Area
        info = new JTextArea(15,20);
        info.setEditable(false);
        info.setVisible(true);
        scroller = new JScrollPane() {
                static final long serialVersionUID = 1L;
                public Dimension getPreferredSize() {
                   return new Dimension(80, 160);
                }
                public float getAlignmentX() {
                   return LEFT_ALIGNMENT;
                }
        };
        scroller.getViewport().add(info);

    }


/** Set up the menubar and items
 */

    private void buildMenu() {
        menuBar = new JMenuBar();
        menuFile = new JMenu("File");
        menuEdit = new JMenu("Edit");
        menuHelp = new JMenu("Help");
        menuEditCopy = new JMenuItem("Copy");
        menuEditCut = new JMenuItem("Cut");
        menuEditPaste = new JMenuItem("Paste");
        menuFileOpen = new JMenuItem("Open");
	menuFileCreate1 = new JMenuItem("Create a V3 CDF");
	menuFileCreate2 = new JMenuItem("Create a V2 CDF");
        menuFileExit = new JMenuItem("Exit");
        menuHelpHelp = new JMenuItem("Help");

        // set the menu bar
        dialog.setJMenuBar(menuBar);

        // add the file menu
        menuBar.add(menuFile);

        // add the menu items to file
        menuFile.add(menuFileOpen);
	if (backwardEnvVar == 1)
	  menuFile.add(menuFileCreate2);
	else {
	  menuFile.add(menuFileCreate1);
	  menuFile.add(menuFileCreate2);
	}
        menuFile.add(menuFileExit);
        menuFileOpen.addActionListener(this);
	menuFileCreate1.addActionListener(this);
	menuFileCreate2.addActionListener(this);
        menuFileExit.addActionListener(this);

        // add the edit menu
        menuBar.add(menuEdit);

        // add the menu items to edit
        menuEdit.add(menuEditCopy);
        menuEdit.add(menuEditCut);
        menuEdit.add(menuEditPaste);
        menuEditCopy.addActionListener(this);
        menuEditCut.addActionListener(this);
        menuEditPaste.addActionListener(this);

        // add the help menu
        menuBar.add(menuHelp);

        // add the menu items to help
        menuHelp.add(menuHelpHelp);
        menuHelpHelp.addActionListener(this);

    }


/** Action for buttons or menu items selection
 */

    public void actionPerformed(ActionEvent evt) {
	Object obj = evt.getSource();
	int ix;
	if (obj == quitb || obj == menuFileExit) { // for "Quit" or "Exit"
          if (frommain == 0) {
		if (modal) dialog.dispose();
		else dialog.setVisible(false);
		if (parentDriver != null) parentDriver.setVisible(true);
          } else {
		System.exit(1);
	  }
	} else if (obj == menuFileOpen || obj == slt1) {
	     String fileName;
	     cdf2.setText("");
	     cdf3.setText("");
	     // "Open" menu item or "Select" button
             fileName = CDFToolUtils.doFileChooser("Select/Enter the Source CDF File Name", 
						   1, cdffilter, currentdir, cdfedit);
	     if (fileName != null && fileName.trim().length() != 0) {
               if (MacOS) {
		 currentdir = fileName.substring(0, fileName.lastIndexOf('/'));
                 if (fileName.startsWith(":") || fileName.startsWith("/")) 
		   fileName = fileName.substring(1);
		 fileName = fileName.replace('/', ':');
               } else {
                 if (WindowsOS) ix = fileName.lastIndexOf('\\');
                 else ix = fileName.lastIndexOf('/');
                 if (ix != -1) currentdir = fileName.substring(0, ix);
                 else currentdir = System.getProperty("user.dir");
               }
//	       String fileNameX = (fileName.toLowerCase().endsWith(".cdf") ? fileName :
//				   new StringBuffer(fileName).append(".cdf").toString());
//             cdf1.setText(fileNameX);
               cdf1.setText(fileName);
               System.getProperties().put("user.dir", currentdir);
	     }
	     select1.setSelected(true);
        } else if (obj == menuFileCreate1 || obj == menuFileCreate2 ||
	           obj == slt2 || obj == slt3) {
             String fileName;
	     cdf1.setText("");
             // "Create" menu item or "Select" button
             fileName = CDFToolUtils.doFileChooser("Select/Enter the New CDF File Name",
                                                   1, cdffilter, currentdir, cdfedit);
             if (fileName != null && fileName.trim().length() != 0) {
               if (MacOS) {
		 currentdir = fileName.substring(0, fileName.lastIndexOf('/'));
                 if (fileName.startsWith(":") || fileName.startsWith("/")) 
		   fileName = fileName.substring(1);
		 fileName = fileName.replace('/', ':');
               } else {
                 if (WindowsOS) ix = fileName.lastIndexOf('\\');
                 else ix = fileName.lastIndexOf('/');
                 if (ix != -1) currentdir = fileName.substring(0, ix);
                 else currentdir = System.getProperty("user.dir");
               }  
//               String fileNameX = (fileName.toLowerCase().endsWith(".cdf") ? fileName :
//                                   new StringBuffer(fileName).append(".cdf").toString());
//               cdf2.setText(fileNameX);
	       if (obj == slt2 || obj == menuFileCreate1) {
	         cdf2.setText(fileName);
		 cdf3.setText("");
		 backwardFlag = BACKWARDFILEoff;
		 select2.setSelected(true);
	       } else {
	         cdf3.setText(fileName);
		 cdf2.setText("");
		 backwardFlag = BACKWARDFILEon;
		 select3.setSelected(true);
	       }
	       System.getProperties().put("user.dir", currentdir);
             }
	} else if (obj == helpb || obj == menuHelpHelp) { // for "Help" 
	     info.setText("");
	     try {
	       InputStream fis = cdfedit.getClass().getResourceAsStream("cdfedit.txt");
	       InputStreamReader reader = new InputStreamReader(fis, "UTF-8");
//	       FileReader reader = new FileReader("cdfedit.txt");
	       info.read(reader, null);
	       info.setCaretPosition(0);
	     } catch (FileNotFoundException e) {
	       info.setText("Help info is not available...");
             } catch (IOException e) {
               info.setText("Help info is not available...");
	     } catch (Exception e) {
	       info.setText("Help info is not available...");
             }
	} else if (obj == entrb) { // for "Enter" button
		String theselected = selectgp.getSelection().getActionCommand();
		if (theselected.equals("1")) { // Open an existing CDF
		  cdfspec = cdf1.getText();
                  if (cdfspec == null || cdfspec.equals("") ||
                      cdfspec.trim().length() == 0) {
                    info.setText("Please enter the source CDF file name");
                    Toolkit.getDefaultToolkit().beep();
                    return;
                  }
		  editSelection = 0;
		} else { // Create a new CDF
		  if (theselected.equals("2")) {
                    cdfspec = cdf2.getText();
		    backwardFlag = BACKWARDFILEoff;
		  } else {
		    cdfspec = cdf3.getText();
		    backwardFlag = BACKWARDFILEon;
		  }
                  if (cdfspec == null || cdfspec.equals("") || 
		      cdfspec.trim().length() == 0) {
                    info.setText("Please enter the new CDF file name");
                    Toolkit.getDefaultToolkit().beep();
                    return;
                  }
		  editSelection = 1;
		  
		} 
		
                if (MacOS) {
                  cdfspec = cdfspec.replace('/', ':');
                  if (cdfspec.startsWith(":")) cdfspec = cdfspec.substring(1);
                }
		if (getCDF()) {
		    if (aCDFEditor != null) aCDFEditor = null;
//		    aCDFEditor = new MYEditor(this, cdfedit, cdfspec);
		    aCDFEditor = new MYEditor(cdfedit, cdfspec);
//		    try {
//			Thread.sleep(1500);
//		    } catch (Exception e) {}
//		    dialog.setVisible(false);
		}
	} else if (obj == cdf1) {
		cdfspec = cdf1.getText();
                if (MacOS) {
                  cdfspec = cdfspec.replace('/', ':');
                  if (cdfspec.startsWith(":")) cdfspec = cdfspec.substring(1);
                }
		select1.setSelected(true);
		cdf2.setText("");
		cdf3.setText("");
	} else if (obj == cdf2) {
                cdfspec = cdf2.getText();
                if (MacOS) {
                  cdfspec = cdfspec.replace('/', ':');
                  if (cdfspec.startsWith(":")) cdfspec = cdfspec.substring(1);
                }
		select2.setSelected(true);
		cdf1.setText("");
		cdf3.setText("");
        } else if (obj == cdf3) {
                cdfspec = cdf3.getText();
                if (MacOS) {
                  cdfspec = cdfspec.replace('/', ':');
                  if (cdfspec.startsWith(":")) cdfspec = cdfspec.substring(1);
                }
                select3.setSelected(true);
		cdf1.setText("");
		cdf2.setText("");
        } else if (obj == menuEditCopy) {
                if (istart == -1) {
		    info.setText("Where to copy from?");
		    Toolkit.getDefaultToolkit().beep();
                } else {
                    focused.setSelectionStart(istart);
                    focused.setSelectionEnd(iend);
                    focused.copy();
                }
        } else if (obj == menuEditCut) {
                if (istart == -1) {
		    info.setText("What to cut?");
		    Toolkit.getDefaultToolkit().beep();
                } else {
                    focused.setSelectionStart(istart);
                    focused.setSelectionEnd(iend);
                    focused.cut();
                }
        } else if (obj == menuEditPaste) {
		if (focused == null) {
		    Toolkit.getDefaultToolkit().beep();
		} else {
                  if (istart != -1) {
                    focused.setSelectionStart(istart);
                    focused.setSelectionEnd(iend);
                  }
                  String temp;
                  try {
                    temp = (String) Toolkit.getDefaultToolkit().
                                    getSystemClipboard().getContents(this).
                                    getTransferData(DataFlavor.stringFlavor);
                    if (temp == null) { // no clipboard text
                        info.setText("No current selection on clipboard");
                        Toolkit.getDefaultToolkit().beep();
                    } else if (temp.indexOf("\n") != -1) { // multiple lines
                        info.setText("Multiple lines selection on clipboard - not allowed:");
                        info.append("\n\n");
                        info.append(temp);
                        Toolkit.getDefaultToolkit().beep();
                    } else { focused.paste();}
                  } catch (Exception e) {}
                }
	}
    }

/** Create an CDF object for the source CDF
 */

    boolean getCDF() {

	try {
	  if (editSelection == 0)
	    sourceCDF  = CDF.open(cdfspec, READONLYoff);
	  else {
	    CDF.setFileBackward(backwardFlag);
	    sourceCDF = CDF.create(cdfspec);
	  }

	  if (sourceCDF == null) { // not existing
            int result =
              JOptionPane.showConfirmDialog(this,
                                            "Do you want to create this CDF? ",
                                            "CDF: "+cdfspec+" not exists!",
                                            JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
		CDF.setFileBackward(backwardFlag);
		sourceCDF = CDF.create(cdfspec);
	    }
	  }

	  if (sourceCDF != null) { // edit the file
	    return true;
	  } else
	   return false;
	} catch (CDFException e) {
	  Toolkit.getDefaultToolkit().beep();
	  if (editSelection == 0) {
            JOptionPane.showMessageDialog(this,
                                          CDFException.getStatusMsg(e.getCurrentStatus()),
                                          "CDFEditor: Error",
                                          JOptionPane.ERROR_MESSAGE);
	    return false;
	  } else {
            int result =
              JOptionPane.showConfirmDialog(this,
                                            "Do you want to delete and re-create this CDF? ",
                                            "CDF: "+cdfspec+" already exists!",
                                            JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
		try {
		  sourceCDF = CDF.open(cdfspec, READONLYoff);
		  sourceCDF.delete();
		  CDF.setFileBackward(backwardFlag);
                  sourceCDF = CDF.create(cdfspec);
		} catch (CDFException ex) {
		  sourceCDF = null;
		}
            } 
            if (sourceCDF != null) return true;
            else return false;
	  }
	}

    }

/** Set/reset the selections to default values
 */

    void reset() {
    
       ROWS = 26;
       COLUMNS = 9;
    }

/** Action for radio buttons for selection
 */

    private class SelectListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
	   String strot = e.getActionCommand();
	   info.setText("");
	   if (strot.equals("1")) {
	     cdf2.setText("");
	     cdf3.setText("");
	   } else if (strot.equals("2")) {
	     cdf1.setText("");
	     cdf3.setText("");
	   } else {
	     cdf1.setText("");
	     cdf2.setText("");
	   }
        }
    }

    public void focusGained(FocusEvent e) {
	focused = (JTextField)e.getSource();
        if (prevfocused != null) {
            prevfocused.setText(prevfocused.getText());
            if (iend != -1)
                if (iend < focused.getText().length())
                             prevfocused.setCaretPosition(iend);
                else focused.setCaretPosition(focused.getText().length());
        }
	if (focused == cdf1) {
	  cdf2.setText("");
	  cdf3.setText("");
	  select1.setSelected(true);
	} else if (focused == cdf2) {
	  cdf1.setText("");
	  cdf3.setText("");
	  select2.setSelected(true);
	} else if (focused == cdf3) {
	  cdf1.setText("");
	  cdf2.setText("");
	  select3.setSelected(true);
	}
    }

    public void focusLost(FocusEvent e) {
        if (istart != -1)     {
            focused.setSelectionStart(istart);
            focused.setSelectionEnd(iend);
            prevfocused = focused;
          }
        }
    public void mouseClicked(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {
        if (focused != null) {
          String selectedText = focused.getSelectedText();
          if (selectedText!=null) {
            istart = focused.getSelectionStart();
            iend = focused.getSelectionEnd();
          } else {
            istart = -1;
            iend = -1;
          }
	}
    }

/** Actions for checkboxs or combo box selection
 */
    public void itemStateChanged(ItemEvent evt) {
        Object obj = evt.getSource();
        if (obj == abc) { // "About" checkbox
           if (abc.isSelected()) {
		try {
		  info.setText("CDF library distribution: "+CDF.getLibraryVersion());
                }
		catch (CDFException e) {System.err.println("error: "+e);}
		abc.setSelected(false);
           }
        }
    }

/** Set up gridbaglayout
 */

    private void makeJButton(GridBagLayout gbl, GridBagConstraints c, Container cont,
		Object arg, int x, int y, int w, int h, double weightx, double weighty) {
        Component comp;

        c.fill = GridBagConstraints.BOTH;
        c.gridx = x;
        c.gridy = y;
        c.gridwidth = w;
        c.gridheight = h;
        c.weightx = weightx;
        c.weighty = weighty;
        if (arg instanceof String) {
            comp = new JButton((String)arg);
        } else {
            comp = (Component)arg;
        }
        cont.add(comp);
        gbl.setConstraints(comp, c);
    }

    protected JDialog getDialog() {
        return dialog;

    }

/** This class can run as an application by its own.
 */

    static public void main(String[] args) {

        try {
            UIManager.setLookAndFeel(UIManager.
                                     getCrossPlatformLookAndFeelClassName());
        } catch (Exception exc) {
        }

//        JFrame myframe = new JFrame();
        CDFEdit thispgm = new CDFEdit();
        thispgm.frommain = 1;

	String osVersion = System.getProperty("os.version");
	String javaVersion = System.getProperty("java.version");
        if (osName.toLowerCase().indexOf("windows") != -1) {
          int thisOS = new Integer(osVersion.substring(0, osVersion.indexOf("."))).intValue();
          int inIndex = javaVersion.indexOf(".");
          String subJavaVersion = javaVersion.substring(inIndex+1);
          int thisMajorV = new Integer(javaVersion.substring(0, inIndex)).intValue();
          int thisMinorV = new Integer(subJavaVersion.substring(0, subJavaVersion.indexOf("."))).intValue();
          int thisJava = (thisMinorV<10?thisMajorV*10+thisMinorV:thisMajorV*100+thisMinorV);
//        if (osVersion.compareTo("5.0") >= 0 &&   // Windows 2000 and beyond...
//            javaVersion.compareTo("1.4") >= 0) { // Java 1.4
          if (thisOS >= 5 &&   // Windows 2000 and beyond...
               thisJava >= 14) { // Java 1.4
            try {
	      Runtime runtime = Runtime.getRuntime();
              Process process = runtime.exec("cmd /c assoc .cdf");
              InputStreamReader inReader1 = new InputStreamReader(process.getInputStream(), "UTF-8");
              BufferedReader inStream = new BufferedReader(inReader1, 8192);
              try {
                process.waitFor();
              } catch (InterruptedException ee) {
                System.err.println("Error with assoc... 1 "+ee);
              }
              thispgm.channelFile = inStream.readLine();
              if (thispgm.channelFile != null &&
                  thispgm.channelFile.toLowerCase().equals(".cdf=channelfile")) {
                process = runtime.exec("cmd /c assoc .cdf="); // dis-associate it
                InputStreamReader inReader2 = new InputStreamReader(process.getInputStream(), "UTF-8");
                inStream = new BufferedReader(inReader2, 8192);
		String dummy = inStream.readLine(); // clear the input buffer
                try {
                  process.waitFor();
                  runtime.addShutdownHook(new RestoreChannelDefinition(thispgm.channelFile));
                } catch (InterruptedException ee) {
                  System.err.println("Error with assoc... 2 "+ee);
                }
              }
            } catch (IOException ex) { // No need to do anything if "cmd" file does not exist
            }
          }
        }

//	thispgm.setSize(INITIAL_WIDTH, INITIAL_HEIGHT);
	thispgm.run();
    }

    // A thread to restore the .cdf association for Windows 2000, etc.
 
    static private class RestoreChannelDefinition extends Thread {

    // The string to be restored. 
        String channelDefinition;

        RestoreChannelDefinition(String channelDefinition) {
           this.channelDefinition = channelDefinition;
        }

    // implement the run method of Runable class.

        public void run() {
          try {
            Process process = Runtime.getRuntime().exec("cmd /c assoc "+
                                                        channelDefinition);
            try {
              process.waitFor();
            } catch (InterruptedException ee) {
              System.err.println("Error with assoc... 3 "+ee);
            }
          } catch (IOException ex) {
            System.err.println("Error running assoc on Windows...(3): "+ex);
          }
        }
    }

}

