/******************************************************************************
* 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.nio.file.*;
import java.util.*;
import javax.swing.*;
import java.awt.datatransfer.*;
import gsfc.nssdc.cdf.*;

/** CDFConvert is used to convert CDFs.  Conversions can be from
    older releases of CDF (eg. Version 2.4 CDFs) to the current release and/or
    to change the format, majority, or encoding.
 */

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

    static final long serialVersionUID = 1L;
    static int macLib = 0;
    static String cdfbase = null;
    static String libcdfPath = null;

    JFrame parentDriver;
/** The dialog for user interface. */
    JDialog dialog;

    JPanel panelx = new JPanel(new BorderLayout(), true);
/** The FileChooser for the file selection. */
    JFileChooser fileChooser = new JFileChooser();

/** The panel for text fields and selectable buttons which goes to dialog's
    north portion. */
    JPanel panel1 = new JPanel(new GridBagLayout(), true);
/** The panel containing all checkboxes goes to dialog's center portion. */
    JPanel panel2 = new JPanel(new BorderLayout(), true);
    JPanel panel2n = new JPanel(new GridBagLayout(), true);
    JPanel panel2c = new JPanel(new BorderLayout(), true);
    JPanel panel2s = new JPanel(new GridBagLayout(), true);
/** The panel containing panel31 and text area goes to dialog's south portion. */
    JPanel panel3 = new JPanel(new BorderLayout(), true);
/** The panel containing enter/help/quit buttons. */
    JPanel panel31 = new JPanel(new GridLayout(1, 3, 50, 20), true);
/** The panel containing enter/help/quit buttons. */
    JPanel tpanel1 = new JPanel(new BorderLayout(), true);
    JPanel tpanel2 = new JPanel(new BorderLayout(), true);
    JPanel tpanel3 = new JPanel(new BorderLayout(), true);
    JPanel tpanel4 = new JPanel(new BorderLayout(), true);
    JPanel tpanel5 = new JPanel(new BorderLayout(), true);

/** "Page Output" checkbox. */
    JCheckBox pgc = new JCheckBox("Page Output", false);
/** "Log Progress" checkbox. */
    JCheckBox lpc = new JCheckBox("Log Progress");
    int lpcX = 0;
/** "Delete Existing" checkbox. */
    JCheckBox dec = new JCheckBox("Delete Existing");
/** "Display Percentages" checkbox. */
    JCheckBox dpc = new JCheckBox("Display Percentages");
    int dpcX = 0;
/** "Report Info's" checkbox. */
    JCheckBox ric = new JCheckBox("Report Info's");
    int ricX = 0;
/** "Report Warnings" checkbox. */
    JCheckBox rwc = new JCheckBox("Report Warnings", true);
    int rwcX = 1;
/** "Report Errors" checkbox. */
    JCheckBox rec = new JCheckBox("Report Errors", true);
    int recX = 1;
/** "-0.0 to 0.0" checkbox. */
    JCheckBox zzc = new JCheckBox("-0.0 to 0.0");
/** "Display Statistics" checkbox. */
    JCheckBox dsc = new JCheckBox("Display Statistics");
    int dscX = 0;
/** "Backward" checkbox. */
    JCheckBox bkw = new JCheckBox("Backward");
    int bkwX = 0;
/** "About" checkbox. */
    JCheckBox abc = new JCheckBox("About");
    int abcX = 0;

/** A group radio buttons for Checksum. */
    ButtonGroup checksum = new ButtonGroup();
/** A group radio buttons for Checksum. */
    JRadioButton checksum0 = new JRadioButton("Source");
    JRadioButton checksum1 = new JRadioButton("No");
    JRadioButton checksum2 = new JRadioButton("MD5");
/** A radio button panel for Checksum. */
    JPanel checksumPanel = new JPanel(true);

/** "Run it Batch" checkbox. */
    JCheckBox bac = new JCheckBox("Run it Batch");

/** A group radio buttons for zMode. */
    ButtonGroup zmode = new ButtonGroup();
/** A group radio buttons for zMode. */
    JRadioButton zmode0 = new JRadioButton("Off");
    JRadioButton zmode1 = new JRadioButton("On/1");
    JRadioButton zmode2 = new JRadioButton("On/2");
/** A radio button panel for zMode. */
    JPanel zmodePanel = new JPanel(true);

/** A group radio buttons for Majority. */
    ButtonGroup majority = new ButtonGroup();
/** A group radio buttons for Majority. */
    JRadioButton majority0 = new JRadioButton("Source");
    JRadioButton majority1 = new JRadioButton("Row");
    JRadioButton majority2 = new JRadioButton("Column");
/** A radio button panel for Majority. */
    JPanel majorityPanel = new JPanel(true);

/** A group radio buttons for Format. */
    ButtonGroup format = new ButtonGroup();
/** A group radio buttons for Format. */
    JRadioButton format0 = new JRadioButton("Source");
    JRadioButton format1 = new JRadioButton("Single");
    JRadioButton format2 = new JRadioButton("Multi");
/** A radio button panel for Format. */
    JPanel formatPanel = new JPanel(true);

/** A group radio buttons for Encoding. */
    ButtonGroup encoding = new ButtonGroup();
/** A group radio buttons for Encoding. */
    JRadioButton encoding0 = new JRadioButton("Source");
    JRadioButton encoding1 = new JRadioButton("Host");
    JRadioButton encoding2 = new JRadioButton("Network");
    JRadioButton encoding3 = new JRadioButton("PPC");
    JRadioButton encoding4 = new JRadioButton("DECstation");
    JRadioButton encoding5 = new JRadioButton("Sun");
    JRadioButton encoding6 = new JRadioButton("VAX");
    JRadioButton encoding7 = new JRadioButton("SGi");
    JRadioButton encoding8 = new JRadioButton("PC");
    JRadioButton encoding9 = new JRadioButton("IBM RS");
    JRadioButton encoding10 = new JRadioButton("HP");
    JRadioButton encoding11 = new JRadioButton("NeXT");
    JRadioButton encoding12 = new JRadioButton("AlphaVMSd");
    JRadioButton encoding13 = new JRadioButton("AlphaVMSg");
    JRadioButton encoding14 = new JRadioButton("AlphaVMSi");
    JRadioButton encoding15 = new JRadioButton("AlphaOSF1");
    JRadioButton encoding16 = new JRadioButton("ARM_LITTLE");
    JRadioButton encoding17 = new JRadioButton("ARM_LITTLE");
    JRadioButton encoding18 = new JRadioButton("IA64VMSi");
    JRadioButton encoding19 = new JRadioButton("IA64VMSd");
    JRadioButton encoding20 = new JRadioButton("IA64VMSg");

