/**
 * A basic implementation of the JFrame class.
 */
package usda.weru.weps;

import de.schlichtherle.truezip.file.TFile;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;

import java.io.FileFilter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.List;
import javax.help.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import org.apache.log4j.Logger;
import usda.weru.mcrew.ManageData;
import usda.weru.soil.IFC;
import usda.weru.soil.SoilChooser;

import usda.weru.soil.SoilTreeModel;
import usda.weru.soil.SoilDatabase;
import usda.weru.soil.NASIS;
import usda.weru.soil.OrganicSoilException;
import usda.weru.soil.Soil;
import usda.weru.soil.SoilTreeModel.ProjectNode;
import usda.weru.util.*;

/**
 * Wrapper for display panel to select and edit management and soil files
 * This GUI class allows a user to select the management files and Soil files
 * from the project or template directories and then launch the respective applications
 * based on the button click events i:e either MCREW or SOIL viewer application.
 * @author  manmohan, wjr=<b>Rotation</b><p>Displays the Management file chosen</p> 
 * @version 1.0
 */
public class AuxPanel extends usda.weru.weps.gui.AuxPanel_n implements PropertyChangeListener {

    private static final long serialVersionUID = 1L;

    private static final Logger LOGGER = Logger.getLogger(AuxPanel.class);
    private static usda.weru.mcrew.Mcrew mm = null;
    //public boolean MCREWLabelState = true;
    private Soil ss = null;

    /**
     *
     */
    public boolean mcrewLabelState = true;

    /**
     *
     */
    public boolean soilLabelState = true;

    /**
     *
     */
    public static String calibFactorDialogManFile = "Not Selected Yet";
    private final static MouseAdapter mouseAdapter = new MouseAdapter() {
    };

    /**
     *
     */
    public JRootPane temp = null;

    /**
     *
     */
    public JPanel temp1 = null;

    /**
     *
     */
    public Thread t = null;
    private boolean mcrewLoadingFlg = false;
    private ConfigData c_cd;
    private SoilTreeModel c_soilModel;
    private ManagementTreeModel c_manModel;