/** A group radio buttons for Epoch data type conversion. */
    ButtonGroup epoch = new ButtonGroup();
/** A group radio buttons for Epoch. */
    JRadioButton epoch0 = new JRadioButton("None");
    JRadioButton epoch1 = new JRadioButton("EPOCH/EPOCH16-TT2000");
    JRadioButton epoch2 = new JRadioButton("TT2000-EPOCH");
    JRadioButton epoch3 = new JRadioButton("TT2000-EPOCH16");

/** A radio button panel for Encoding. */
    JPanel encodingPanel = new JPanel(true);

/** A radio button panel for Epoch. */
    JPanel epochPanel = new JPanel(true);

/** "Enter" button. */
    JButton entrb = new JButton(" Enter ");
/** "Help" button. */
    JButton helpb = new JButton(" Help ");
/** "Quit" button. */
    JButton quitb = new JButton(" Quit ");
/** "Select1" button for selecting the source CDF file. */
    JButton slt1 = new JButton("Select");
/** "Select2" button for selecting the destination CDF file. */
    JButton slt2 = new JButton("Select");
/** "Select3" button for selecting the skeleton CDF file. */
    JButton slt3 = new JButton("Select");

/** Text area for information. */
    JTextArea info = new JTextArea(20,60);

/** Text field for entering optional cache sizes. */
    JTextField cachesizes = new JTextField("",30);
/** Text field for entering optional sparseness. */
    JTextField sparseness = new JTextField("",20);
/** Text field for entering optional compression. */
    JTextField compression = new JTextField("",10);
/** Text field for entering the mandatory source CDF file name. */
    JTextField cdf1 = new JTextField("", 40);
/** Text field for entering the mandatory destination CDF file name. */
    JTextField cdf2 = new JTextField("", 40);
/** Text field for entering the optional skeleton table file name. */
    JTextField sklt = new JTextField("", 40);
/** Text field for entering the optional sort variable. */
    JTextField sort = new JTextField("", 5);
/** Text field for entering the optional blockingFactor. */
    JTextField blockingFactor = new JTextField("", 5);

/** A label of "Source CDF:" for the text field cdf1. */
    JLabel CDF1 = new JLabel("Source CDF: ");
/** A label of "Destination CDF:" for the text field cdf2. */
    JLabel CDF2 = new JLabel("Destination CDF: ");
/** A label of "Skeleton CDF:" for the text field sklt. */
    JLabel SKLT = new JLabel("Skeleton CDF: ");
/** A label of "Cache Sizes:" for the text field cachesizes. */
    JLabel CASS = new JLabel("Cache Sizes: ");
/** A label of "zMode:" for the radio button zmode. */
    JLabel ZMODE = new JLabel("zMode:  ");
/** A label of "Format:" for the combobox format. */
    JLabel FORMAT = new JLabel("Format:  ");
/** A label of "Encoding:" for the combobox encoding. */
    JLabel ENCODING = new JLabel("Encoding:  ");
/** A label of "Epoch:" for the combobox epoch. */
    JLabel EPOCH = new JLabel("Epoch:  ");
/** A label of "Majority:" for the combobox majority. */
    JLabel MAJORITY = new JLabel("Majority:  ");
/** A label of "Sparseness:" for the text field sparseness. */
    JLabel SPAR = new JLabel("Sparseness: ");
/** A label of "Compression:" for the text field compression. */
    JLabel COMP = new JLabel("Compression: ");
/** A label of "Checksum:" for the combobox majority. */
    JLabel CHECKSUM = new JLabel("Checksum:  ");
/** A label of "Sort:" for sorting variable. */
    JLabel SORT = new JLabel("Sort:  ");
/** A label of "BlockingFactor:" for BlockingFactor. */
    JLabel BlockingFactor = new JLabel("BlockingFactor:  ");
    
/** Scroll pane for the text area. */
    JScrollPane scroller;
/** Hold valid extensions for the CDF files for the file chooser. */
    String[] cdfs = {"cdf", "CDF"};
/** A file filter for the file chooser. */
    SimpleFileFilter filter = new SimpleFileFilter(cdfs,
                                                " CDF files (*.cdf, *.CDF)");
/** The command string. */
    String command = "cdfconvert ";
    String commandX;
    String[] cmds = new String[3];

/** Environment variable for the current directory. */
    String currentdir = System.getProperty("user.dir");
/** The file separator. */
    String separator = System.getProperty("file.separator");
    String strpo = "-nopage ";
    String strlp = " ";
    String strdp = " ";
    String strde = " ";
    String strri = "";
    String strrw = "w";
    String strre = "e";
    String strds = " ";
    String strzm = "";
    String strzz = " ";
    String strsp = " ";
    String strcp = " ";
    String strmj = "";
    String strfm = "";
    String strsr = " ";
    String stren = "";
    String strep = "";
    String strcs = "";
    String strsk = "";
    String strbw = " ";
    String stret = " ";
    String strcks = "";
    String report, Zmode, Majority, Format, Encoding, caches, temp, Checksum;
    String Epoch;
    String Caches = " ";
    String Compression = " ";
    String Sparseness = " ";
    String cdfspec = " ";
    String filespec = " ";
    String sparsespec = " ";
    String comprspec = " ";
    String skeleton;
    String skeletonFile;
    String cdfDelimiter, fileDelimiter, sktDelimiter;
/** A platform-dependent Runtime object. */
    Runtime runtime = Runtime.getRuntime();
/** A separate process to run the command. */
    Process process = null;
    int hlp = 0;
    int iba = 0;

/** The text field is currently getting the focus. */
    JTextField focused = null;
/** The text field previously was focused. */
    JTextField prevfocused = null;
/** Menu bar. */
    JMenuBar menuBar = new JMenuBar();
/** A menu: File. */
    JMenu menuFile = new JMenu("File");
/** A menu: Edit. */
    JMenu menuEdit = new JMenu("Edit");
/** A menu: Help. */
    JMenu menuHelp = new JMenu("Help");
/** An Edit menu item: Copy. */
    JMenuItem menuEditCopy = new JMenuItem("Copy");
/** An Edit menu item: Cut. */
    JMenuItem menuEditCut = new JMenuItem("Cut");
/** An Edit menu item: Paste. */
    JMenuItem menuEditPaste = new JMenuItem("Paste");
/** A File menu item: Exit. */
    JMenuItem menuFileExit = new JMenuItem("Exit");
/** A Help menu item: Help. */
    JMenuItem menuHelpHelp = new JMenuItem("Help");
    int istart = -1;
    int iend = -1;

    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 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    static int INITIAL_WIDTH = 650;
    static int INITIAL_HEIGHT = 600;