    /**
     *
     * Default constructor for AuxPanel Holds parameter information (name and  value) and the methods that are used for
     * data retrieval and manipulation.
     * 
     * Primary 
     */
    public AuxPanel() {
        super();
        JP_main.setVisible(true);

        addHelp();

        c_soilModel = new SoilTreeModel(true);
        g_soilTreeCombo.setModel(c_soilModel);
        g_soilTreeCombo.addPropertyChangeListener(WepsTreeComboBox.PROP_SELECTED_ITEM, new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                loadSelectedSoil();
                changes.firePropertyChange(RunFileData.SoilRockFragments, null, "-1");
                changes.firePropertyChange(RunFileData.AverageSlope, null, "-1");
            }
        });

        g_soilTreeCombo.getTree().expandPath(c_soilModel.getPathToProject());
        g_soilTreeCombo.getTree().expandPath(c_soilModel.getPathToTemplates());

        c_manModel = new ManagementTreeModel();
        g_manTreeCombo.setModel(c_manModel);
        g_manTreeCombo.addPropertyChangeListener(WepsTreeComboBox.PROP_SELECTED_ITEM, new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                TFile file = null;
                if (evt.getNewValue() instanceof FileTreeNode) {
                    file = ((FileTreeNode) evt.getNewValue()).getFile();
                } else {
                    return;
                }
                ManageData manData = new ManageData();
                int result = manData.readDataFile(file.getAbsolutePath());
                if (result == ManageData.kCorruptedFile) {
                    WepsMessageLog log = new WepsMessageLog();
                    log.logMessage(WepsMessage.MessageSeverity.ERROR, "The file appears to be corrupted.");
                    WepsMessageDialog.showMessageList(null, "Management File Errors",
                            "Errors were detected with the management file.", projDir, log.getMessages());
                    changes.firePropertyChange(RunFileData.ManageFile, "OLD", "");
                    return;
                }

                Vector<String> msgs = new Vector<String>();
                if (manData.checkAllConditions(msgs) == ManageData.CHECK_FAILED) {
                    WepsMessageLog log = new WepsMessageLog();
                    for (String msg : msgs) {
                        log.logMessage(WepsMessage.MessageSeverity.ERROR, msg);
                    }
                    WepsMessageDialog.showMessageList(null, "Management File Errors",
                            "Errors were detected with the management file.", projDir, log.getMessages());
                    changes.firePropertyChange(RunFileData.ManageFile, "OLD", "");
                } else {
                    changes.firePropertyChange(RunFileData.ManageFile, null, file.getAbsolutePath());
                }
            }
        });

        g_manTreeCombo.getTree().expandPath(c_manModel.getPathToProject());
        g_manTreeCombo.getTree().expandPath(c_manModel.getPathToTemplates());
    }

    /**
     *
     * @param cd
     */
    public AuxPanel(ConfigData cd) {
        this();
        c_cd = cd;
    }
    private HelpBroker hb = null;

    /**
     * Constructor that sets the helpbroker object for the AuxPanel frame 
     * besides just calling the default constructor to initialize other items
     * and add help to the components sitting in its container.
     * @param hb The hb is the help broker object that links the help items
     * from WEPS help API to the respective componennts on the panel if and 
     * when triggered. 
     */
    public AuxPanel(HelpBroker hb) {
        this();
        this.hb = hb;
    }

    /**
     * Constructor that sets the title of AuxPanel frame besides calling the
     * default constructor to initialize other items and add help to the 
     * components sitting in its container.
     * @param sTitle This is the title heading for the frame that holds the 
     * components and makes it visible in it.
     */
    public AuxPanel(String sTitle) {
        this();
        setTitle(sTitle);
    }

    /**
     * This methd adds help pages to the different labels, buttons, text field, etc.
     * that are on the auxillary panel GUI.
     */
    private void addHelp() {
        CSH.setHelpIDString(JP_main, "MCREWSoilPanel_html");
        CSH.setHelpIDString(JL_mcrew, "MCREWBand_html");
        CSH.setHelpIDString(JB_projMan, "MCREWBand_html");
        CSH.setHelpIDString(JB_tempMan, "MCREWBand_html");
        CSH.setHelpIDString(g_manTreeCombo, "MCREWBand_html");
        CSH.setHelpIDString(JL_soil, "SoilBand_html");
        CSH.setHelpIDString(JB_projSoil, "SoilBand_html");
        CSH.setHelpIDString(JB_tempSoil, "SoilBand_html");
        CSH.setHelpIDString(g_soilTreeCombo, "SoilBand_html");
    }

    /**
     * Entry point for testing AuxPanel
     * This method is used if this dialog is rum as an independent application.
     * @param args These are the command line arguments passed to the main method.
     */
    static public void main(String args[]) {
        String projectsDir = "";

        WepsFileChooser wfc = new WepsFileChooser(WepsFileChooser.Filetype.PROJECT, projectsDir,
                WepsFileChooser.SELECT);
        //set the tooltip of "home" button to "Home" instead of "Desktop"
        wfc.homeToolTip(wfc);
        //remove the NewFolder button
        wfc.disableNewFolder(wfc);

        wfc.setCurrentDirectory(new de.schlichtherle.truezip.file.TFile("c:/weps/weps.install/projects"));

        RunFileData rfd = new RunFileData();

        if (wfc.showDialog(null) == JFileChooser.APPROVE_OPTION) {
            TFile sf = new TFile(wfc.getSelectedFile());
            try {
                projectsDir = sf.getCanonicalPath();
            } catch (java.io.IOException e) {//System.err.println(
                //	"Error getting canoncial path of projectsDir");
            }
            rfd.readRunData(projectsDir);
            //	rfd.showRunFileData("this is a test");
        } else {
            //System.err.println("No project directory selected");                        
            System.exit(1);
        }

        AuxPanel ap = new AuxPanel();
        ap.setVisible(true);
        rfd.addPropertyChangeListener(ap);
        ap.addPropertyChangeListener(rfd);
        rfd.fireAll(ap);
        //System.out.println("status of AuxPanel:"+ap.isVisible());
    }
    /**
     * String containing management template directory
     */
    String manDir = "";
    /**
     * String containing soil template directory
     */
    String soilDir = "";
    /**
     * String containing the soil DB Specification
     */
    String soilDBSpecName = "";
    /**
     * String containing the soil DB String as in ConfigPanel,makeSoil() method - neha
     */
    String soilDB = "";
    /**
     * String containing current project directory
     */
    String projDir = "";
    String soilFileName = "";
    String manFileName = "";
    /**
     * Entry point to change items displayed in AuxPanel
     */
    private String mcrewDir = "";
    //Name of the data config file that is to be written in the weps_mcrew_cfg - Neha
    private String mcrewDataConfigFile = "";
    private String manSkel = "";
    private String cropDB = "";
    private String manoperdb = "";
    private String units = ""; // Added by Sada
    private boolean McrewEditFlg = false; //Added by Neha
    private String formatOperationDate = "";

    /**
     * This method triggers specific actions based upon who generates the 
     * events that occur on accessing these components sitting in their parent
     * containers. 
     * @param e The generated event by the component's access.
     */
    @Override
    public void propertyChange(PropertyChangeEvent e) {
        switch (e.getPropertyName()) {
            case RunFileData.SoilFile:
                setSoilFile(e);
                break;
            case RunFileData.ManageFile:
                setManageFile(e);
                break;
            case ConfigData.ManTemp:
                manDir = ConfigData.getDefault().getDataParsed(ConfigData.ManTemp);
                break;
            case ConfigData.SoilDB:
                soilDB = ConfigData.getDefault().getDataParsed(ConfigData.SoilDB);
                break;
            case ConfigData.ManSkel:
                manSkel = ConfigData.getDefault().getDataParsed(ConfigData.ManSkel);
                break;
            case ConfigData.CropDB:
                cropDB = ConfigData.getDefault().getDataParsed(ConfigData.CropDB);
                break;
            case ConfigData.MCREW:
                mcrewDir = ConfigData.getDefault().getDataParsed(ConfigData.MCREW);
                break;
            case ConfigData.McrewDataConfigFile:
                mcrewDataConfigFile = (String) e.getNewValue();
                break;
            case ConfigData.McrewEdit:
                setMcrewEdit(e);
                break;
            case ConfigData.ManDB:
                manoperdb = ConfigData.getDefault().getDataParsed(ConfigData.ManDB);
                break;
            case ConfigData.CurrentProj:
                setCurrentProj(e);
                break;
            case ConfigData.Units:
                //Added by Sada
                units = (String) e.getNewValue();
                break;
            case usda.weru.mcrew.Mcrew.FileName:
                changes.firePropertyChange(RunFileData.ManageFile, null,
                        (String) e.getNewValue());
                break;
            case usda.weru.mcrew.Mcrew.WindowClosing:
                setMCREWLabelState(true);
                //System.out.println("Mcrew File Name:"+mm.fileName+" abs:"+mm.absFileName);
                TFile mcrewFile = new TFile(mm.absFileName);
                String mcrewFileName = mcrewFile.getName();
                // strip suffix so that only file Name is displayed and uniformity is maintained.
                if (mcrewFileName.toUpperCase().endsWith(".MAN")) {
                    mcrewFileName = mcrewFileName.substring(0, mcrewFileName.lastIndexOf('.'));
                } else if (mcrewFileName.toUpperCase().endsWith(".XML")) {
                    mcrewFileName = mcrewFileName.substring(0, mcrewFileName.lastIndexOf('.'));
                }   //if the file name is not changed or saved in Mcrew, it remains null or empty.
                //Then we dont change the filename field.
                if (mm.fileName != null && mm.fileName.equals("") == false) {
                    //JTF_manFileName.setText(mcrewFileName);
                    g_manTreeCombo.getComboBox().removeAllItems();
                    g_manTreeCombo.getComboBox().addItem(mcrewFileName);
                    g_manTreeCombo.getComboBox().setSelectedItem(mcrewFileName);

                    changes.firePropertyChange(RunFileData.ManageFile, null, mm.absFileName);
                }
                mm = null;
                break;
            case ConfigData.FormatOperationDate:
                formatOperationDate = (String) e.getNewValue();
                break;
            case ConfigData.HideProjectFileButtons: {
                String value = e.getNewValue().toString();
                if (value.equals("1")) {
                    JB_projMan.setVisible(false);
                    JB_projSoil.setVisible(false);
                } else {
                    JB_projMan.setVisible(true);
                    JB_projSoil.setVisible(true);
                }
                break;
            }
            case ConfigData.HideTemplatetFileButtons: {
                String value = e.getNewValue().toString();
                if (value.equals("1")) {
                    JB_tempMan.setVisible(false);
                    JB_tempSoil.setVisible(false);
                } else {
                    JB_tempMan.setVisible(true);
                    JB_tempSoil.setVisible(true);
                }
                break;
            }
        }

    }

    /**
     * This method assigns the number of rotation years to the text field 
     * that stores the value to be referred in future
     * @param filnam The name of the file that holds the integer value for the
     * number of rotation years to be assigned to the variable.
     */
    void setRotationYears(String filnam) {
        if (filnam == null || filnam.length() == 0 || filnam.equals("none")) {
            return;
        }
        try {
            ManageData data = new ManageData();
            data.readDataFile(filnam);
            int years = data.getRotationYears();
            changes.firePropertyChange(RunFileData.RotationYears, null, Integer.toString(years));
        } catch (Exception e) {
            LOGGER.error("Unable to set rotation years.", e);
        }
    }

    /**
     * Handlers for property changes. This method selects and sets the soil 
     * file passed as an argument.
     * @param e The event occurs when a new soil file is selected which will 
     * be used for pulling the data into the Soil UI screens for analysis purpose.
     */
    private void setSoilFile(PropertyChangeEvent e) {
        String filnam = (String) e.getNewValue();
        if ((soilFileName != null && soilFileName.equals(filnam))
                || (filnam != null && soilFileName.equals(filnam)) || (filnam == null && soilFileName == null)) {
            //clearSoilFile();
            return;
        }
        soilFileName = filnam;

        //refresh the project node so the soil exists.
        ProjectNode projectNode = c_soilModel.getProjectNode();
        projectNode.refreshChildren();
        c_soilModel.nodeStructureChanged(projectNode);

        TFile sf = new TFile(filnam);
        if (sf.exists()) {
            FileTreeNode nodeToSelect = projectNode.getDecendantNode(sf);
            if (nodeToSelect != null) {
                TreePath treePath = new TreePath(c_soilModel.getPathToRoot(nodeToSelect));
                g_soilTreeCombo.setSelectedPath(treePath);
            }
        } else {
            //file does not exist
            //System.out.println("AP_sSF: file does not exist");
            soilFileName = "";
            if (!filnam.equals("")) {
                changes.firePropertyChange(RunFileData.SoilFile, null, "");
            }
            clearSoilFile();
            return;
        }

        String mySoilFile = sf.getName();
        int sfindex = mySoilFile.lastIndexOf(".");
        if (sfindex > 0) {
            String sFileStr = mySoilFile.substring(0, sfindex);

            g_soilTreeCombo.getComboBox().removeAllItems();
            g_soilTreeCombo.getComboBox().addItem(sFileStr);
            g_soilTreeCombo.getComboBox().setSelectedItem(sFileStr);

        } else {
            if (filnam.equals(RunFileData.DefaultSoilFileName)) {
                soilFileName = "";
                clearSoilFile();
            } else {
                //System.err.println("Soil File with extension not Found " + mySoilFile );
            }
        }

    }
    boolean overflew = false;

    private void clearManageFile() {
        g_manTreeCombo.setSelectedPath(null);
        g_manTreeCombo.getComboBox().addItem("(select a management file)");
        g_manTreeCombo.getComboBox().setSelectedItem("(select a management file)");
    }

    private void clearSoilFile() {
        g_soilTreeCombo.setSelectedPath(null);
        g_soilTreeCombo.getComboBox().addItem("(select a soil file)");
        g_soilTreeCombo.getComboBox().setSelectedItem("(select a soil file)");
    }

    /**
     * Handlers for property changes. This method selects and sets the management 
     * file passed as an argument to be pulled into the MCREW application to
     * analyse, modify, study and interprete the data.
     * @param e The event occurs when a new management(.MAN) file is selected which will 
     * be used for pulling the data into the MCREW UI screens.
     */
    private void setManageFile(PropertyChangeEvent e) {
        try {
            String filnam = (String) e.getNewValue();

            manFileName = new TFile(filnam).getAbsolutePath();

            //refresh the project node so the soil exists.
            FileTreeNode projectNode = c_manModel.getProjectNode();
            if (projectNode != null) {
                projectNode.refreshChildren();
            }
            c_manModel.nodeStructureChanged(projectNode);

            TFile mf = new TFile(filnam);
            if (mf.exists() && mf.length() <= 0 && mf.isFile()) {
                JOptionPane.showMessageDialog(null, "The Management File \n " + filnam + " exists,\n but contains NO data.",
                        "Problem with Management File", JOptionPane.ERROR_MESSAGE);
                //System.err.println("AuxPanel:SetManageFile-The Management File "+filnam+" exists, but contains NO data.");
                clearManageFile();
                return;
            }
            setRotationYears(filnam);
            if (!mf.exists() || mf.isDirectory()) {
                manFileName = "";

                if (!overflew) {
                    changes.firePropertyChange(RunFileData.ManageFile, null, "");
                }
                overflew = false;
                clearManageFile();
                return;
            }

            String myMgmtFile = mf.getName();
            int mfindex = myMgmtFile.lastIndexOf(".");
            if (mfindex > 0) {
                String mFileStr = myMgmtFile.substring(0, mfindex);
                //JTF_manFileName.setText(mFileStr);
                g_manTreeCombo.getComboBox().removeAllItems();
                g_manTreeCombo.getComboBox().addItem(mFileStr);
                g_manTreeCombo.getComboBox().setSelectedItem(mFileStr);

                calibFactorDialogManFile = mFileStr;

                FileTreeNode nodeToSelect = projectNode.getDecendantNode(mf);
                if (nodeToSelect != null) {
                    g_manTreeCombo.setSelectedPath(new TreePath(c_soilModel.getPathToRoot(nodeToSelect)));
                }
            } else {
                if (filnam.equals(RunFileData.DefaultManageFileName)) {
                    manFileName = "";
                    clearManageFile();
                } else {
                    //System.err.println("Management File with extension not Found " + myMgmtFile );
                }
            }
        } catch (StackOverflowError sofe) {
            overflew = true;
        }
    }

    /**
     * Handlers for property changes. This method sets flag for the MCREW to 
     * screen & data rows as editable.
     * @param e The event occurs when the flag is changed from editable to 
     * non-editable or vice versa.
     */
    private void setMcrewEdit(PropertyChangeEvent e) {
        McrewEditFlg = ((String) e.getNewValue()).equals("1");

    }

    /**
     * Handlers for property changes. This method selects the project currently 
     * being worked on as the current project for various screens and reports
     * to refer to it when asked for it. 
     * @param e The event occurs when the value is to be set for what will be
     * the current project path.
     */
    private void setCurrentProj(PropertyChangeEvent e) {
        projDir = Util.parse(e.getNewValue().toString());
    }

    /**
     * Open management file in project directory
     * 
     * @param event
     */
    @Override
    public void JBProjMan_actionPerformed(java.awt.event.ActionEvent event) {
        if (JB_projMan.isEnabled()) {
            WepsFileChooser wfc = new WepsFileChooser(WepsFileChooser.Filetype.MANAGE, projDir,
                    WepsFileChooser.SELECT);
            wfc.setCurrentDirectory(new de.schlichtherle.truezip.file.TFile(projDir));
            //set the tooltip of "home" button to "Home" instead of "Desktop"
            wfc.homeToolTip(wfc);
            //remove the NewFolder button
            wfc.disableNewFolder(wfc);
            if (wfc.showDialog(this.JP_main) == JFileChooser.APPROVE_OPTION) {
                try {

                    //JTF_manFileName.setText(wfc.getSelectedFile().getName());
                    //JTF_manFileName.setCaretPosition(0);
                    //Test the data
                    ManageData manData = new ManageData();
                    int result = manData.readDataFile(wfc.getSelectedFile().getAbsolutePath());
                    if (result == ManageData.kCorruptedFile) {
                        WepsMessageLog log = new WepsMessageLog();
                        log.logMessage(WepsMessage.MessageSeverity.ERROR, "The file appears to be corrupted.");
                        WepsMessageDialog.showMessageList(null, "Management File Errors",
                                "Errors were detected with the management file.", projDir, log.getMessages());
                        changes.firePropertyChange(RunFileData.ManageFile, "OLD", "");
                        return;
                    }

                    Vector<String> msgs = new Vector<String>();
                    if (manData.checkAllConditions(msgs) == ManageData.CHECK_FAILED) {
                        WepsMessageLog log = new WepsMessageLog();
                        for (String msg : msgs) {
                            log.logMessage(WepsMessage.MessageSeverity.ERROR, msg);
                        }
                        WepsMessageDialog.showMessageList(null, "Management File Errors",
                                "Errors were detected with the management file.", projDir, log.getMessages());
                        changes.firePropertyChange(RunFileData.ManageFile, "OLD", "");
                        return;
                    }

                    changes.firePropertyChange(RunFileData.ManageFile, null,
                            wfc.getSelectedFile().getCanonicalPath());
                } catch (IOException e) {
                    //System.err.println("Error getting canoncial path of man file");
                }
            }

        }
    }

    /**
     * Open management file in temnplate directory
     * @param event The mouse click or keybord event generated when the template
     * management button is clicked to open the file chooser for selecting
     * the template .MAN file.
     */
    @Override
    public void JBTempMan_actionPerformed(java.awt.event.ActionEvent event) {
        if (JB_tempMan.isEnabled()) {
            WepsFileChooser wfc = new WepsFileChooser(WepsFileChooser.Filetype.MANAGE, manDir,
                    WepsFileChooser.SELECT);
            wfc.setCurrentDirectory(new de.schlichtherle.truezip.file.TFile(manDir));
            //set the tooltip of "home" button to "Home" instead of "Desktop"
            wfc.homeToolTip(wfc);
            //remove the NewFolder button
            wfc.disableNewFolder(wfc);

            if (wfc.showDialog(this.JP_main) == JFileChooser.APPROVE_OPTION) {
                //JTF_manFileName.setText(wfc.getSelectedFile().getName());
                //JTF_manFileName.setCaretPosition(0);
                //Test the data
                ManageData manData = new ManageData();
                int result = manData.readDataFile(wfc.getSelectedFile().getAbsolutePath());
                if (result == ManageData.kCorruptedFile) {
                    WepsMessageLog log = new WepsMessageLog();
                    log.logMessage(WepsMessage.MessageSeverity.ERROR, "The file appears to be corrupted.");
                    WepsMessageDialog.showMessageList(null, "Management File Errors",
                            "Errors were detected with the management file.", projDir, log.getMessages());
                    changes.firePropertyChange(RunFileData.ManageFile, "OLD", "");
                    return;
                }

                Vector<String> msgs = new Vector<String>();
                if (manData.checkAllConditions(msgs) == ManageData.CHECK_FAILED) {
                    WepsMessageLog log = new WepsMessageLog();
                    for (String msg : msgs) {
                        log.logMessage(WepsMessage.MessageSeverity.ERROR, msg);
                    }
                    WepsMessageDialog.showMessageList(null, "Management File Errors",
                            "Errors were detected with the management file.", projDir, log.getMessages());
                    changes.firePropertyChange(RunFileData.ManageFile, null, "");
                    return;
                }
                try {
                    changes.firePropertyChange(RunFileData.ManageFile, null, wfc.getSelectedFile().getCanonicalPath());
                } catch (IOException e) {
                    LOGGER.error("Could not get file path.", e);
                }
            }

        }
    }

    /**
     * Open soil file in project directory
     * @param event The mouse click or keybord event generated when the project
     * soil button is clicked to open the file chooser for selecting
     * the project SOIL file.
     */
    @Override
    public void JBProjSoil_actionPerformed(java.awt.event.ActionEvent event) {
        if (JB_projSoil.isEnabled()) {
            WepsFileChooser wfc = new WepsFileChooser(WepsFileChooser.Filetype.SOIL, projDir,
                    WepsFileChooser.SELECT);
            wfc.setCurrentDirectory(new de.schlichtherle.truezip.file.TFile(projDir));
            //set the tooltip of "home" button to "Home" instead of "Desktop"
            wfc.homeToolTip(wfc);
            //remove the NewFolder button
            wfc.disableNewFolder(wfc);

            if (wfc.showDialog(this.JP_main) == JFileChooser.APPROVE_OPTION) {
                try {
                    //JTF_soilFileName.setText(wfc.getSelectedFile().getName());
                    String sFileStr = wfc.getSelectedFile().getName();
                    g_soilTreeCombo.getComboBox().removeAllItems();
                    g_soilTreeCombo.getComboBox().addItem(sFileStr);
                    g_soilTreeCombo.getComboBox().setSelectedItem(sFileStr);

                    changes.firePropertyChange(RunFileData.SoilFile, null, wfc.getSelectedFile().getCanonicalPath());
                    changes.firePropertyChange(RunFileData.SoilRockFragments, null, "0.0");
                    changes.firePropertyChange(RunFileData.AverageSlope, null, "-1");
                } catch (IOException e) {
                    //System.err.println("Error getting canoncial path of soil file");
                }
            }
        }
    }

    /**
     * Open soil file in template directory
     * 
     * @param event
     */
    /**
     * Open soil file in temnplate directory
     * @param event The mouse click or keybord event generated when the template
     * soil button is clicked to open the file chooser for selecting
     * the template SOIL file.
     */
    @Override
    public void JBTempSoil_actionPerformed(java.awt.event.ActionEvent event) {

        SoilChooser soilChooser = new SoilChooser();
        //soilChooser.setRootFile(new File(soilDir));
        soilChooser.setProjectDirectory(new TFile(projDir));
        soilChooser.setChanges(changes);

        soilChooser.setSelected();
        
        soilChooser.setVisible(true);

    }//end of JBTempSoil_actionPerformed

    /**
     *
     * @param event
     */
    public void JBShow_actionPerformed(java.awt.event.ActionEvent event) {
        changes.firePropertyChange(RunFileData.ShowRunData, null, "AuxPanel");

    }
    /**
     * Used to notify listeners of changes
     */
    private PropertyChangeSupport changes = new PropertyChangeSupport(this);

    /**
     * Adds listeners to the components to recognize the changes made on this panel.
     * @param l The listener object for the components on the panel to be removed.
     */
    @Override
    public void addPropertyChangeListener(PropertyChangeListener l) {
        changes.addPropertyChangeListener(l);
    }

    /**
     * Removes listeners for the components to recognize the changes made on this panel.
     * @param l The listener object for the components on the panel to be removed.
     */
    @Override
    public void removePropertyChangeListener(PropertyChangeListener l) {
        changes.removePropertyChangeListener(l);
    }

    /**
     *
     * @param evt
     */
    @Override
    public void soilActionPerformed(java.awt.event.ActionEvent evt) {

        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        ////System.out.println("AP_JLS_mC: " + soilFileName);
        if (soilLabelState) {
            if (ss != null && ss.isValid()) {//React to change button clicks.

                ss.setState(JFrame.NORMAL);
                // ss.setVisible(true);
                setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                return;
            } else {
                //Lock the soil buttons.
                setSoilLabelState(false);
                TFile sfn = new TFile(soilFileName);
                //System.out.println("AuxPanel : JLSoil_mouseClicked : SoilFilename on Line 388 : " + soilFileName);
                if (sfn.exists()) {
                    TFile pd = new TFile(projDir);
                    try {
                        if (!sfn.getParentFile().getCanonicalPath().equals(pd.getCanonicalPath())) {
                            //				//System.out.println("AP_JLS_mC: not in dir " + soilFileName + " " + projDir);
                            String fromFile = sfn.getCanonicalPath();
                            String toFile = new TFile(pd, sfn.getName()).getCanonicalPath();
                            //System.out.println("AuxPanel : JLSoil_mouseClicked : toFile : " + toFile );
                            //System.out.println("AuxPanel : JLSoil_mouseClicked : toFile : " + fromFile );
                            Util.copyFile(fromFile, toFile);
                            changes.firePropertyChange(RunFileData.SoilFile, null, toFile);
                        } else {
                            //					//System.out.println("AP_JLS_mC: in dir " + soilFileName + " " + projDir);
                        }
                    } catch (java.io.IOException e) {
                        //System.err.println("AP_JLS_mC: IO error on " + soilFileName + " or " + projDir);
                        //System.err.println("AP_JLS_mC: " + e);
                    }
                } else {
                    //System.out.println("AP_JLS_mC: " + "calling Soil  with no Soil file");
                }

                ss = new Soil(soilFileName, projDir, soilDir);

                if (ConfigData.getDefault().isSoilReadonly()) {
                    ss.setReadonly(true);
                } else {
                    ss.setReadonly(false);
                }

                ss.addWindowListener(new WindowAdapter() {

                    @Override
                    public void windowClosed(WindowEvent e) {
                        setSoilLabelState(true);
                        if (ss != null) {
                            ss.removePropertyChangeListener(AuxPanel.this);
                            ss = null;
                        }

                    }

                });

                //}
                ss.addPropertyChangeListener(this);
                c_cd.fireAll(ss);
                ss.setVisible(true);
                setSoilLabelState(false);
            }
        } else {
            int windowState = ss.getExtendedState();
            if ((windowState & ICONIFIED) == ICONIFIED) {
                ss.setExtendedState(windowState - ICONIFIED);
            }
            ss.toFront();
            ss.requestFocusInWindow();
        }
        ss.toFront();        // new usda.weru.soil.Soil(soilFileName, soilDir).setVisible(true);
        // Modified above code to open soil from specific project Directory
        setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    }

    /**
     * Disables the Soil button on the panel if a SoilUI object is already instantiated
     * else makes it enabled it. 
     * @param flag The boolean value that determines whether the label should be 
     * set enabled or not.
     */
    public void setSoilLabelState(boolean flag) {
        JL_soil.setEnabled(flag);
        soilLabelState = flag;
        JB_projSoil.setEnabled(flag);
        JB_tempSoil.setEnabled(flag);
        g_soilTreeCombo.setEnabled(flag);
    }

    /**
     * Disables the MCREW button on the panel if a MCREW object is already instantiated
     * else makes it enabled it. 
     * @param flag The boolean value that determines whether the label should be 
     * set enabled or not.
     */
    public void setMCREWLabelState(boolean flag) {
        JL_mcrew.setEnabled(flag);
        mcrewLabelState = flag;
        JB_projMan.setEnabled(flag);
        JB_tempMan.setEnabled(flag);
        g_manTreeCombo.setEnabled(flag);

    }

    /*
     private class WaitFrame extends JFrame implements=<b>Rotation</b><p>Displays the Management file chosen</p>  Runnable {
     WaitFrame(String title) {
     super(title);
     setSize(300,100);
     setLocation(5,400);
     setVisible(true);
     Thread mainRunThread = new Thread(this);
     mainRunThread.start();
     }
    
     public void run() {
     while (true) {
     try {
     Thread.sleep(1000);
     } catch (Exception e) {
     }
     //				Point loc = this.getLocation();
     //				this.setLocation((int) (Math.random() * 300), (int) (Math.random() * 200));
     }
     }
     }
     */
    /**
     * Brings the MCREW UI screen up using the data from the management file
     * shown or selected.
     * @param evt
     */
    @Override
    public void mcrewActionPerformed(java.awt.event.ActionEvent evt) {

        if (mcrewLabelState) {
            //if double click on the left mouse button, then ignore.
            //By Neha-If McrewLoadingFlg is TRUE, means Multiple mouse clicks on Mcrew button before it can load
            if ((mm != null && mm.isValid()) || (mcrewLoadingFlg == true)) {
                if (mcrewLoadingFlg != true) {
                    mm.setState(Frame.NORMAL);
                }
            } else {
                //Lock the buttons
                setMCREWLabelState(false);
                // JFrame waitFrame = new WaitFrame("Please wait while MCREW loads");
                //  waitFrame.setCursor(new Cursor(Cursor.WAIT_CURSOR));
                // By Neha-Change the Cursor to Wait Cursor, set the McrewLoadingFlg ON
                mcrewLoadingFlg = true;
                Component prev1 = null;
                Component prev2 = null;
                Component prev3 = null;
                Component prev4 = null;
                Component c = this.JP_main;
                //  //System.out.println("AP_MmC: " + c);
                do {
                    //  //System.out.println("AP_MmC: " + c.getClass().getName());
                    prev2 = prev1;
                    prev1 = c;
                    c = c.getParent();
                    if (c == null) {
                        //System.out.println("prev2: "+ prev2.getClass().getName());
                        //System.out.println("prev1: "+ prev1.getClass().getName());
                        //System.out.println("c: "+c);
                        temp = (JRootPane) prev2;
                        temp.getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                        temp.getGlassPane().setVisible(true);
                        temp.addMouseListener(mouseAdapter);
                        //System.out.println("Did i add the mouse listener");                     
                    }
                } while (c != null);

                //  //System.out.println("AM I an Event dispatching thread:"+SwingUtilities.isEventDispatchThread());
                /*
                 File mfn = new File(manFileName);
                 //System.out.println("AP:JL_MmC:Abs Path of mfn "+mfn.getAbsolutePath());
                 if(mfn.exists()) {
                 File pd = new File(projDir);
                 try {
                 if (!mfn.getParentFile().getCanonicalPath().equals(pd.getCanonicalPath())) {
                 ////System.out.println("AP_JLM_mC: not in dir " + manFileName + " " + projDir);
                 String fromFile = mfn.getCanonicalPath();
                 String toFile = new File(pd, mfn.getName()).getCanonicalPath();
                 Util.copyFile(fromFile, toFile);
                 changes.firePropertyChange(RunFileData.ManageFile, null, toFile);
                 } else {
                 ////System.out.println("AP_JLM_mC: in dir " + manFileName + " " + projDir);
                 }
                 } catch (java.io.IOException e) {
                 //System.err.println("AP_JLM_mC: IO error on " + manFileName + " or " + projDir);
                 //System.err.println("AP_JLM_mC: " + e);
                 }
                 } 
                 else {
                 //System.out.println("AP_JLM_mC: " + "calling MCREW with no management file");
                 }
                 */
                Thread th = new Thread("MCREW Action") {

                    @Override
                    public void run() {

                        try {
                            //System.out.println("The big task is starting"); 

                            //The ConfigData is now linked to Mcrew in Weps.main(); --Joseph
                            String title = Application.MCREW.getName() + "(" + Application.MCREW.getDescription() + ")";
                            mm = new usda.weru.mcrew.Mcrew(title, manFileName, projDir, c_cd);
                            mm.setWaiting(true);

                            /** By Neha- Disabling or Enabling the Open, and Open Copy of Template Menu option
                             * as MCREW is being opened from Weps here[not stand-alone]. This option is set 
                             * in the "Miscellaneous" tab of Config Panel of Weps.
                             */
                            // //System.out.println("McrewEditFlg:"+McrewEditFlg);
                            mm.JB_open.setEnabled(McrewEditFlg);
                            mm.JMI_open.setEnabled(McrewEditFlg);

                            if (mm.getLabelState() == false) {
                                setMCREWLabelState(false);
                            } else {
                                setMCREWLabelState(true);
                            }
                            try {
                                //mm.openFile(manFileName);
                                //System.out.println("The big task is over");
                                //remove the mouse listener and add the Property Change Listener for mm - Mcrew
                                removeAndAddListener();
                                mm.toFront();
                                //Mcrew Loading has finished.Turn off the flag
                                mcrewLoadingFlg = false;
                            } catch (IllegalStateException ise) {
                                //System.out.println("The big task was killed");
                                mcrewLoadingFlg = false;
                                setMCREWLabelState(true);
                                mm = null;
                                interrupt();
                            }
                        } finally {
                            if (mm != null) {
                                mm.setWaiting(false);
                            }
                            temp.getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                        }

                    }
                };

                //set the lowest priority to this thread, so that the main thread can listen 
                //to mouse events and change the  cursor to Wait cursor
                //t.start();
                SwingUtilities.invokeLater(th);
                //System.out.println("Did i come back to main thread?");
            }
        } else {
            if (mm != null) {
                int windowState = mm.getExtendedState();
                if ((windowState & ICONIFIED) == ICONIFIED) {
                    mm.setExtendedState(windowState - ICONIFIED);
                }
                mm.toFront();
                mm.requestFocusInWindow();
            }
        }
    }//end of method

    /**
     * This method removes listener from the root pane and adds it to the MCREW
     * object as a property change listener to get the feedback on events occurig
     * on MCREW GUI object.
     */
    public void removeAndAddListener() {
        temp.getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        temp.getGlassPane().setVisible(false);
        temp.removeMouseListener(mouseAdapter);
        mm.addPropertyChangeListener(this);
        //System.out.println("The object is"+this.getClass().getName());
    }

    /**
     * This method sets the cursor to a pre-defined shape on entering the set 
     * bounds. 
     * @param event Tells when the mouse entered a pre-defined bounds to trigger 
     * this event.
     */
    public void mouseEntered(MouseEvent event) {
        //System.out.println("AuxPanel:Mouse entered event occured");
        //System.out.println("Mouse position: x="+event.getX()+" y= "+event.getY());
        temp.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

    }

    /**
     *
     * @return
     */
    public Hashtable<String, String> getMcrewConfig() {
        Hashtable<String, String> config = new Hashtable<String, String>();
        config.put(ConfigData.ManTemp, manDir);
        config.put(ConfigData.ManSkel, manSkel);
        config.put(ConfigData.CropDB, cropDB);
        config.put(ConfigData.MCREW, mcrewDir);
        config.put(ConfigData.McrewDataConfigFile, mcrewDataConfigFile);
        config.put(ConfigData.ManDB, manoperdb);
        config.put(ConfigData.Units, units);
        config.put(ConfigData.FormatOperationDate, formatOperationDate);
        return config;
    }

    /**
     *
     */
    public void rebuildDropDowns() {
        if (!g_manTreeCombo.isPopupVisible()) {
            updateFileNode(c_manModel, c_manModel.getProjectNode());
            updateFileNode(c_manModel, c_manModel.getTemplateNode());
        }

        //SOIL IS NOT THREAD SAFE YET!!
//        if(!g_soilTreeCombo.isPopupVisible()){
//            updateFileNode(c_soilModel, c_soilModel.getProjectNode());
//            for(int i = 0; i < c_soilModel.getTemplatesNode().getChildCount(); i++){
//                TreeNode node = c_soilModel.getTemplatesNode().getChildAt(i);
//                if(node instanceof FileTreeNode){
//                    updateFileNode(c_soilModel, (FileTreeNode) node);
//                }
//            }
//        }
    }

    private void updateFileNode(final DefaultTreeModel model, final FileTreeNode node) {

        List<TFile> nodeFileChildren = new LinkedList<TFile>();
        final List<FileTreeNode> removed = new LinkedList<FileTreeNode>();
        for (FileTreeNode child : node.getChildren()) {
            if (!child.getFile().exists()) {
                removed.add(child);
            } else {
                nodeFileChildren.add(child.getFile());
            }
        }

        List<TFile> added = new LinkedList<TFile>();
        TFile[] listFiles = node.getFile().listFiles();
        listFiles = listFiles != null ? listFiles : new TFile[0];
        for (TFile file : listFiles) {
            if (!nodeFileChildren.contains(file)) {
                added.add(file);
            }
        }

        if (!removed.isEmpty() || !added.isEmpty()) {
            Runnable onTheEDT = new Runnable() {

                @Override
                public void run() {
                    node.refreshChildren();
                    model.reload(node);
                }

            };

            if (EventQueue.isDispatchThread()) {
                onTheEDT.run();
            } else {
                try {
                    EventQueue.invokeAndWait(onTheEDT);
                } catch (InterruptedException | InvocationTargetException e) {
                    LOGGER.error("Unable to notfiy tree of node removal.", e);
                }
            }
        }

        for (FileTreeNode child : node.getChildren()) {
            if (!removed.contains(child)) {
                updateFileNode(model, child);
            }
        }

    }

    private class ManagementTreeModel extends DefaultTreeModel implements PropertyChangeListener, FileFilter {

        private static final long serialVersionUID = 1L;

        FileTreeNode c_templateNode;
        FileTreeNode c_projectNode;

        public ManagementTreeModel() {
            super(null);
            build();
            ConfigData.getDefault().addPropertyChangeListener(ConfigData.ManTemp, this);
            ConfigData.getDefault().addPropertyChangeListener(ConfigData.CurrentProj, this);
            ConfigData.getDefault().fireAll(this);

        }

        @Override
        public void nodeStructureChanged(final TreeNode node) {
            try {
                super.nodeStructureChanged(node);
            } catch (Exception e) {
                //attempt to recover
                EventQueue.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        //pass off to the super so that any exceptions will be thrown to the default handler
                        ManagementTreeModel.super.nodeStructureChanged(node);
                    }
                });
            }
        }

        public TreePath getPathToProject() {
            return c_projectNode != null ? new TreePath(getPathToRoot(c_projectNode)) : null;
        }

        public TreePath getPathToTemplates() {
            return c_templateNode != null ? new TreePath(getPathToRoot(c_templateNode)) : null;
        }

        protected void build() {
            final TreePath selectedPath = g_manTreeCombo.getTree().getSelectionPath();
            final DefaultMutableTreeNode rootTemp = new DefaultMutableTreeNode();

            final String path = ConfigData.getDefault().getDataParsed(ConfigData.CurrentProj);
            if (path != null) {
                TFile project = new TFile(path);
                c_projectNode = new FileTreeNode(project, this);
                c_projectNode.setDisplayName("Current Project");

                rootTemp.add(c_projectNode);
            }

            TFile template = new TFile(ConfigData.getDefault().getDataParsed(ConfigData.ManTemp));
            c_templateNode = new FileTreeNode(template, this);
            c_templateNode.setDisplayName("Templates");

            rootTemp.add(c_templateNode);

            Runnable mustBeOnEDT = new Runnable() {

                @Override
                public void run() {
                    setRoot(rootTemp);

                    if (path != null) {
                        TreePath projectPath = new TreePath(getPathToRoot(c_projectNode));
                        g_manTreeCombo.getTree().expandPath(projectPath);
                    }

                    TreePath templatePath = new TreePath(getPathToRoot(c_templateNode));
                    g_manTreeCombo.getTree().expandPath(templatePath);
                }
            };

            if (EventQueue.isDispatchThread()) {
                mustBeOnEDT.run();
            } else {
                try {
                    EventQueue.invokeAndWait(mustBeOnEDT);
                } catch (InterruptedException | InvocationTargetException e) {
                    LOGGER.error("Unable to update management drop down tree.", e);
                }
            }

        }

        public FileTreeNode getProjectNode() {
            return c_projectNode;
        }

        public FileTreeNode getTemplateNode() {
            return c_templateNode;
        }

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if (null != evt.getPropertyName()) {
                switch (evt.getPropertyName()) {
                    case ConfigData.ManTemp: {
                        String path = ConfigData.getDefault().getDataParsed(ConfigData.ManTemp);
                        if (path != null) {
                            c_templateNode.setFile(new TFile(path));
                        } else {
                            c_templateNode.setFile(null);
                        }
                        nodeStructureChanged(c_templateNode);
                        break;
                    }
                    case ConfigData.CurrentProj: {
                        String path = ConfigData.getDefault().getDataParsed(ConfigData.CurrentProj);
                        if (path != null) {
                            c_projectNode.setFile(new TFile(path));
                        } else {
                            c_projectNode.setFile(null);
                        }
                        nodeStructureChanged(c_projectNode);
                        break;
                    }
                }
            }
        }

        @Override
        public boolean accept(java.io.File file) {
            if (file.getName().startsWith(".svn")) {
                return false;
            } else if (file.getName().startsWith("CVS")) {
                return false;
            } else if (file.isDirectory() || file.getName().toLowerCase().trim().endsWith(".man")) {
                return true;
            } else {
                return false;
            }
        }
    }

    //copied an modifed from SoilChooser
    private void loadSelectedSoil() {
        Object o = g_soilTreeCombo.getSelectedItem();

        if (o instanceof FileTreeNode) {
            FileTreeNode node = (FileTreeNode) o;
            changes.firePropertyChange(RunFileData.SoilFile, soilFileName, node.getFile().getAbsolutePath());
        } //hanlde the soil databases
        else if (o instanceof TreeNode) {
            final TreeNode node = (TreeNode) o;
            for (final SoilDatabase database : c_soilModel.getDatabases()) {
                if (database.isSoil(node)) {
                    //Thread off the loading of the soil ifc with a progress monitor.
                    final ProgressMonitor progress = new ProgressMonitor(this.getParent(), "Loading Soil Record", "", 0, 100);
                    progress.setMillisToDecideToPopup(100);
                    progress.setMillisToPopup(50);
                    Thread task = new Thread("loadSelectedSoil") {

                        @Override
                        public void run() {
                            try {
                                g_soilTreeCombo.getComboBox().removeAllItems();
                                String text = "Loading Soil Record...";
                                g_soilTreeCombo.getComboBox().addItem(text);
                                g_soilTreeCombo.getComboBox().setSelectedItem(text);
                                setSoilLabelState(false);
                                setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                                IFC ifc = database.getIfcFromNode(node, progress);

                                if (ifc != null) {
                                    //WepsMessageLog log = new WepsMessageLog();
                                    WepsMessageLog log = ifc.getLog();

                                    if (log.getCount(WepsMessage.MessageSeverity.ERROR) == 0) {
                                        // sends double errors to IFC file extracted from NASIS
                                        // ifc.sendErrorsToInternalVariable();
                                        ifc.writeNewIfc(projDir, changes);

                                        g_soilTreeCombo.getComboBox().removeAllItems();
                                        g_soilTreeCombo.getComboBox().addItem(ifc.getFileName());
                                        g_soilTreeCombo.getComboBox().setSelectedItem(ifc.getFileName());

                                    } else { //We have errors to report
                                        if (!NASIS.getEstimateNullValues()
                                                && log.getCount(WepsMessage.MessageSeverity.ERROR) > 0) {
                                            WepsMessageDialog.showMessageList(null, "Soil Record",
                                                    projDir, log.getMessages(WepsMessage.MessageSeverity.ERROR));
                                        } else {
                                            WepsMessageDialog.showMessageList(null, "Soil Record",
                                                    projDir, log.getMessages(WepsMessage.MessageSeverity.ERROR,
                                                            WepsMessage.MessageSeverity.WARNING));
                                        }
                                        //revert back
                                        g_soilTreeCombo.getComboBox().removeAllItems();
                                        String name = new TFile(soilFileName).getName();
                                        g_soilTreeCombo.getComboBox().addItem(name);
                                        g_soilTreeCombo.getComboBox().setSelectedItem(name);

                                    }
                                }
                            } catch (OrganicSoilException ose) {
                                //the soil being loaded
                                String message = ose.getMessage();
                                final JOptionPane pane
                                        = new JOptionPane("The selected soil is not supported by the WEPS science model.  "
                                                + "The high organic content may cause unexpected results."
                                                + (message != null ? "\n" + message + "\n" : "\n")
                                                + "Do you want to use the supplied organic soil substitue?\n"
                                                + "Note that selecting \"No\" will revert the soil to the previously selected record.",
                                                JOptionPane.WARNING_MESSAGE, JOptionPane.YES_NO_OPTION) {
                                            private static final long serialVersionUID = 1L;

                                            @Override
                                            public int getMaxCharactersPerLineCount() {
                                                return 80;
                                            }

                                        };

                                final JDialog dialog = pane.createDialog(g_soilTreeCombo, "Organic Soil");
                                dialog.setVisible(true);
                                int result = pane.getValue() != null
                                        ? Integer.valueOf(pane.getValue().toString()) : JOptionPane.CANCEL_OPTION;
                                if (result == JOptionPane.YES_OPTION) {
                                    //use the organic soil,

                                    changes.firePropertyChange(RunFileData.SoilFile, null,
                                            ConfigData.getDefault().getDataParsed(ConfigData.SoilOrganicFile));
                                    //SoilChooser.this.setVisible(false);

                                } else {
                                    //revert the selection
                                    g_soilTreeCombo.setSelectedPath(null);
                                    g_soilTreeCombo.getComboBox().removeAllItems();
                                    String name = new TFile(soilFileName).getName();
                                    g_soilTreeCombo.getComboBox().addItem(name);
                                    g_soilTreeCombo.getComboBox().setSelectedItem(name);

                                }
                            } finally {
                                progress.close();
                                setCursor(Cursor.getDefaultCursor());
                                setSoilLabelState(true);
                            }
                        }
                    };
                    task.start();
                }
            }
        }
    }
}