/** The default dialog modal (is set to false). */
    static boolean defaultModal = false;
/** The current dialog modal. */
    boolean modal;
    int frommain = 0;

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

    CDFConvert(JFrame parentDriver) {
        this(parentDriver, null, defaultModal);
    }

    CDFConvert(JFrame parentDriver, String cdfbase) {
        this(parentDriver, cdfbase, defaultModal);
    }

    CDFConvert(JFrame parentDriver, String cdfbase, boolean modal) {
        if (cdfbase == null) {
          cdfbase = System.getProperty("CDF_BASE");
          if (cdfbase == null)
            cdfbase = CDFToolsUtil.getenv("CDF_BASE");
        }
        if (cdfbase != null)
          command = cdfbase + separator + "bin" + separator + "cdfconvert ";
        else
          command = "cdfconvert ";
        dialog = new JDialog(this, modal);
        this.modal = modal;
	this.parentDriver = parentDriver;
    }

/** Set up the GUI stuff for user selection.
 */

    private void buildGUI() {

        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 {
		if (macLib == 1) new File(libcdfPath).delete();
		System.exit(1);
	      }
	   }
        };
        dialog.addWindowListener(l);
        dialog.setTitle("Enter   Parameters/qualifiers  for  CDFconvert");
        dialog.setSize(INITIAL_WIDTH, INITIAL_HEIGHT);
        dialog.setLocation(screenSize.width/2 - INITIAL_WIDTH/2,
                          screenSize.height/2 - INITIAL_HEIGHT/2);
        dialog.getContentPane().setLayout(new BorderLayout());

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

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

        // add the menu items to file
        menuFile.add(menuFileExit);
        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);


        // Panel 1

	makeJButton(panel1, Box.createRigidArea(vpad5), 0, 0, 1, 1, 1.0, 1.0);
        makeJButton(panel1, CDF1, 0, 1, 1, 1, 1.0, 1.0);
        makeJButton(panel1, cdf1, 1, 1, 1, 1, 1.0, 1.0);
	makeJButton(panel1, Box.createRigidArea(hpad10), 2, 1, 1, 1, 1.0, 1.0);
        makeJButton(panel1, slt1, 3, 1, 1, 1, 1.0, 1.0);
        makeJButton(panel1, CDF2, 0, 2, 1, 1, 1.0, 1.0);
        makeJButton(panel1, cdf2, 1, 2, 1, 1, 1.0, 1.0);
	makeJButton(panel1, Box.createRigidArea(hpad10), 2, 2, 1, 1, 1.0, 1.0);
        makeJButton(panel1, slt2, 3, 2, 1, 1, 1.0, 1.0);
	makeJButton(panel1, Box.createRigidArea(vpad20), 0, 3, 1, 1, 1.0, 1.0);

        cdf1.addActionListener(this);
        cdf1.addFocusListener(this);
        cdf1.addMouseListener(this);
	cdf1.setToolTipText("Enter the source CDF (without extension) to convert");
        cdf2.addActionListener(this);
        cdf2.addFocusListener(this);
        cdf2.addMouseListener(this);
        cdf2.setToolTipText("Enter the destination CDF (without extension) from the converted source");
        sklt.addActionListener(this);
        sklt.addFocusListener(this);
        sklt.addMouseListener(this);
        sklt.setToolTipText("Enter the skeleton CDF (without extension) to be used during the converion");
        slt1.addActionListener(this);
        slt1.setToolTipText("Use the file chooser to select the source CDF");
        slt2.addActionListener(this);
        slt2.setToolTipText("Use the file chooser to select the destination CDF");
        slt3.addActionListener(this);
        slt3.setToolTipText("Use the file chooser to select a skleleton CDF");
        CDF1.setFont(boldFont);
        cdf1.setFont(boldFont);
        CDF2.setFont(boldFont);
        cdf2.setFont(boldFont);
        SKLT.setFont(boldFont);
        sklt.setFont(boldFont);
//	dialog.getContentPane().add(panel1,BorderLayout.NORTH);
	panelx.add(panel1,BorderLayout.NORTH);
	
        // Panel 2

        // Initialize the zMode radio button.
        ZModeListener zModeListener = new ZModeListener();
        zmode0.setActionCommand("0");
        zmode1.setActionCommand("1");
        zmode2.setActionCommand("2");
        zmode0.addActionListener(zModeListener);
        zmode1.addActionListener(zModeListener);
        zmode2.addActionListener(zModeListener);
        zmode0.setSelected(true);
        zmode.add(zmode0);
        zmode.add(zmode1);
        zmode.add(zmode2);
	zmode0.setToolTipText("Use variables as-is from the source CDF");
        zmode1.setToolTipText("Use zMode/1 for variables written to the destination CDF");
        zmode2.setToolTipText("Use zMode/2 for variables written to the destination CDF");
        zmodePanel.setLayout(new FlowLayout());
        zmodePanel.add(zmode0);
        zmodePanel.add(zmode1);
        zmodePanel.add(zmode2);

        // Initialize the format radio button.
        FormatListener formatListener = new FormatListener();
        format0.setActionCommand("source");
        format1.setActionCommand("single");
        format2.setActionCommand("multi");
        format0.addActionListener(formatListener);
        format1.addActionListener(formatListener);
        format2.addActionListener(formatListener);
        format0.setSelected(true);
        format.add(format0);
        format.add(format1);
        format.add(format2);
        format0.setToolTipText("Use the file format from the source CDF for the destination CDF");
        format1.setToolTipText("Use Single file format for the destination CDF");
        format2.setToolTipText("Use Multi file format for the destination CDF");
        formatPanel.setLayout(new FlowLayout());
        formatPanel.add(format0);
        formatPanel.add(format1);
        formatPanel.add(format2);

        // Initialize the majority radio button.
        MajorityListener majorityListener = new MajorityListener();
        majority0.setActionCommand("source");
        majority1.setActionCommand("row");
        majority2.setActionCommand("column");
        majority0.addActionListener(majorityListener);
        majority1.addActionListener(majorityListener);
        majority2.addActionListener(majorityListener);
        majority0.setSelected(true);
        majority.add(majority0);
        majority.add(majority1);
        majority.add(majority2);
        majority0.setToolTipText("Use the majority from the source CDF for the destination CDF");
        majority1.setToolTipText("Use Row majority for the destination CDF");
        majority2.setToolTipText("Use Column majority for the destination CDF");
        majorityPanel.setLayout(new FlowLayout());
        majorityPanel.add(majority0);
        majorityPanel.add(majority1);
        majorityPanel.add(majority2);

        // Initialize the checksum radio button.
        ChecksumListener checksumListener = new ChecksumListener();
        checksum0.setActionCommand("source");
        checksum1.setActionCommand("no");
        checksum2.setActionCommand("md5");
        checksum0.addActionListener(checksumListener);
        checksum1.addActionListener(checksumListener);
        checksum2.addActionListener(checksumListener);
	try {
          if (CDF.getChecksumEnvVar() == 1) {
	    checksum2.setSelected(true);
	    strcks = "md5";
	  } else {
	    checksum0.setSelected(true);
	    strcks = "";
          }
	} catch (CDFException sum) {
	  checksum0.setSelected(true);
	  strcks = "";
	}
        checksum.add(checksum0);
        checksum.add(checksum1);
        checksum.add(checksum2);
        checksum0.setToolTipText("Use the checksum from the source CDF for the destination CDF");
        checksum1.setToolTipText("Do not use checksum for the destination CDF");
        checksum2.setToolTipText("Use MD5 method for checksum for the destination CDF");
        checksumPanel.setLayout(new FlowLayout());
        checksumPanel.add(checksum0);
        checksumPanel.add(checksum1);
        checksumPanel.add(checksum2);

        // Initialize the encoding radio button.
        EncodingListener encodingListener = new EncodingListener();
        encoding0.setActionCommand("source");
        encoding1.setActionCommand("host");
        encoding2.setActionCommand("network");
        encoding3.setActionCommand("ppc");
        encoding4.setActionCommand("decstation");
        encoding5.setActionCommand("sun");
        encoding6.setActionCommand("vax");
        encoding7.setActionCommand("sgi");
        encoding8.setActionCommand("ibmpc");
        encoding9.setActionCommand("ibmrs");
        encoding10.setActionCommand("hp");
        encoding11.setActionCommand("next");
        encoding12.setActionCommand("alphavmsd");
        encoding13.setActionCommand("alphavmsg");
        encoding14.setActionCommand("alphavmsi");
        encoding15.setActionCommand("alphaosf1");
        encoding16.setActionCommand("arm_little");
        encoding17.setActionCommand("arm_big");
        encoding18.setActionCommand("ia64vmsi");
        encoding19.setActionCommand("ia64vmsd");
        encoding20.setActionCommand("ia64vmsg");
        encoding0.addActionListener(encodingListener);
        encoding1.addActionListener(encodingListener);
        encoding2.addActionListener(encodingListener);
        encoding3.addActionListener(encodingListener);
        encoding4.addActionListener(encodingListener);
        encoding5.addActionListener(encodingListener);
        encoding6.addActionListener(encodingListener);
        encoding7.addActionListener(encodingListener);
        encoding8.addActionListener(encodingListener);
        encoding9.addActionListener(encodingListener);
        encoding10.addActionListener(encodingListener);
        encoding11.addActionListener(encodingListener);
        encoding12.addActionListener(encodingListener);
        encoding13.addActionListener(encodingListener);
        encoding14.addActionListener(encodingListener);
        encoding15.addActionListener(encodingListener);
        encoding16.addActionListener(encodingListener);
        encoding17.addActionListener(encodingListener);
        encoding18.addActionListener(encodingListener);
        encoding19.addActionListener(encodingListener);
        encoding20.addActionListener(encodingListener);

        encoding0.setSelected(true);
        encoding.add(encoding0);
        encoding.add(encoding1);
        encoding.add(encoding2);
        encoding.add(encoding3);
        encoding.add(encoding4);
        encoding.add(encoding5);
        encoding.add(encoding6);
        encoding.add(encoding7);
        encoding.add(encoding8);
        encoding.add(encoding9);
        encoding.add(encoding10);
        encoding.add(encoding11);
        encoding.add(encoding12);
        encoding.add(encoding13);
        encoding.add(encoding14);
        encoding.add(encoding15);
        encoding.add(encoding16);
        encoding.add(encoding17);
        encoding.add(encoding18);
        encoding.add(encoding19);
        encoding.add(encoding20);

        encoding0.setToolTipText("Use the encoding from the source CDF for the destination CDF");
        encoding1.setToolTipText("Use the host machine encoding for the destination CDF");
        encoding2.setToolTipText("Use the network encoding for the destination CDF");
        encoding3.setToolTipText("Use the PPC encoding for the destination CDF");
        encoding4.setToolTipText("Use the DECStation encoding for the destination CDF");
        encoding5.setToolTipText("Use the Sun encoding for the destination CDF");
        encoding6.setToolTipText("Use the VAX encoding for the destination CDF");
        encoding7.setToolTipText("Use the SGi encoding for the destination CDF");
        encoding8.setToolTipText("Use the PC encoding for the destination CDF");
        encoding9.setToolTipText("Use the IBM RS6000 encoding for the destination CDF");
        encoding10.setToolTipText("Use the HP encoding for the destination CDF");
        encoding11.setToolTipText("Use the NeXT encoding from he destination CDF");
        encoding12.setToolTipText("Use the AlphaVMSd encoding for the destination CDF");
        encoding13.setToolTipText("Use the AlphaVMSg encoding for the destination CDF");
        encoding14.setToolTipText("Use the AlphaVMSi encoding for the destination CDF");
        encoding15.setToolTipText("Use the AlphaOSF1 encoding for the destination CDF");
        encoding16.setToolTipText("Use the ARM_LITTLE encoding from he destination CDF");
        encoding17.setToolTipText("Use the ARM_BIG encoding for the destination CDF");
        encoding18.setToolTipText("Use the IA64VMSi encoding for the destination CDF");
        encoding19.setToolTipText("Use the IA64VMSd encoding for the destination CDF");
        encoding20.setToolTipText("Use the IA64OSFg encoding for the destination CDF");

        encodingPanel.setLayout(new GridLayout(3,6));
        encodingPanel.add(ENCODING);
        encodingPanel.add(encoding0);
        encodingPanel.add(encoding1);
        encodingPanel.add(encoding2);
        encodingPanel.add(encoding3);
        encodingPanel.add(encoding4);
        encodingPanel.add(encoding5);
        encodingPanel.add(encoding6);
        encodingPanel.add(encoding7);
        encodingPanel.add(encoding8);
        encodingPanel.add(encoding9);
        encodingPanel.add(encoding10);
        encodingPanel.add(encoding11);
        encodingPanel.add(encoding12);
        encodingPanel.add(encoding13);
        encodingPanel.add(encoding14);
        encodingPanel.add(encoding15);
        encodingPanel.add(encoding16);
        encodingPanel.add(encoding17);
        encodingPanel.add(encoding18);
        encodingPanel.add(encoding19);
        encodingPanel.add(encoding20);

        // Initialize the epoch radio button.
        EpochListener epochListener = new EpochListener();
        epoch0.setActionCommand("");
        epoch1.setActionCommand("epoch2tt2000");
        epoch2.setActionCommand("tt20002epoch");
        epoch3.setActionCommand("tt20002depoch");
        epoch0.addActionListener(epochListener);
        epoch1.addActionListener(epochListener);
        epoch2.addActionListener(epochListener);
        epoch3.addActionListener(epochListener);
        epoch0.setSelected(true);
        epoch.add(epoch0);
        epoch.add(epoch1);
        epoch.add(epoch2);
        epoch.add(epoch3);
        epoch0.setToolTipText("Keep the CDF epoch data type as is");
        epoch1.setToolTipText("Convert the CDF epoch type from EPOCH/EPOCH16 to TT2000");
        epoch2.setToolTipText("Convert the CDF epoch type from TT2000 to EPOCH");
        epoch3.setToolTipText("Convert the CDF epoch type from TT2000 to EPOCH16");
        epochPanel.setLayout(new GridLayout(1,8));
        epochPanel.add(EPOCH);
        epochPanel.add(epoch0);
        epochPanel.add(epoch1);
        epochPanel.add(epoch2);
        epochPanel.add(epoch3);

	makeJButton(panel2n, pgc, 0, 0, 1, 1, 1.0, 1.0);
        makeJButton(panel2n, ric, 1, 0, 1, 1, 1.0, 1.0);
        makeJButton(panel2n, dsc, 2, 0, 1, 1, 1.0, 1.0);
	tpanel1.add(FORMAT,BorderLayout.WEST);
	tpanel1.add(formatPanel, BorderLayout.CENTER);
	tpanel1.add(Box.createRigidArea(hpad20), BorderLayout.EAST);
        makeJButton(panel2n, tpanel1, 3, 0, 1, 1, 1.0, 1.0);
        makeJButton(panel2n, lpc, 0, 1, 1, 1, 1.0, 1.0);
        makeJButton(panel2n, rwc, 1, 1, 1, 1, 1.0, 1.0);
        makeJButton(panel2n, zzc, 2, 1, 1, 1, 1.0, 1.0);
	tpanel2.add(MAJORITY,BorderLayout.WEST);
	tpanel2.add(majorityPanel, BorderLayout.CENTER);
	tpanel2.add(Box.createRigidArea(hpad20), BorderLayout.EAST);
        makeJButton(panel2n, tpanel2, 3, 1, 1, 1, 1.0, 1.0);
        makeJButton(panel2n, dpc, 0, 2, 1, 1, 1.0, 1.0);
        makeJButton(panel2n, rec, 1, 2, 1, 1, 1.0, 1.0);
        tpanel4.add(ZMODE,BorderLayout.WEST);
        tpanel4.add(zmodePanel, BorderLayout.CENTER);
        tpanel4.add(Box.createRigidArea(hpad20), BorderLayout.EAST);
        makeJButton(panel2n, tpanel4, 2, 2, 1, 1, 1.0, 1.0);
        makeJButton(panel2n, dec, 0, 3, 1, 1, 1.0, 1.0);
	int iijj = 1;
	try {
	  if (CDF.getLibraryVersion().charAt(0) == '3') {
	    if (CDF.getFileBackwardEnvVar() == 0) { // Env var is not true
	      makeJButton(panel2n, bkw, 1, 3, 1, 1, 1.0, 1.0);
	      iijj++;
	    }
	  }
	} catch (CDFException ex) {}
        makeJButton(panel2n, abc, iijj, 3, 1, 1, 1.0, 1.0);
        tpanel5.add(CHECKSUM,BorderLayout.WEST);
        tpanel5.add(checksumPanel, BorderLayout.CENTER);
        tpanel5.add(Box.createRigidArea(hpad20), BorderLayout.EAST);
	makeJButton(panel2n, tpanel5, iijj+1, 3, 1, 1, 1.0, 1.0);

	panel2c.add(encodingPanel, BorderLayout.CENTER);
        panel2c.add(epochPanel, BorderLayout.SOUTH);

        makeJButton(panel2s, SKLT, 0, 1, 1, 1, 1.0, 1.0);
        makeJButton(panel2s, sklt, 1, 1, 1, 1, 1.0, 1.0);
        makeJButton(panel2s, slt3, 2, 1, 1, 1, 1.0, 1.0);
        makeJButton(panel2s, CASS, 0, 2, 1, 1, 1.0, 1.0);
        makeJButton(panel2s, cachesizes, 1, 2, 2, 1, 1.0, 1.0);
        makeJButton(panel2s, SPAR, 0, 3, 1, 1, 1.0, 1.0);
        makeJButton(panel2s, sparseness, 1, 3, 2, 1, 1.0, 1.0);
        makeJButton(panel2s, COMP, 0, 4, 1, 1, 1.0, 1.0);
        makeJButton(panel2s, compression, 1, 4, 2, 1, 1.0, 1.0);
	makeJButton(panel2s, Box.createRigidArea(vpad20), 0, 5, 1, 1, 1.0, 1.0);

        panel2.add(panel2n, BorderLayout.NORTH);
        panel2.add(panel2c, BorderLayout.CENTER);
        panel2.add(panel2s, BorderLayout.SOUTH);

	pgc.addItemListener(this);
	pgc.setToolTipText("Select to display the output one page at a time -- not avaiable for Java");
        ric.addItemListener(this);
	ric.setToolTipText("Select to report informational messages from the CDF library calls");
        lpc.addItemListener(this);
        lpc.setToolTipText("Select to display the progress of a conversion");
        rwc.addItemListener(this);
        rwc.setToolTipText("Select to report warning messages from the CDF library calls");
        dpc.addItemListener(this);
        dpc.setToolTipText("Select to display the conversion percentage of a variable");
        rec.addItemListener(this);
        rec.setToolTipText("Select to report error messages from the CDF library calls");
        dec.addItemListener(this);
        dec.setToolTipText("Select to delete the existing destination CDF");
        dsc.addItemListener(this);
        dsc.setToolTipText("Select to display caching statistics after conversion");
        zzc.addItemListener(this);
        zzc.setToolTipText("Select to convert -0.0 to 0.0");
        bkw.addItemListener(this);
        bkw.setToolTipText("Convert the file to a backward V2.7 version");

        abc.addItemListener(this);
        abc.setToolTipText("Display the current version");
	bac.addItemListener(this);
	bac.setToolTipText("Select to set up and run the conversion by a batch job");
        cachesizes.addActionListener(this);
        cachesizes.addFocusListener(this);
        cachesizes.addMouseListener(this);
        cachesizes.setToolTipText("Enter the cache sizes for dotCDF, staging and compression scratch files in 512 bytes buffer");
        sparseness.addActionListener(this);
        sparseness.addFocusListener(this);
        sparseness.addMouseListener(this);
        sparseness.setToolTipText("Enter the sparse types for the variables in the destination CDF");
        compression.addActionListener(this);
        compression.addFocusListener(this);
        compression.addMouseListener(this);
        compression.setToolTipText("Enter the types of compression to be used with the destination CDF and/or variables");
        sort.addActionListener(this);
        sort.addFocusListener(this);
        sort.addMouseListener(this);
        sort.setToolTipText("Enter the variable name, .e.g., Epoch, that is used for sorting.");
        blockingFactor.addActionListener(this);
        blockingFactor.addFocusListener(this);
        blockingFactor.addMouseListener(this);
        blockingFactor.setToolTipText("Enter the blocking factor for all of the compressed variables.");
	CASS.setFont(boldFont);
        cachesizes.setFont(boldFont);
        SPAR.setFont(boldFont);
        sparseness.setFont(boldFont);
        COMP.setFont(boldFont);
        compression.setFont(boldFont);

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

        // Panel 3 (buttons and text area)

        panel31.add(entrb);
        panel31.add(helpb);
        panel31.add(quitb);
  	panel3.add(panel31, BorderLayout.NORTH);
	panel3.add(Box.createRigidArea(vpad30),BorderLayout.CENTER);

        // Listen for events on buttons
        entrb.addActionListener(this);
	entrb.setToolTipText("Run CDFConvert");
        helpb.addActionListener(this);
	helpb.setToolTipText("Get the complete help information");
        quitb.addActionListener(this);
	quitb.setToolTipText("Exit CDFConvert");

	// Text Area
  	info.setEditable(false);
        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);
//        panel3.add(scroller, BorderLayout.SOUTH);
//	dialog.getContentPane().add(panel3, BorderLayout.SOUTH);
	panelx.add(panel3, BorderLayout.SOUTH);
  	info.setVisible(true);

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

    }

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

    public void run() {
        buildGUI();
	dialog.pack();
	fileChooser.setCurrentDirectory(new File(currentdir));
	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);
        info.setText("");
	cdf1.setText("");
	cdf2.setText("");
	sklt.setText("");
	cachesizes.setText("");
	sparseness.setText("");
	compression.setText("");
    }

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

    public void actionPerformed(ActionEvent evt) {
	Object obj = evt.getSource();
	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 {
	     if (macLib == 1) new File(libcdfPath).delete();
	     System.exit(1);
	   }
	} else if (obj == slt1 || obj == slt2 || obj == slt3) { 
	// for "Select 1", "Select 2" or "Select 3" button
             if (obj == slt1) { // for "Select1" button
                doFileChooser("Select/enter the source CDF", cdf1, 1, filter);
             } else if (obj == slt2) { // for "Select2" button
                doFileChooser("Select/enter the destination of CDF", cdf2, 1, filter);
             } else { // for "Select3" button
                doFileChooser("Select/enter the Skeleton CDF", sklt, 1, filter);
	     }
	} else if (obj == helpb || obj == menuHelpHelp) { // for "Help" 
		commandX = command + "-java";
		hlp = 1;
		iba = 0;
                String OS = System.getProperty("os.name").toLowerCase();
                if (OS.indexOf("windows") != -1) {
                    cmds[0] = commandX;
                } else if (OS.indexOf("vms") != -1) {
                    cmds[0] = commandX;
                } else {
                    cmds[0] = "/bin/sh";
                    cmds[1] = "-c";
                    cmds[2] = commandX;
                }
                runit(cmds);
                // runit(commandX);
		hlp = 0;
	} else if (obj == entrb) { // for "Enter" button
                cdfspec = cdf1.getText();
                filespec = cdf2.getText();
                if ((filespec.equals("") || filespec.trim().equals("")) ||
                    (cdfspec.equals("") || cdfspec.trim().equals(""))) {
                  info.setText("");
                  info.append("Please enter a source and destination CDF...");
                  Toolkit.getDefaultToolkit().beep();
                  return;
                }
                filespec = filespec.trim();
                cdfspec = cdfspec.trim();

		temp = strri + strrw + strre;
		if (temp.length() == 0) report = " ";
		else if (temp.length() == 3) report = "-report \"i,w,e\" ";
		else if (temp.length() == 1) {
		   if (strri.length() == 1) report = "-report \"i\" ";
		   if (strrw.length() == 1) report = "-report \"w\" ";
		   if (strre.length() == 1) report = "-report \"e\" ";
		} else {
		   if (strri.length() == 0) report = "-report \"w,e\" ";
		   if (strrw.length() == 0) report = "-report \"i,e\" ";
		   if (strre.length() == 0) report = "-report \"i,w\" ";
		}
		if (sklt.getText().trim().equals("")) {
		  skeleton = " ";
		  skeletonFile = " ";
		} else {
		  skeleton = "-skeleton "; 
		  skeletonFile = sklt.getText().trim();
		}

                strcs = cachesizes.getText();
                if (strcs.equals("") || strcs.trim().equals("")) Caches = " ";
                else if (strcs.startsWith("\"") || strcs.startsWith("\'"))
                       Caches = "-cache " + strcs.substring(1,strcs.length()-2) + " ";
                     else Caches = "-cache " + strcs + " ";

		if (strmj.equals("") || strmj.equals("source")) Majority = " ";
                else Majority = " -" + strmj + " ";

                if (strzm.equals("")) Zmode = " ";
                else Zmode = " -zmode " + strzm + " ";

                if (strfm.equals("") || strfm.equals("source")) Format = " ";
                else Format = " -" + strfm + " ";

		if (stren.equals("") || stren.equals("source")) 
			Encoding = " ";
                else if (stren.equals("host") || stren.equals("network")) 
		        Encoding = "-" + stren + " ";
		else 
		  Encoding = "-encoding " + stren + " ";

                if (strep.equals("")) Epoch = "";
                else Epoch = "-" + strep;

                strsp = sparseness.getText();
                if (strsp.equals("") || strsp.trim().equals("")) Sparseness = " ";
                else if (strsp.startsWith("\"") || strsp.startsWith("\'"))
                       Sparseness = "-sparseness " + strsp.substring(1,strsp.length()-2) + " ";
                     else Sparseness = "-sparseness " + strsp + " ";

                strcp = compression.getText();
                if (strcp.equals("") || strcp.trim().equals("")) Compression = " ";
                else if (strcp.startsWith("\"") || strcp.startsWith("\'"))
                       Compression = "-compression " + strcp.substring(1,strcp.length()-2) + " ";
                     else Compression = "-compression " + strcp + " ";

                if (strcks.equals("") || strcks.equals("source")) 
		  Checksum = " -checksum source ";
                else if (strcks.equals("no")) Checksum = " -checksum no ";
		else if (strcks.equals("md5")) Checksum = " -checksum md5 ";

                if (cdfspec.startsWith("'")) cdfDelimiter = " ";
                else if (cdfspec.startsWith("\"")) cdfDelimiter = " ";
                else cdfDelimiter = "\"";

                if (filespec.startsWith("'")) fileDelimiter = " ";
                else if (filespec.startsWith("\"")) fileDelimiter = " ";
                else fileDelimiter = "\"";

                String yyy;
                if (skeleton.equals(" "))
                  yyy = "";
                else {
                  if (skeletonFile.startsWith("'")) sktDelimiter = " ";
                  else if (skeletonFile.startsWith("\"")) sktDelimiter = " ";
                  else sktDelimiter = "\"";
                  yyy = sktDelimiter + skeletonFile.trim() + sktDelimiter;
                }

                commandX = command + strpo + strds + strlp + skeleton + yyy +
//			   sktDelimiter + skeletonFile + sktDelimiter +
                           Caches + report + cdfDelimiter + cdfspec + 
			   cdfDelimiter + Zmode + strzz + fileDelimiter +  
			   filespec + fileDelimiter + " " + Format + 
			   Majority + Encoding + strde + Compression + 
                           Sparseness + " " + strbw + " " + Checksum + " " +
                           stret + Epoch;
                /*********************************
		commandX = command + strpo + strds + strlp + skeleton + 
			   " " + skeletonFile + " " +
                           Caches + report + " "+ cdfspec + " " + 
                           Zmode + strzz + " " +  filespec + " " + 
                           " " + Format + 
			   Majority + Encoding + strde + Compression + 
                           Sparseness + " " + strbw + " " + Checksum;
		*********************************/
                String OS = System.getProperty("os.name").toLowerCase();
                if (OS.indexOf("windows") != -1) {
                    cmds[0] = commandX;
                } else if (OS.indexOf("vms") != -1) {
                    commandX = commandX.replace('-', '/');
                    cmds[0] = commandX;
                } else {
                    cmds[0] = "/bin/sh";
                    cmds[1] = "-c";
                    cmds[2] = commandX;
                }
                runit(cmds);
	} else if (obj == cdf1) {
		cdfspec = cdf1.getText();
	} else if (obj == cdf2) {
                filespec = cdf2.getText();
	} else if (obj == cachesizes) {
		strcs = cachesizes.getText();
	} else if (obj == sparseness) {
                strsp = sparseness.getText();
	} else if (obj == compression) {
                strcp = compression.getText();
        } 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) {
		    info.setText("Where to paste to?");
                    Toolkit.getDefaultToolkit().beep();
                } else {
                  if (istart != -1) {
                    focused.setSelectionStart(istart);
                    focused.setSelectionEnd(iend);
                  }
                  String tempX;
                  try {
                    tempX = (String) Toolkit.getDefaultToolkit().
                                    getSystemClipboard().getContents(this).
                                    getTransferData(DataFlavor.stringFlavor);
                    if (tempX == null) { // no clipboard text
                        info.setText("No current selection on clipboard");
                        Toolkit.getDefaultToolkit().beep();
                    } else if (tempX.indexOf("\n") != -1) { // multiple lines
                        info.setText("Multiple lines selection on clipboard - not allowed:");
                        info.append("\n\n");
                        info.append(tempX);
                        Toolkit.getDefaultToolkit().beep();
                    } else { focused.paste();}
                  } catch (Exception e) {}
                }
	}
    }

/** Action for radio buttons for zMode
 */

    class ZModeListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
           strzm = e.getActionCommand();
        }
    }

/** Action for radio buttons for Format
 */

    class FormatListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
           strfm = e.getActionCommand();
        }
    }

/** Action for radio buttons for Majority
 */

    class MajorityListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
           strmj = e.getActionCommand();
        }
    }

/** Action for radio buttons for Encoding
 */

    class EncodingListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
           stren = e.getActionCommand();
        }
    }

/** Action for radio buttons for Epoch
 */

    class EpochListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
           strep = e.getActionCommand();
        }
    }

/** Action for radio buttons for Checksum
 */

    class ChecksumListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
           strcks = e.getActionCommand();
        }
    }

/** Action for checkboxs selection
 */

    public void itemStateChanged(ItemEvent evt) {
	Object obj = evt.getSource();
	if (obj == pgc) { // "Page Output" checkbox
	   if (pgc.isSelected()) {
		info.setText("");                                              
		info.append("Page output is not allowed in Java");
		pgc.setSelected(false);
		Toolkit.getDefaultToolkit().beep();
	        strpo = "-nopage ";
	   }
        } else if (obj == bkw) { // "Backward" checkbox
           if (bkw.isSelected()) {
		strbw = "-backward";
                bkwX = 1;
           }
        } else if (obj == abc) { // "About" checkbox 
	   if (abc.isSelected()) {
		abcX = 1;
		iba = 0;
		commandX = command + " -about";
                String OS = System.getProperty("os.name").toLowerCase();
                if (OS.indexOf("windows") != -1) {
                    cmds[0] = commandX;
                } else if (OS.indexOf("vms") != -1) {
                    cmds[0] = commandX;
                } else {
                    cmds[0] = "/bin/sh";
                    cmds[1] = "-c";
                    cmds[2] = commandX;
                }
                runit(cmds);
                // runit(commandX);
		abc.setSelected(false);
		abcX = 0;
	   }
        } else if (obj == bac) { // "Run it Batch" checkbox
           if (bac.isSelected()) {
		iba = 1;
                if (cdf1.getText().equals("") || cdf2.getText().equals("")) {
                   info.setText("");
                   info.append("Please enter a source and destination CDF for a batch run...");
                   Toolkit.getDefaultToolkit().beep();
                }
	   } else 
                iba = 0;
	} else if (obj == ric) { // "Report Info's" checkbox
           if (ric.isSelected()) {
		strri = "i";
		ricX = 1;
	   } else {
		strri = "";
		ricX = 0;
	   }
        } else if (obj == rwc) { // "Report Warnings" checkbox 
           if (rwc.isSelected()) {
                strrw = "w";
		rwcX = 1;
           } else {
                strrw = "";
		rwcX = 0;
	   }
        } else if (obj == rec) { // "Report Errors" checkbox
           if (rec.isSelected()) {
                strre = "e";
		recX = 1;
           } else {
                strre = "";
		recX = 0;
	   }
        } else if (obj == lpc) { // "Log Progress" checkbox
           if (lpc.isSelected()) {
                strlp = "-log ";
		lpcX = 1;
           } else {
                strlp = "-nolog ";
		lpcX = 0;
	   }
        } else if (obj == dec) { // "Delete Existing" checkbox
           if (dec.isSelected())
                strde = "-delete ";
           else
                strde = "-nodelete ";
	} else if (obj == zzc) { // "-0.0 to 0.0" checkbox
           if (zzc.isSelected())
                strzz = "-neg2posfp0 ";
           else
                strzz = "-noneg2posfp0 ";
	} else if (obj == dsc) { // "Display Statistics" checkbox
           if (dsc.isSelected()) {
                strds = "-statistics ";
		dscX = 1;
           } else {
                strds = "-nostatistics ";
		dscX = 0;
	   }
        } else if (obj == dpc) { // "Display Percentages" checkbox
           if (dpc.isSelected()) {
                strdp = "-percent ";
		dpcX = 1;
           } else {
                strdp = "-nopercent ";
		dpcX = 0;
	   }
	}
    }

    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());
        }
    }

    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;
          }
        }
    }

/** Set up gridbaglayout.
 */

    private void makeJButton(Container cont, Object arg,
            int x, int y, int w, int h, double weightx, double weighty) {
        GridBagLayout gbl = (GridBagLayout)cont.getLayout();
        GridBagConstraints c = new GridBagConstraints();
        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);
    }

/** Execute a command as a separate process for the user selection and returns
    the results in the text area.
 */

    private void runit(String[] command) {
    // private void runit(String command) {
	try {
           String osName = System.getProperty("os.name");
           String cwd = System.getProperty("user.dir");
           libcdfPath = cwd + "/libcdf.dylib";
           if (osName.toLowerCase().indexOf("mac") != -1) {
               File libcdf = new File(libcdfPath);
               if (libcdf.exists()) {
                   macLib = 0;
               } else {
                 if (Files.isWritable(Paths.get(cwd))) {
                   try {
                     cdfbase = System.getProperty("CDF_BASE");
                     if (cdfbase == null)
                         cdfbase = CDFToolsUtil.getenv("CDF_BASE");
                     Files.copy(Paths.get(cdfbase+"/lib/libcdf.dylib"),
                                Paths.get(libcdfPath),
                                StandardCopyOption.REPLACE_EXISTING);
                     macLib = 1;
                   } catch (Exception ex) {
                     System.out.println ("**** Error for copying... "+ex);
                   }
                 }
               }
           }


           if (command[1] != null)
                  process = runtime.exec(command);
           else
                  process = runtime.exec(command[0]);

	   if (iba == 1 && hlp == 0 && abcX == 0) {
                   info.setText("Program is submitted...\n\n");
		   info.append("A CDF: " + filespec + 
				".cdf  will/may be created.");
            } else {
                  if (abcX == 0 && hlp == 0) {
                          info.setText("");
                          info.append("Program is running...\n");
                  }
            }
            Dimension dialogSize = dialog.getSize();
            ((JComponent)(dialog.getContentPane())).paintImmediately(
                                                0, 0, dialogSize.width, dialogSize.height);

            InputStreamReader inReader = new InputStreamReader(process.getInputStream(), "UTF-8");
            BufferedReader inStream = new BufferedReader(inReader, 8192);

	    boolean first = true;
	    String line = null;
            if (hlp == 1 || abcX == 1 || ricX == 1 || rwcX == 1 || recX == 1 ||
                lpcX == 1 || dscX == 1 || dpcX == 1) {
                  while ((line = inStream.readLine()) != null) {
		    if (first) {
			info.setText("");
			first = false;
		    }
                    info.append(line+"\n");
		  }
            }
	    process.waitFor(); 
	    info.setCaretPosition(0);
            if (process.exitValue() == 1) {
		  Toolkit.getDefaultToolkit().beep();
		  info.append("ERROR: error is detected... job failed\n");
	    } else {
		  if (iba == 1) {
		    if (info.getText().toLowerCase().indexOf("error") == -1)
                            info.append("Done!\n\n");
	    	    else
			    info.append("ERROR: converting file is not created or is invalide.\n");
		  }
	    }
        } catch (Exception e) {
              info.setText("error executing: "+e);
              Toolkit.getDefaultToolkit().beep();
        }
    }

/** Initiate the file chooser and strip the extension for the selected file
    if necessary
 */

    private void doFileChooser (String title, JTextField textField, int theone, SimpleFileFilter filter) {
//	JFileChooser fileChooser = new JFileChooser();
	ExampleFileView fileView = new ExampleFileView();
//        fileChooser.setCurrentDirectory(new File(currentdir));
	fileChooser.setDialogTitle(title);
        if (filter != null) {
	  fileChooser.addChoosableFileFilter(filter);
	  fileChooser.setFileFilter(filter);
	}
        try {
           fileView.putIcon("cdf",
                            new ImageIcon(CDFConvert.class.getResource("CDF_Logo3.gif")));
           fileView.putIcon("CDF",
                            new ImageIcon(CDFConvert.class.getResource("CDF_Logo3.gif")));
           fileChooser.setFileView(fileView);
        } catch (Exception e) {}

        int returnValue = fileChooser.showDialog(dialog, "OK");
        if (returnValue == JFileChooser.APPROVE_OPTION) {
           File selectedFile = fileChooser.getSelectedFile();
           if (selectedFile != null) {
              int ind;
              String myfile = selectedFile.getAbsolutePath();
              if (theone == 1) { // for .cdf file
                ind = myfile.lastIndexOf(".cdf");
                if (ind != -1) myfile = myfile.substring(0, ind);
                ind = myfile.lastIndexOf(".CDF");
                if (ind != -1) myfile = myfile.substring(0, ind);
              } else { // for .skt file
                ind = myfile.lastIndexOf(".skt");
                if (ind != -1) myfile = myfile.substring(0, ind);
                ind = myfile.lastIndexOf(".SKT");
                if (ind != -1) myfile = myfile.substring(0, ind);
              }
	      fileChooser.setCurrentDirectory(selectedFile);
              textField.setText(myfile);
           }
        } else {
//         JOptionPane.showMessageDialog(dialog, "No file chosen");
        }
    }

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

    static public void main(String[] args) {

        String cdfbase = System.getProperty("CDF_BASE");
        if (cdfbase == null) 
            cdfbase = CDFToolsUtil.getenv("CDF_BASE");

        CDFConvert thispgm = new CDFConvert(null, cdfbase);
	thispgm.fileChooser.setCurrentDirectory(new File(thispgm.currentdir));
        thispgm.frommain = 1;
	thispgm.run();
    }

}
