package usda.weru.weps;

import de.schlichtherle.truezip.file.TFile;
import de.schlichtherle.truezip.file.TFileInputStream;
import de.schlichtherle.truezip.file.TFileReader;
import de.schlichtherle.truezip.file.TFileWriter;
import de.schlichtherle.truezip.file.swing.TFileChooser;

import java.awt.AWTEvent;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import javax.help.CSH;
import javax.help.HelpBroker;
import javax.help.HelpSet;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ToolTipManager;
import usda.weru.nrmv.ConvertAllToNrmv;
import org.apache.log4j.Appender;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.RollingFileAppender;
import org.apache.log4j.spi.RootLogger;
import org.openide.util.Exceptions;
import javax.swing.GroupLayout;
import usda.weru.mcrew.Mcrew;
import usda.weru.soil.NASIS;

import usda.weru.util.About;
import usda.weru.util.AboutDialog;
import usda.weru.util.Application;
import usda.weru.util.ConfigData;
import usda.weru.util.Help;
import usda.weru.util.JavaLogging2Log4JHandler;
import usda.weru.util.LoadProperties;
import usda.weru.util.LoadingContext;
import usda.weru.util.LogViewer;
import usda.weru.util.ResetRunLocationPanel;
import usda.weru.util.RestoringContext;
import usda.weru.util.Util;
import usda.weru.util.WepsAWTEventListener;
import usda.weru.util.WepsExceptionHandler;
import usda.weru.util.WepsFileChooser;
import usda.weru.util.WepsMessageDialog;
import usda.weru.util.WindGenStationDisplay;
import usda.weru.util.diff.DifferFrame;
import static usda.weru.weps.SimulationPanel.getDatesUnordered;
import usda.weru.weps.gui.LocalePanel_n;
import usda.weru.weps.location.LocationPanel;
import usda.weru.weps.location.Station;
import usda.weru.weps.reports.ReportManager;
import usda.weru.weps.startup.PreviousVersionResolver;
import usda.weru.weps.startup.ReleaseVersion;
import usda.weru.weps.startup.WelcomeWizard;
import usda.weru.wmrm.Wmrm;

/**
 * WEPS is an important part of controlling wind erosion through conservation
 * planning. By observing how the soil loss is affected by weather and field
 * conditions, the management operations can be adjusted to reduce soil loss.
 * Although WEPS 1.0 is designed to simulate rectangular field shapes, special
 * field configurations such as circles, strip cropping, or using barriers are
 * part of using WEPS as a conservation planning tool. By manipulating the field
 * shape to represent a field with the same area and rotating the field along
 * with any barriers many field shapes can be approximated. This is the start-up
 * class or main class for the application's execution. Kind of like a
 * CONTROLLER for a MVC architecture.
 */
public class Weps extends usda.weru.weps.gui.Weps_n implements PropertyChangeListener {

    private static final long serialVersionUID = 1L;

    private static final Logger logger = Logger.getLogger(Weps.class);

    /**
     *
     */
    public static final String WEPS = "WEPS";

    /**
     *
     */
    public static final String WEPS_RUNCREATED = WEPS + "run created";

    /**
     *
     */
    public static final String WEPS_RUNRESTORED = WEPS + "run restored";

    /**
     *
     */
    public static final String WEPS_RUNLOCATION = WEPS + "run location";
    /**
     * Static defintions for WEPS system.
     */
    public RunFileData rfd;

    /**
     *
     */
    protected ConfigData cd;

    private LoadProperties propertyLoader = null;

    /**
     *
     */
    protected boolean reviewWarnings = true;

    /**
     *
     */
    public boolean warnAboutLocale = true;
    /**
     * The set of objects used to associate the help line system.
     */
    public HelpSet hs;
    /**
     * Object used for setting up the help system and associated data for
     * context sensitive help regarding the GUI objects on the application
     * interface panel and a short desciption on what they are meant for on the
     * interface.
     */
    public HelpBroker hb;
    private boolean c_singleProjectMode = false;

    private static Weps c_instance;

    /**
     *
     * @return
     */
    public static Weps getInstance() {
        return c_instance;
    }

    /**
     * Default constructor for the main WEPS GUI application.
     */
    public Weps() {
        super();
        setMinimumSize(new Dimension(650, 175));
        c_instance = this;
        //setIconImage(wepsIcon.getImage());

        addHelp();

        MI_currentStirEnergyReport.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (lastRun.length() == 0) {
                    JOptionPane.showMessageDialog(Weps.this, "No current run available",
                            "Error (W-005)", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                String runDir = (!(new TFile(lastRun).isAbsolute()))
                        ? (new TFile(projectDirectory, lastRun)).getAbsolutePath() : lastRun;
                ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_STIR);
            }
        });
        MI_otherStirEnergyReport.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                ReportManager.getDefault().displayReport(projectDirectory, runsLocationPath,
                        ReportManager.REPORT_STIR);
            }
        });
    }

    /**
     * Creates a new instance of JFrame1 with the given title.
     *
     * @param sTitle the title for the new frame.
     * @see #JFrame1()
     */
    public Weps(String sTitle) {
        this();
        setTitle(sTitle);
    }

    @Override
    public void exitApplication() {
        if (dataChanged) {
            int res = JOptionPane.showConfirmDialog(this, "Save current WEPS project?",
                    "Save Project", JOptionPane.YES_NO_CANCEL_OPTION);
            switch (res) {
                //We need to set the default window close operation to DO_NOTHING_ON_CLOSE for CANCEL option
                //otherwise the frame remains hidden since the JFrame default close operation is HIDE_ON_CLOSE- added by Neha
                case JOptionPane.CANCEL_OPTION:
                    this.setVisible(true);
                    this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                    return;
                case JOptionPane.YES_OPTION:
                    rfd.writeRunDataXML(projectDirectory);
                    break;
                case JOptionPane.NO_OPTION:
                    break;
            }
        }
        try {
            // Beep
            Toolkit.getDefaultToolkit().beep();
            // Show a confirmation dialog
            int reply = JOptionPane.showConfirmDialog(this,
                    "Do you really want to exit?",
                    "WEPS Exit",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE);

            // If the confirmation was affirmative, handle exiting.
            ////System.out.println("W_eA: " + reply);
            if (reply == JOptionPane.YES_OPTION) {
                this.setVisible(false);    // hide the Frame

                this.dispose();            // free the system resources

                this.fileWatcher.interrupt();
                System.exit(0);            // close the application

            } else {
                this.setVisible(true);
                this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
            }
        } catch (HeadlessException e) {
        }
        //super.exitApplication();
    }

    /**
     *
     * @return
     */
    public RunFileData getRunFileData() {
        return rfd;
    }

    private static void printHelp() {
        System.out.println("Usage: weps [OPTION]");
        System.out.println();
        System.out.println("List of avaliable command line options");
        System.out.println("-cfg path/to/cfg\tspecify the main configuration file");
        System.out.println("-usercfg path/to/cfg\tspecify the user configuration file");
        System.out.println("-logcfg path/to/cfg\tspecify the logging configuration file");
        System.out.println("-log path/to/log\tspecify the logging file");
        //System.out.println("-log path/to/log\tspecify alternative logging file");
        System.out.println("-help \t\tdisplay this screen");
    }

    private static void configureDefaultLoggers(TFile logFile, Exception ex) {
        try {
            PatternLayout rfp = new PatternLayout("%d %5p [%t] (%F:%L) - %m%n");
            RollingFileAppender rfa = new RollingFileAppender(rfp, logFile.getAbsolutePath(), true);
            rfa.setMaxBackupIndex(5);
            rfa.setThreshold(Level.DEBUG);
            BasicConfigurator.configure(rfa);

            PatternLayout rfc = new PatternLayout("%5p [%t] (%F:%L) - %m%n");
            ConsoleAppender ca = new ConsoleAppender(rfc);
            ca.setThreshold(Level.WARN);
            BasicConfigurator.configure(ca);

            logger.info("Configuring default logger.");

            if (ex != null) {
                logger.info("Using default logger configuration.");
                logger.info("Log File: " + logFile.getAbsolutePath());
            } else {
                logger.warn("Error configuring loggers. Using default logger configuration.");
            }

        } catch (IOException e) {
            BasicConfigurator.configure();
            logger.error("Default logger configuration failed. Using basic configuration.", e);
        }
    }

    private static void deleteOldLogs() {
        //loggers are mow configured.  Rollover the file logger.
        Appender appender = RootLogger.getRootLogger().getAppender("file");
        if (appender instanceof FileAppender) {
            FileAppender ra = (FileAppender) appender;
            TFile file = new TFile(ra.getFile());

            String[] exts = Util.getExtensions(file.getName());
            final String requiredName = Util.purgeExtensions(file.getName(), exts);
            final String requiredExt = exts.length > 1 ? exts[exts.length - 1] : "";

            final Calendar staleLogCalendar = Calendar.getInstance();
            //staleLogCalendar.add(Calendar.DAY_OF_YEAR, -2);
            int days = 0;
            try {
                String dayText = ConfigData.getDefault().getData(ConfigData.DaysToKeepLogs);
                days = Integer.parseInt(dayText);
            } catch (NumberFormatException e) {
                logger.warn("Error parsing " + ConfigData.DaysToKeepLogs, e);
                days = Integer.MAX_VALUE;
            }
            staleLogCalendar.add(Calendar.DAY_OF_YEAR, -Math.abs(days));
            final boolean deleteAllOld = days <= 0;
            FileFilter filter = new FileFilter() {

                @Override
                public boolean accept(java.io.File file) {
                    String name = file.getName();
                    if (name.startsWith(requiredName) && name.endsWith(requiredExt)) {
                        if (deleteAllOld) {
                            return true;
                        }

                        Date fileDate = null;
                        try {
                            String[] exts2 = Util.getExtensions(file.getName());
                            if (exts2 != null && exts2.length > 0) {
                                String timeString = exts2[0].replaceFirst("\\.", "");
                                long time = Long.parseLong(timeString);
                                fileDate = new Date(time);
                            } else {
                                fileDate = new Date(file.lastModified());
                            }
                        } catch (NumberFormatException e) {
                            fileDate = new Date(file.lastModified());
                        }

                        if (staleLogCalendar.getTime().after(fileDate)) {
                            return true;
                        }

                    }
                    return false;
                }
            };

            if (file != null) {
                TFile dir = file.getParentFile();
                if (dir != null) {
                    TFile[] logs = dir.listFiles(filter, dir.getArchiveDetector());
                    for (TFile log : logs) {
                        try {
                            log.rm();
                        } catch (IOException ex) {
                            Exceptions.printStackTrace(ex);
                        }
                    }
                }
            }
        }
    }

    /**
     * The entry point for this application. Sets the Look and Feel to the
     * System Look and Feel. Creates a new JFrame and makes the GUI components
     * visible.
     *
     * @param args The command line arguments if any needed for application to
     * start up and any other data required for application execution.
     */
    static public void main(String args[]) {
        try {

            //link the java logger to the log4j
            JavaLogging2Log4JHandler.install();

            //Workaround a jvm bug with multiple monitors and buffers
            //http://forums.java.net/jive/thread.jspa?messageID=328557
            System.setProperty("sun.java2d.d3d", "false");

            //Test java version
            if (About.getJavaSpecificationVersion() < 1.6) {
                JOptionPane.showMessageDialog(null, "WEPS requires the Java Runtime Environment 1.6  or higher."
                        + "\nPlease visit http://java.sun.com and upgrade to the latest version.",
                        "Java Upgrade Required", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // make settings default
            boolean setMainConfig = false;
            String working = null;
            String userWeps = null;
            String mainConfig = "cfg/weps.cfg";
            String userConfig = null;
            String logConfig = "cfg/log.cfg";
            String log = null;

            // parse command line args
            for (int idx = 0; idx < args.length; idx++) {
                String cmd = args[idx].trim();
                switch (cmd) {
                    case "-working":
                        working = args[++idx];
                        break;
                    case "-userweps":
                        userWeps = args[++idx];
                        break;
                    case "-cfg":
                        setMainConfig = true;
                        mainConfig = args[++idx];
                        break;
                    case "-usercfg":
                        userConfig = args[++idx];
                        break;
                    case "-logcfg":
                        logConfig = args[++idx];
                        break;
                    case "-log":
                        log = args[++idx];
                        break;
                    case "-help":
                        printHelp();
                        System.exit(0);
                        break;
                    case "-?":
                        printHelp();
                        System.exit(0);
                        break;
                    case "/?":
                        printHelp();
                        System.exit(0);
                        break;
                    default:
                        System.out.println("Unknown option: " + args[idx]);
                        printHelp();
                        System.exit(0);
                        break;
                }
            }

            if (working != null) {
                working = Util.parse(working);
                TFile workingFile = new TFile(working);
                try {
                    System.setProperty("user.dir", workingFile.getCanonicalPath());
                } catch (IOException ioe) {
                    System.out.print("Unable to resolve working directory: " + working);
                    return;
                }
            }

            if (userWeps != null) {
                userWeps = Util.parse(userWeps);
                TFile userWepsFile = new TFile(userWeps).getCanOrAbsFile();
                About.setUserWepsRoot(userWepsFile);
            }

            TFile userWepsDir = About.getUserWeps();
            boolean testForOldCfgDir = !userWepsDir.exists();

            mainConfig = Util.parse(mainConfig);
            TFile mainConfigFile = new TFile(mainConfig).getCanOrAbsFile();

            //quit if we can't find the main config file.
            if (setMainConfig && !mainConfigFile.exists()) {
                System.err.println("Specified main config file not found.");
                return;
            }

            //Strip off the extensions
            String mainConfigNameNoExt = mainConfigFile.getName();
            mainConfigNameNoExt = Util.purgeExtensions(mainConfigNameNoExt,
                    Util.getExtensions(mainConfigNameNoExt));

            //if the user config is not set use the name of the main config file
            if (userConfig == null) {
                userConfig = About.getUserWeps().getAbsolutePath() + "/" + mainConfigFile.getName();
            }

            //if the log has not been set
            if (log == null) {
                log = About.getUserWeps().getAbsolutePath() + "/log/" + mainConfigNameNoExt + ".log";
            }

            userConfig = Util.parse(userConfig);
            logConfig = Util.parse(logConfig);
            log = Util.parse(log);

            //setup log4j logging.
            TFile logConfigFile = new TFile(logConfig).getCanOrAbsFile();

            About.setLogConfig(logConfigFile);

            TFile logFile = new TFile(log);

            //add the current time to the log file, this allows for a log per instance
            TFile logDir = logFile.getParentFile();
            String timeExt = Long.toString(System.currentTimeMillis());
            String logName = logFile.getName();
            String[] exts = Util.getExtensions(logName);
            String logNameNoExt = Util.purgeExtensions(logName, exts);
            logName = Util.addExtensions(logNameNoExt + "." + timeExt, exts);
            logFile = new TFile(logDir, logName);

            if (logConfigFile.exists()) {
                try {
                    Properties logProps = new Properties();
                    InputStream in = new TFileInputStream(logConfigFile);
                    logProps.load(in);
                    logProps.setProperty("log4j.appender.file.File", logFile.getAbsolutePath());
                    PropertyConfigurator.configure(logProps);
                    logger.info("Configuring logger.");
                } catch (IOException ex) {
                    //error loading the cfg
                    configureDefaultLoggers(logFile, ex);
                }
            } else {
                //the log cfg file does not exist
                configureDefaultLoggers(logFile, null);
            }

            // get the 'about' information, parse it, and log it
            {
                String[] strings = About.getAbout(Application.WEPS, false).split("\\n");
                for (String s : strings) {
                    logger.info(s);
                }
            }

            if (args.length > 0) {
                StringBuilder buffer = new StringBuilder("Command Arguments:\n");
                for (int i = 0; i < args.length; i++) {
                    buffer.append("\t[" + i + "]=" + args[i] + "\n");
                }
                logger.debug(buffer.toString());
            }

            boolean showWizard = checkForOldVersion(testForOldCfgDir, userWepsDir);

            ConfigData.getDefault().load(mainConfigFile, new TFile(userConfig).getCanOrAbsFile());

            //Add the default exception handler
            Thread.setDefaultUncaughtExceptionHandler(new WepsExceptionHandler(null));

            //Add the event queue listener
            try {
                Toolkit.getDefaultToolkit().addAWTEventListener(new WepsAWTEventListener(),
                        AWTEvent.MOUSE_EVENT_MASK | AWTEvent.WINDOW_EVENT_MASK);
            } catch (SecurityException e) {
                logger.debug("Unable to add a \"catch all\" AWTEventListener.", e);
            }

            //purge old log files so things don't get out of hand in the user directory
            deleteOldLogs();

            AuxPanel ap = null;
            Weps wp = null;
            try {
                // Add the following code if you want the Look and Feel
                // to be set to the Look and Feel of the native system.
                /*
                 try {
                 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                 }
                 catch (Exception e) {
                 }
                 */

                //Create a new instance of our application's frame, and make it visible.
                logger.debug("Creating Weps instance...");
                wp = new Weps();
                //Add a more complete exception handler
                Thread.setDefaultUncaughtExceptionHandler(new WepsExceptionHandler(wp));
                logger.debug("Weps instance created.");

                wp.cd = ConfigData.getDefault();
                logger.debug("Creating LoadProperties instance...");
                wp.propertyLoader = new LoadProperties();
                logger.debug("Done creating LoadProperties instance.");

                logger.debug("Applying property loader to weps...");
                wp.propertyLoader.setupPropertyHashtable(wp.getRootPane());
                logger.debug("Done applying property loader to weps.");

                //Tell the email client form to listen to changes in email settings
                Email.listen(wp.cd);

                //Link the mcrew configData to the weps config data
                usda.weru.mcrew.ConfigData.initialize(wp.cd);

                wp.rfd = new RunFileData(false);

                ClientPanel cp = new ClientPanel();
                cp.addPropertyChangeListener(wp.rfd);
                wp.rfd.addPropertyChangeListener(cp);
                wp.cd.addPropertyChangeListener(cp);
                //sp.JP_main.setVisible(true);
                cp.JP_main.setLocation(4, 4);
                wp.JP_client.add(cp.JP_main);
                //wp.JP_main.add(sp.JP_main);
                //sp.setBounds(0,0,235,160);
                //sp.setLocation(200,200);
                SimulationPanel sp = new SimulationPanel();
                sp.addPropertyChangeListener(wp.rfd);
                wp.rfd.addPropertyChangeListener(sp);
                wp.JP_sim.add(sp);
                wp.cd.addPropertyChangeListener(sp);

                RegPanel rp = new RegPanel();
                rp.addPropertyChangeListener(wp.rfd);
                wp.rfd.addPropertyChangeListener(rp);
                wp.cd.addPropertyChangeListener(rp);
                //rp.JP_main.setVisible(true);
                rp.JP_main.setLocation(4, 4);
                wp.JP_reg.add(rp.JP_main);
                //			wp.JP_main.add(rp.JP_main);

                BarPanel bp = new BarPanel();
                bp.addPropertyChangeListener(wp.rfd);
                wp.rfd.addPropertyChangeListener(bp);
                wp.cd.addPropertyChangeListener(bp);
                //bp.JP_main.setVisible(true);
                bp.JP_main.setLocation(4, 4);
                wp.JP_bar.add(bp.JP_main);
                //wp.JP_main.add(bp.JP_main);

                //LocPanel lp = new LocPanel(wp);
                //lp.addPropertyChangeListener(wp.rfd);
                //wp.rfd.addPropertyChangeListener(lp);
                //wp.cd.addPropertyChangeListener(lp);
                //lp.JP_main.setVisible(true);
                //lp.JP_main.setLocation(4, 4);
                LocationPanel lp = new LocationPanel(wp.getRunFileData().getBean());
                wp.JP_loc.add(lp);
                //wp.JP_main.add(lp.JP_main);

                //AuxPanel ap = new AuxPanel(wp.hb);
                ap = new AuxPanel(wp.cd);
                wp.addPropertyChangeListener(ap);
                ap.addPropertyChangeListener(wp.rfd);
                wp.rfd.addPropertyChangeListener(ap);
                wp.cd.addPropertyChangeListener(ap);
                //ap.JP_main.setVisible(true);
                /**
                 * This block of code allows the MCREW and Soil drop downs to
                 * resize with the main WEPS screen.
                 */
                GroupLayout borderControl = new GroupLayout(wp.JP_aux);
                borderControl.setHorizontalGroup(
                        borderControl.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(borderControl.createSequentialGroup()
                                .addContainerGap(5, 5)
                                .addComponent(ap.JP_main, javax.swing.GroupLayout.DEFAULT_SIZE, 800, Short.MAX_VALUE)
                                .addContainerGap(5, 5)
                        ));
                borderControl.setVerticalGroup(
                        borderControl.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(borderControl.createSequentialGroup()
                                .addContainerGap(5, 5)
                                .addComponent(ap.JP_main, javax.swing.GroupLayout.DEFAULT_SIZE, 800, Short.MAX_VALUE)
                                .addContainerGap(5, 5)
                        ));
                //add(ap.JP_main);

                DrawField df = new DrawField();
                wp.rfd.addPropertyChangeListener(df);
                df.setBackground(Color.white);
                df.setSize(210, 210);
                //df.setVisible(true);
                df.setLocation(5, 5);
                wp.JP_map.add(df);

                NotPanel np = new NotPanel();
                //np.JP_main.setVisible(true);
                //  np.JP_main.setLocation(4, 4);
                wp.JP_not.add(np.JP_main);
                np.addPropertyChangeListener(wp.rfd);
                wp.rfd.addPropertyChangeListener(np);
                wp.cd.addPropertyChangeListener(np);

                wp.cd.addPropertyChangeListener(wp);
                wp.addPropertyChangeListener(wp.cd);
                wp.rfd.addPropertyChangeListener(wp);
                wp.addPropertyChangeListener(wp.rfd);

                wp.rfd.addPropertyChangeListener(wp.cd);
                wp.cd.addPropertyChangeListener(wp.rfd);

                bp.addPropertyChangeListener(df);
                df.addPropertyChangeListener(bp);

                wp.validate();
                wp.cd.fireAll();

                {
                    wp.JB_RR.setVisible(wp.cd.getReportVisibility(wp.JB_RR.getName()));
                    wp.JB_MR.setVisible(wp.cd.getReportVisibility(wp.JB_MR.getName()));
                    wp.JB_CR.setVisible(wp.cd.getReportVisibility(wp.JB_CR.getName()));
                    wp.JB_CC.setVisible(wp.cd.getReportVisibility(wp.JB_CC.getName()));
                    wp.JB_CI.setVisible(wp.cd.getReportVisibility(wp.JB_CI.getName()));
                    wp.JB_SR.setVisible(wp.cd.getReportVisibility(wp.JB_SR.getName()));
                    wp.JB_DR.setVisible(wp.cd.getReportVisibility(wp.JB_DR.getName()));
                    wp.JB_IR.setVisible(wp.cd.getReportVisibility(wp.JB_IR.getName()));
                }
                //splash.setVisible(false);
                //splash.dispose(); //dispose the splash screen

                wp.dataChanged = false;

                wp.setLocaleTo(Locale.US);

                wp.loadCurrentProject(wp);

                try {
                    LoadingContext.enter();
//                    wp.rfd.fireAll();
                } finally {
                    LoadingContext.exit();
                }

                //System.out.println("W_m: " + wp.projectDirectory);
                Util.loadToolTips((Container) wp, new TFile("cfg", "tooltips.cfg"));
                Util.adjustLabelWidths(wp);

                String myprojFile = new TFile(wp.projectDirectory).getName();
                int proFileExtIndex = myprojFile.lastIndexOf(".");

                if (proFileExtIndex > 0) {

                    String projFileStr = myprojFile.substring(0, proFileExtIndex);
                    wp.setTitle(projFileStr);

                } else {
                    //System.err.println("W_m: Project Title not set, File name is : " + myprojFile );
                }

                wp.setTTTime("", 3);

                // TODO: find out what 4EDT means and document
                final Weps weps4EDT = wp;
                boolean userName = wp.cd.getData(ConfigData.UserFullName) != null
                        ? wp.cd.getData(ConfigData.UserFullName).equals("") : true;
                boolean userEmail = wp.cd.getData(ConfigData.MantisEmail) != null
                        ? wp.cd.getData(ConfigData.MantisEmail).equals("") : true;
                final boolean showWizard4EDT = userName && userEmail;
                EventQueue.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        weps4EDT.setVisible(true);
                        if (showWizard4EDT) {
                            WelcomeWizard wizard = new WelcomeWizard();
                            wizard.show();
                        }
                        //check if there is a file reference problem
                        Thread task = fileReferenceThread(weps4EDT);
                        task.start();
                        try {
                            task.join();
                        } catch (InterruptedException ex) {
                            Exceptions.printStackTrace(ex);
                        }
                    }
                });
            } catch (java.lang.OutOfMemoryError e) {
                JOptionPane.showMessageDialog(wp, "JVM has used all available memory\n"
                        + "Please restart to reset memory pool",
                        "Out of memory", JOptionPane.ERROR_MESSAGE);
                logger.error("Out of memory.", e);
            } catch (HeadlessException t) {
                logger.error(t.getMessage(), t);
                //Ensure the application exits with an error condition.
                System.exit(1);
            }

            //set the cursor back to default on the main Weps screen
            wp.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

            //Setup thread to watch for deleted management/soil files.
            final Weps wp2 = wp;
            final AuxPanel ap2 = ap;
            wp2.fileWatcher = fileWatcherThread(wp2, ap2);

            wp2.fileWatcher.start();
        } catch (HeadlessException e) {
            logger.fatal("Unable to start application.", e);
        }

    }

    private static boolean checkForOldVersion(boolean testForOldCfgDir, TFile userWepsDir) {
        //check for previous version
        boolean showWizard = false;
        try {
            if (testForOldCfgDir) {
                showWizard = true;
                logger.debug("User directory does not exist: " + userWepsDir.getAbsolutePath());
                //first run with this version, do we have previous versions?
                TFile previousWepsDir = PreviousVersionResolver.findPreviousSettingsDirectory(
                        new TFile(userWepsDir.getParentFile()), ReleaseVersion.valueOf(userWepsDir));
                if (previousWepsDir != null) {
                    logger.debug("Previous user directory found: " + previousWepsDir.getAbsolutePath());
                    JOptionPane pane = new JOptionPane(
                            "User settings created by a previous version of WEPS were found at "
                            + previousWepsDir.getAbsolutePath() + ". \nDo you want to import them?",
                            JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
                    final JDialog dialog = pane.createDialog("Confirm Import Settings");
                    dialog.setAlwaysOnTop(true);
                    try {
                        EventQueue.invokeAndWait(new Runnable() {

                            @Override
                            public void run() {
                                dialog.setVisible(true);
                            }
                        });
                    } catch (InterruptedException | InvocationTargetException e) {
                        logger.warn("Unable to display dialog.", e);
                    }

                    Object value = pane.getValue();
                    int result = value != null ? Integer.valueOf(value.toString()) : JOptionPane.NO_OPTION;

                    if (result == JOptionPane.YES_OPTION) {
                        //copy over the old settings
                        logger.debug("User selected to import settings.");
                        boolean imported = PreviousVersionResolver.importSettings(previousWepsDir, userWepsDir);

                        if (!imported) {
                            logger.warn("Import failed.");
                            JOptionPane.showMessageDialog(null, "Unable to import all of the previous settings."
                                    + " Please verfiy your settings in the configuration window.",
                                    "Import Settings Error", JOptionPane.ERROR_MESSAGE);
                        } else {
                            logger.debug("Import succeeded.");
                        }
                    } else {
                        logger.debug("User selected to NOT previous import settings.");
                    }
                }
            }
        } catch (HeadlessException | SecurityException | NumberFormatException e) {
            logger.error("Unable to import previous settings", e);
        }
        return showWizard;
    }

    /**
     * Locale change. We only support US
     *
     * @param l should always be Locale.US
     * @return
     */
    private void setLocaleTo(Locale l) {
        /**
         * Note: Assertions are not enabled. These will be useless items unless
         * assertions are enabled. Thus, they will be commented out unless the
         * user wishes to enable specific assertions (feed the virtual machine
         * the -ea argument).
         */
//        assert l == Locale.US;
        Locale current = Locale.getDefault();
        boolean changedLocale = false;
        if (current.equals(l) == false) {
            //Change the locale to US
            Locale.setDefault(l);
            changedLocale = true;
            logger.warn("Changed locale to US.");
        }
        if (changedLocale && warnAboutLocale) {
            LocalePanel_n panel = new LocalePanel_n();
            String text = "WEPS has detected that this machine is using the " + current.getDisplayName()
                    + " locale.  WEPS uses the " + Locale.US.getDisplayName()
                    + " locale.  You do not need to change your machine's locale, "
                    + "but be aware that numbers will be formatted in the "
                    + Locale.US.getDisplayName() + " style.";
            text = "<html>" + text + "</html>";
            panel.jl_text.setText(text);
            JOptionPane.showMessageDialog(this, panel, "System Locale Warning", JOptionPane.WARNING_MESSAGE);
            if (panel.jcb_displayWarning.isSelected()) {
                cd.setData(ConfigData.DoNotWarnAboutSystemLocale, "1");
                cd.save();
            }
        }
    }

    private static Thread fileReferenceThread(final Weps weps4EDT) {
        return new Thread("File Reference Checking") {
            @Override
            public void run() {
                if (weps4EDT.cd.isFileReferenceErrorInConfigData()) {

                    try {
                        weps4EDT.c_configPanel = new ConfigPanel(weps4EDT);
                        EventQueue.invokeAndWait(new Runnable() {

                            @Override
                            public void run() {
                                JOptionPane warningPane = new JOptionPane(
                                        "The current WEPS configuration references files "
                                        + "that can no longer be found. "
                                        + "This may cause unexpected errors. "
                                        + "Please edit your configuration or "
                                        + "contact your system administrator.",
                                        JOptionPane.WARNING_MESSAGE) {
                                    private static final long serialVersionUID = 1L;

                                    @Override
                                    public int getMaxCharactersPerLineCount() {
                                        return 80;
                                    }
                                };
                                JDialog warningDialog
                                        = warningPane.createDialog("File Reference Error");
                                warningDialog.setAlwaysOnTop(true);
                                warningDialog.setVisible(true);
                                weps4EDT.c_configPanel.setVisible(true, true);

                            }
                        });
                        // wait for the config panel to close
                        while (weps4EDT.c_configPanel.isVisible()) {
                            Thread.yield();
                        }
                        if (weps4EDT.cd.isFileReferenceErrorInConfigData()) {
                            EventQueue.invokeAndWait(new Runnable() {

                                @Override
                                public void run() {
                                    JOptionPane error = new JOptionPane(
                                            "The file reference errors are still "
                                            + "unresolved.  This may cause unexpected errors.",
                                            JOptionPane.ERROR_MESSAGE) {
                                        private static final long serialVersionUID = 1L;

                                        @Override
                                        public int getMaxCharactersPerLineCount() {
                                            return 80;
                                        }
                                    };
                                    JDialog errorDialog
                                            = error.createDialog("File Reference Error");
                                    errorDialog.setAlwaysOnTop(true);
                                    errorDialog.setVisible(true);
                                }
                            });

                        }
                    } catch (InterruptedException | InvocationTargetException e) {
                    }
                }

            }
        };
    }

    private static Thread fileWatcherThread(final Weps wp2, final AuxPanel ap2) {
        return new Thread("File Watcher") {

            @Override
            public void run() {
                try {
                    while (wp2 != null) {
                        if (wp2.manFileName != null && wp2.manFileName.length() > 0) {
                            TFile manFile = new TFile(wp2.manFileName);
                            if (!manFile.exists()) {
                                //Man file was deleted.
                                EventQueue.invokeLater(new Runnable() {
                                    @Override
                                    public void run() {
                                        wp2.changes.firePropertyChange(RunFileData.ManageFile,
                                                wp2.manFileName, "");
                                    }
                                });

                            }
                            manFile = null;
                        }

                        if (wp2.soilFileName != null && wp2.soilFileName.length() > 0) {
                            TFile soilFile = new TFile(wp2.soilFileName);
                            if (!soilFile.exists()) {
                                //Man file was deleted.
                                EventQueue.invokeLater(new Runnable() {
                                    @Override
                                    public void run() {
                                        wp2.changes.firePropertyChange(RunFileData.SoilFile,
                                                wp2.soilFileName, "");
                                    }
                                });
                            }
                            soilFile = null;
                        }

                        try {
                            ap2.rebuildDropDowns();
                        } catch (Exception e) {
                            logger.error("Unable to rebuild dropdown trees.", e);
                        }

                        Thread.sleep(5000);
                    }
                } catch (InterruptedException ex) {
                }
            }
        };
    }
    /**
     *
     */
    public transient Thread fileWatcher;

    /**
     * Sets whatever the title of the screen is passed as argument.
     *
     * @param title The title of WEPS application GUI
     */
    @Override
    public void setTitle(String title) {
        updateTitle();
        // Setting the Icon Image in the title bar
        super.setIconImage(About.getWeruIconImage());
    }

    private void updateTitle() {
        String title = "";
        if (projectDirectory != null && projectDirectory.length() > 0) {
            TFile project = new TFile(projectDirectory);
            title = project.getName();
            if (title.toLowerCase().endsWith(".wpj")) {
                title = title.substring(0, title.length() - 4);
            }
        }
        super.setTitle("WEPS Project: " + title);
        String mostRecentRunName = "";
        if (lastRun != null) {
            mostRecentRunName = new TFile(lastRun).getName();
            mostRecentRunName = mostRecentRunName.replace(".wjr", "");
        }
        JTF_mostRecentRun.setText(mostRecentRunName);
    }

    private void selectProjDir() {

        WepsFileChooser wpc = new WepsFileChooser(WepsFileChooser.Filetype.PROJDIR, ".",
                WepsFileChooser.SELECT);
        wpc.setCurrentDirectory(new TFile("."));
        // set the tooltip of "home" button to "Home" instead of "Desktop"
        wpc.homeToolTip(wpc);
        // remove the new Folder option
        wpc.disableNewFolder(wpc);
        if (wpc.showDialog(this) == TFileChooser.APPROVE_OPTION) {
            //System.out.println("Selecting a project directory location");
            try {
                TFile selProj = new TFile(wpc.getSelectedFile().getCanonicalPath());
                if (!selProj.isAbsolute()) {
                    selProj = new TFile(projectsPath, wpc.getSelectedFile().getCanonicalPath());
                }

                //parent path of the Project directory chosen
                String parentPath = selProj.getParent();
                // This is the user's current working directory - Generally this is ..\weps\weps1.install
                String workingDir = System.getProperty("user.dir");
                //System.out.println("parent Path of the Project Directory:
                //"+parentPath+" working Directory:"+workingDir);
                // If the Project is created in the current working directory, then just store the
                // Name [relative path] of the Projects directory, else store the absoulte path.
                if (parentPath.equals(workingDir)) {
                    changes.firePropertyChange(ConfigData.ProjDir, null, selProj.getName());
                } else {
                    changes.firePropertyChange(ConfigData.ProjDir, null, selProj.getAbsolutePath());
                }

                ConfigData.getDefault().save();
            } catch (IOException e) {
                //System.err.println("WEPS:selectProjDir: projectsDir " + e);
            }
        }
    }//end of selectProjDir()

    private void makeProjDir() {

        java.io.File current = new TFile(projectsPath);
        while (current != null && !current.exists()) {
            current = current.getParentFile();
        }
        if (current == null) {  // findbugs fix -- this shouldn't be able to happen
            System.err.println("really odd file system error");
            return;
        }
        WepsFileChooser wpc = new WepsFileChooser(WepsFileChooser.Filetype.PROJDIR, current.getAbsolutePath(),
                WepsFileChooser.CREATE);
        wpc.setCurrentDirectory(current);
        // set the tooltip of "home" button to "Home" instead of "Desktop"
        wpc.homeToolTip(wpc);
        if (wpc.showDialog(this) == TFileChooser.APPROVE_OPTION) {
            // work with the picked item
            JOptionPane.showMessageDialog(this, wpc.getSelectedFile().getAbsolutePath(),
                    "WEPS Project Directory to create", JOptionPane.PLAIN_MESSAGE);
        } else {
            return;
        }
        try {

            TFile mU = new TFile(wpc.getSelectedFile().getCanonicalPath());

            //System.out.println("projectsPath:"+projectsPath+"  
            //Absolute Path:"+mU.getCanonicalPath()+" is it absolute?:
            // "+mU.isAbsolute());
            //  //System.out.println("parent:"+ mU.getParent()+" parent file:"+mU.getParentFile());
            if (!mU.isAbsolute()) {
                mU = new TFile(projectsPath, wpc.getSelectedFile().getCanonicalPath());
            }
            if (mU.exists()) {
                JOptionPane.showMessageDialog(this, "Project directory already exists",
                        "Error (W-001)", JOptionPane.WARNING_MESSAGE);
                throw new IOException("Project directory already exists");
            }
            if (!mU.mkdirs()) {
                JOptionPane.showMessageDialog(this, "Cannot create project directory",
                        "Error (t W-002)", JOptionPane.WARNING_MESSAGE);
                throw new IOException("Cannocreate project directory");
            }

            // parent path of the Project directory chosen
            String parentPath = mU.getParent();
            // This is the user's current working directory - Generally this is ..\weps\weps1.install
            String workingDir = System.getProperty("user.dir");
            //System.out.println("parent Path of the Project Directory:
            //"+parentPath+" working Directory:"+workingDir);
            // If the Project is created in the current working directory, then just store the
            // Name [relative path] of the Projects directory, else store the absoulte path.
            if (parentPath.equals(workingDir)) {
                changes.firePropertyChange(ConfigData.ProjDir, null, mU.getName());
            } else {
                changes.firePropertyChange(ConfigData.ProjDir, null, mU.getAbsolutePath());
            }

            ConfigData.getDefault().save();

        } catch (IOException e) {
            //System.err.println("nIaP: projectsDir " + e);
        }
    }

    private void makeProject(String projName, boolean forceSuffix) throws IOException {
        if (forceSuffix) {
            if (!projName.endsWith(RunFileData.ProjectSuffix)) {
                projName += RunFileData.ProjectSuffix;
            }
        }
        TFile mU = new TFile(projName);
        if (!mU.isAbsolute()) {
            mU = new TFile(projectsPath, projName);
        }
        if (mU.exists()) {
            JOptionPane.showMessageDialog(this, "Project directory already exists",
                    "Error (W-001)", JOptionPane.WARNING_MESSAGE);
            throw new IOException("Project directory already exists");
        }
        if (!mU.mkdirs()) {
            JOptionPane.showMessageDialog(this, "Cannot create project directory",
                    "Error (W-002)", JOptionPane.WARNING_MESSAGE);
            throw new IOException("Cannot create project directory");
        }
        changes.firePropertyChange(ConfigData.CurrentProj, null, mU.getAbsolutePath());
        changes.firePropertyChange(RunFileData.LastRun, null, "");
        setTitle(mU.getName());
    }

    @Override
    public void newItem_actionPerformed(java.awt.event.ActionEvent event) {
        if (dataChanged) {
            int res = JOptionPane.showConfirmDialog(this, "Save current WEPS project?",
                    "Save Project", JOptionPane.YES_NO_CANCEL_OPTION);
            switch (res) {
                case JOptionPane.CANCEL_OPTION:
                    return;
                case JOptionPane.YES_OPTION:
                    saveItem_actionPerformed(event);
                    break;
                case JOptionPane.NO_OPTION:
                    break;
            }
        }

        TFile tf = Util.incrementFileName(new TFile(projectsPath, "Project_1.wpj"), null, ".wpj");

        TFile projectsFolder = new TFile(projectsPath);
        if (!projectsFolder.exists()) {
            JOptionPane.showMessageDialog(this, "Projects location not found:\n" + projectsFolder.getPath(),
                    "Path Warning", JOptionPane.WARNING_MESSAGE);
        }

        WepsFileChooser wpc = new WepsFileChooser(WepsFileChooser.Filetype.PROJECT, projectsPath,
                WepsFileChooser.CREATE);
        wpc.setCurrentDirectory(new TFile(projectsPath));
        // set the tooltip of "home" button to "Home" instead of "Desktop"
        wpc.homeToolTip(wpc);
        wpc.setPersitSelectedFile(true);
        wpc.setSelectedFile(tf);
        // Required because we are persiting the file name.
        wpc.setText(tf.getName());

        if (wpc.showDialog(this) == TFileChooser.APPROVE_OPTION) {
            // work with the picked item
            try {
                java.io.File selected = wpc.getSelectedFile();
                String path = selected != null ? selected.getAbsolutePath() : "NULL";

                JOptionPane.showMessageDialog(this, path, "WEPS Project to create", JOptionPane.PLAIN_MESSAGE);
            } catch (NullPointerException npe) {
                // very very odd error
                logger.debug("Very very odd npe error.", npe);
            }
        } else {
            return;
        }
        try {
            //System.out.println("W_nIaP: 1");
            makeProject(wpc.getSelectedFile().getCanonicalPath(), true);
            rfd.initialize();
            rfd.fireAll();
            //System.out.println("W_nIaP: 2");
            rfd.writeRunDataXML(projectDirectory);
            //Set the title of the window with no run name since this is a new project - neha
            setTitle(wpc.getSelectedFile().getName());

        } catch (IOException e) {
            //System.err.println("nIaP: projectsDir " + e);
        }
    }

    @Override
    public void openItem_actionPerformed(java.awt.event.ActionEvent event) {
        if (dataChanged) {
            int res = JOptionPane.showConfirmDialog(this, "Save current WEPS project?",
                    "Save Project", JOptionPane.YES_NO_CANCEL_OPTION);
            switch (res) {
                case JOptionPane.CANCEL_OPTION:
                    return;
                case JOptionPane.YES_OPTION:
                    saveItem_actionPerformed(event);
                    break;
                case JOptionPane.NO_OPTION:
                    break;
            }
        }

        TFile projectsFolder = new TFile(projectsPath);
        if (!projectsFolder.exists()) {
            JOptionPane.showMessageDialog(this, "Projects location not found:\n" + projectsFolder.getPath(),
                    "Path Warning", JOptionPane.WARNING_MESSAGE);
        }

        WepsFileChooser wfc = null;
        try {

            wfc = new WepsFileChooser(WepsFileChooser.Filetype.PROJECT, projectsPath, WepsFileChooser.OPEN);

            //  UIManager.put("wfc.homeFolderToolTipText","NEW TTT FOR HOME");
            //  UIManager.put("wfc.directoryOpenButtonText","NEW OPEN");
            //System.out.println("W_oI_aP: " + projectsPath);
            //set the tooltip of "home" button to "Home" instead of "Desktop"
            wfc.homeToolTip(wfc);
            //remove the NewFolder button
            wfc.disableNewFolder(wfc);
            wfc.setCurrentDirectory(new TFile(projectsPath).getAbsoluteFile());

        } catch (java.lang.ArrayIndexOutOfBoundsException e) {
            JOptionPane.showMessageDialog(this, "Internal error has occurred\nRestart and create new project",
                    "Error (W-003)", JOptionPane.ERROR_MESSAGE);
            //System.err.println("W_oI_aP: " + e);
            e.printStackTrace();
            return;
        }

        if (wfc.showDialog(this) != TFileChooser.APPROVE_OPTION) {
            //System.out.println("W_oKaP: not approved");
            return;
        }

        TFile sf = new TFile(wfc.getSelectedFile());

        try {
            String projectsDir = sf.getCanonicalPath();

            //System.out.println("W_oIaP: C " + sf.getCanonicalPath());
            //System.out.println("W_oIaP: A " + sf.getAbsolutePath());
            //System.out.println("W_oIaP: N " + sf.getPath());
            //System.out.println("W_oIaP: CD " + System.getProperty("user.dir"));
            //System.out.println("W_oIaP: R " + Util.getRelativePath(sf.getPath(),System.getProperty("user.dir")));
            //System.out.println("W_oI_aP: " + cd.CurrentProj + " " + projectsDir);
            changes.firePropertyChange(ConfigData.CurrentProj, null, projectsDir);
            changes.firePropertyChange(RunFileData.LastRun, null, "");

            LoadingContext.enter();
            try {
                rfd.initialize();
                TFile runData = new TFile(projectsDir, RunFileData.WepsData);
                if (runData.exists()) {
                    rfd.readRunData(projectsDir);
                } else {
                    rfd.writeRunDataXML(projectsDir);
                }
            } finally {
                LoadingContext.exit();
            }

            winCliMode();

        } catch (IOException e) {
            //System.err.println("oIaP: projectsDir " + e);
        }
    }

    @Override
    public void saveItem_actionPerformed(java.awt.event.ActionEvent event) {
        rfd.writeRunDataXML(projectDirectory);
        dataChanged = false;
    }

    @Override
    public void saveAsItem_actionPerformed(java.awt.event.ActionEvent event) {
        WepsFileChooser wpc = new WepsFileChooser(WepsFileChooser.Filetype.PROJECT, projectsPath,
                WepsFileChooser.SAVE);
        //set the tooltip of "home" button to "Home" instead of "Desktop"
        wpc.homeToolTip(wpc);

        wpc.setCurrentDirectory(new TFile(projectsPath));
        if (wpc.showDialog(this) == TFileChooser.APPROVE_OPTION) {
            // work with the picked item
            JOptionPane.showMessageDialog(this, wpc.getSelectedFile().getAbsolutePath(),
                    "WEPS Project to create", JOptionPane.PLAIN_MESSAGE);
        } else {
            return;
        }
        try {
            makeProject(wpc.getSelectedFile().getCanonicalPath(), true);
            rfd.writeRunDataXML(projectDirectory);
            dataChanged = false;
        } catch (IOException e) {
            //System.err.println("W-sAIaP: projectsDir " + e);
        }

    }

    /**
     *
     * @param evt
     */
    @Override
    protected void openDatabasesItem_actionPerformed(java.awt.event.ActionEvent evt) {
        try {
            Desktop.getDesktop().open(About.getWepsDatabases());
        } catch (IOException e) {
            String path = About.getWepsDatabases().getAbsolutePath();
            logger.warn("Unable to open: " + path, e);
            JOptionPane.showMessageDialog(this, "Unable to open weps databases.", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void resetProjectItem_ActionPerformed(java.awt.event.ActionEvent evt) {
        //We want to create an option pane that will display yes and no, and 
        //we want the default option to be no.
        int response = JOptionPane.showOptionDialog(this, "Reset current settings and delete files?\n"
                + "Run settings will return to defaults.\nManagement and soil files will be deleted.",
                "Reset", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[]{"Yes", "No"}, "No");
        if (JOptionPane.YES_OPTION == response) {
            //clear the project
            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            try {
                rfd.initialize();
                saveItem_actionPerformed(null);
                //delete all the non run files
                TFile dir = new TFile(projectDirectory);
                for (TFile file : dir.listFiles()) {
                    deleteNonRuns(file);
                }
                changes.firePropertyChange(ConfigData.CurrentProj, null, projectDirectory);
            } finally {
                setCursor(Cursor.getDefaultCursor());
            }

        } else {
        }
    }

    private void deleteNonRuns(TFile file) {
        if (file.getName().toLowerCase().endsWith(RunFileData.RunSuffix)) {
            //is a run, exit
            return;
        }

        if (file.isDirectory()) {
            //try to delete all the children first
            for (TFile child : file.listFiles()) {
                deleteNonRuns(child);
            }
        }

        if (!file.isDirectory() || file.listFiles().length == 0) {
            //only delete if we no longer have any children left.
            try {
                file.rm();
            } catch (IOException e) {
                logger.debug("Unable to delete file: \"" + file.getAbsolutePath()
                        + "\".  Delete will be scheduled for application exit.");
                file.deleteOnExit();
            }
        }
    }

    /**
     *
     * @param event
     */
    @Override
    public void deleteProjectItem_actionPerformed(java.awt.event.ActionEvent event) {
        // //System.out.println("The current running project is- projectDirectory value"+projectDirectory);

        WepsFileChooser wfc = null;
        try {
            wfc = new WepsFileChooser(WepsFileChooser.Filetype.PROJECT, projectsPath,
                    WepsFileChooser.DELETE);
            javax.swing.filechooser.FileSystemView fsv = wfc.getFileSystemView();
//            File fHome=new File(fsv.getHomeDirectory());
            //System.out.println("The Home Directory is:"+fHome.getName());

            wfc.setMultiSelectionEnabled(true);
            //System.out.println("W_dPI_aP: " + projectsPath);
            //set the tooltip of "home" button to "Home" instead of "Desktop"
            wfc.homeToolTip(wfc);
            //remove the NewFolder button
            wfc.disableNewFolder(wfc);

            wfc.setCurrentDirectory(new TFile(
                    (new TFile(projectsPath)).getAbsolutePath()));
        } catch (java.lang.ArrayIndexOutOfBoundsException e) {
            JOptionPane.showMessageDialog(this, "Internal error has occurred\nRestart and delete project",
                    "Error (W-004)",
                    JOptionPane.ERROR_MESSAGE);
            //System.err.println("W_dPI_aP: " + e);
            e.printStackTrace();
            return;
        }
        if (wfc.showDialog(this) == TFileChooser.APPROVE_OPTION) {
            int res = -1;
            java.io.File[] sf = wfc.getSelectedFiles();
            int numFiles = sf.length;
            if (numFiles == 1) {
                if (wfc.getSelectedFile().getAbsolutePath().equals(projectDirectory)) {
                    JOptionPane.showMessageDialog(this, "Project " + sf[0].getName() + " is presently open."
                            + "\n Open some other project to delete this one.",
                            "alert", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                res = JOptionPane.showConfirmDialog(this, "Delete " + wfc.getSelectedFile().getName(),
                        "Delete Project", JOptionPane.YES_NO_CANCEL_OPTION);
            } else {
                //System.out.println("The selected files is"+wfc.getSelectedFile().getName());

                String messg = "";
                for (int j = 0; j < numFiles; j++) {
                    if (j == (numFiles - 1)) {
                        messg = messg + sf[j].getName();
                    } else {
                        messg = messg + sf[j].getName() + "\n";
                    }

                    if (sf[j].getAbsolutePath().equals(projectDirectory)) {
                        JOptionPane.showMessageDialog(this, "Project " + sf[j].getName() + " is presently open."
                                + "\n Open some other project to delete this one.",
                                "alert", JOptionPane.WARNING_MESSAGE);
                        return;
                    }
                }

                JTextArea jt = new JTextArea(messg);
                jt.setEditable(false);
                JScrollPane sp = new JScrollPane(jt, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
                sp.setPreferredSize(new Dimension(500, 100));
                res = JOptionPane.showConfirmDialog(this, sp, "Delete Projects",
                        JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
            }

            switch (res) {
                case JOptionPane.CANCEL_OPTION:
                    return;
                case JOptionPane.YES_OPTION:
                    for (int i = 0; i < numFiles; i++) {
                        rfd.removeRunData(new TFile(sf[i]));
                    }
                    break;
                case JOptionPane.NO_OPTION:
                    break;
            }
        } else {
            //System.out.println("W_oKaP: not approved");
        }

    }

    /**
     *
     * @param event
     */
    @Override
    public void deleteRunItem_actionPerformed(java.awt.event.ActionEvent event) {
        WepsFileChooser wfc = null;
        try {
            wfc = new WepsFileChooser(WepsFileChooser.Filetype.RUNDIR, runsLocationPath, WepsFileChooser.DELETE);
            wfc.setCurrentDirectory(new TFile(runsLocationPath));
            wfc.setMultiSelectionEnabled(true);
            //set the tooltip of "home" button to "Home" instead of "Desktop"
            wfc.homeToolTip(wfc);
            //remove the NewFolder button
            wfc.disableNewFolder(wfc);
        } catch (java.lang.ArrayIndexOutOfBoundsException e) {
            JOptionPane.showMessageDialog(this, "Internal error has occurred\nRestart and delete run",
                    "Error (W-005)", JOptionPane.ERROR_MESSAGE);

            logger.fatal("Internal error has occurred\nRestart and delete run", e);
            return;
        }
        if (wfc.showDialog(this) == TFileChooser.APPROVE_OPTION) {
            int res = -1;
            java.io.File[] sf = wfc.getSelectedFiles();
            int numFiles = sf.length;
            if (numFiles == 1) {

                res = JOptionPane.showConfirmDialog(this, "Delete " + wfc.getSelectedFile().getName(),
                        "Delete Run", JOptionPane.YES_NO_CANCEL_OPTION);
            } else {

                StringBuilder sb = new StringBuilder(sf[0].getName());
                for (int j = 1; j < numFiles; j++) {
                    sb.append("\n");
                    sb.append(sf[j].getName());
                }
                JTextArea jt = new JTextArea(sb.toString());
                jt.setEditable(false);
                JScrollPane sp = new JScrollPane(jt, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
                sp.setPreferredSize(new Dimension(500, 100));
                res = JOptionPane.showConfirmDialog(this, sp, "Delete Runs", JOptionPane.YES_NO_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE);

            }

            switch (res) {
                case JOptionPane.CANCEL_OPTION:
                    return;
                case JOptionPane.YES_OPTION:
                    deleteRun(sf);
                    break;
                case JOptionPane.NO_OPTION:
                    break;
            }
        }
    }

    /**
     *
     * @param files
     */
    public void deleteRun(java.io.File... files) {

        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        List<TFile> lockedFiles = new LinkedList<TFile>();
        for (java.io.File file : files) {
            if (file.getName().equals(lastRun)) {
                changes.firePropertyChange(RunFileData.LastRun, lastRun, "");
            }

            boolean deleted = Util.deleteAll(new TFile(file), lockedFiles);
            if (!deleted) {
                JOptionPane.showMessageDialog(this, "Files failed to delete.",
                        "Deletion Fail", JOptionPane.INFORMATION_MESSAGE);
            }
        }

        if (!lockedFiles.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (TFile notDeleted : lockedFiles) {
                sb.append(notDeleted.getAbsolutePath());
                sb.append("\n");
            }

            JTextArea jt = new JTextArea(sb.toString());
            jt.setEditable(false);
            JScrollPane sp = new JScrollPane(jt, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            sp.setPreferredSize(new Dimension(500, 100));

            //JOptionPane.showMessageDialog(this, "Unable to Delete Run:\n" + file.getPath() +
            //"\nThe following files may be read only or open in another application.");
            JOptionPane.showMessageDialog(this, sp, "Locked Files", JOptionPane.ERROR_MESSAGE);
        }

        setCursor(Cursor.getDefaultCursor());

    }

    /**
     *
     * @param evt
     */
    @Override
    protected void exportRunItem_actionPerformed(java.awt.event.ActionEvent evt) {
        TFile source = new TFile(lastRun);
        RunExporter export = new RunExporter(source, null, false);
        export.display(this);
    }

    /**
     *
     * @param evt
     */
    @Override
    public void deleteMgmtItem_actionPerformed(java.awt.event.ActionEvent evt) {
        WepsFileChooser wfc = null;
        try {
            wfc = new WepsFileChooser(WepsFileChooser.Filetype.MANAGE, projectDirectory,
                    WepsFileChooser.DELETE);

            wfc.setMultiSelectionEnabled(true);

            //set the tooltip of "home" button to "Home" instead of "Desktop"
            wfc.homeToolTip(wfc);
            //remove the NewFolder button
            wfc.disableNewFolder(wfc);

            wfc.setCurrentDirectory(new TFile(projectDirectory));
        } catch (java.lang.ArrayIndexOutOfBoundsException e) {
            JOptionPane.showMessageDialog(this, "Internal error has occurred\nRestart and delete Management File",
                    "Error (W-006)",
                    JOptionPane.ERROR_MESSAGE);
            //System.err.println("W_dMI_aP: " + e);
            e.printStackTrace();
            return;
        }

        //System.out.println("Current Management File is:"+manFileName);
        if (wfc.showDialog(this) == TFileChooser.APPROVE_OPTION) {
            int res = -1;
            java.io.File[] sf = wfc.getSelectedFiles();
            int numFiles = sf.length;
            if (numFiles == 1) {
                if (wfc.getSelectedFile().getAbsolutePath().equals(manFileName)) {
                    JOptionPane.showMessageDialog(this, "Management Rotation File " + sf[0].getName()
                            + " is currently being used for this project."
                            + "\n Open some other project to delete this one.",
                            "alert", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                res = JOptionPane.showConfirmDialog(this, "Delete " + wfc.getSelectedFile().getName(),
                        "Delete Management Rotation File", JOptionPane.YES_NO_CANCEL_OPTION);
            } else {
                //System.out.println("The selected files is"+wfc.getSelectedFile().getName());
                StringBuilder sb = new StringBuilder(sf[0].getName());
                for (int j = 1; j < numFiles; j++) {
                    sb.append("\n");
                    sb.append(sf[j].getName());
                }
                JTextArea jt = new JTextArea(sb.toString());
                jt.setEditable(false);
                JScrollPane sp = new JScrollPane(jt, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
                sp.setPreferredSize(new Dimension(500, 100));
                res = JOptionPane.showConfirmDialog(this, sp, "Delete Management Files",
                        JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);

            }

            switch (res) {
                case JOptionPane.CANCEL_OPTION:
                    return;
                case JOptionPane.YES_OPTION:
                    for (int i = 0; i < numFiles; i++) {
                        Util.deleteAll(new TFile(sf[i]));
                    }
                    break;
                case JOptionPane.NO_OPTION:
                    break;
            }
        } else {
            //System.out.println("W_oKaP: not approved");
        }

    }

    /**
     *
     * @param evt
     */
    @Override
    public void deleteSoilItem_actionPerformed(java.awt.event.ActionEvent evt) {
        // TO DO: code goes here:
        WepsFileChooser wfc = null;
        try {
            wfc = new WepsFileChooser(WepsFileChooser.Filetype.SOIL, projectDirectory,
                    WepsFileChooser.DELETE);

            wfc.setMultiSelectionEnabled(true);

            //set the tooltip of "home" button to "Home" instead of "Desktop"
            wfc.homeToolTip(wfc);
            //remove the NewFolder button
            wfc.disableNewFolder(wfc);

            wfc.setCurrentDirectory(new TFile(projectDirectory));
        } catch (java.lang.ArrayIndexOutOfBoundsException e) {
            JOptionPane.showMessageDialog(this, "Internal error has occurred\nRestart and delete Soil File",
                    "Error (W-006)",
                    JOptionPane.ERROR_MESSAGE);
            //System.err.println("W_dMI_aP: " + e);
            e.printStackTrace();
            return;
        }

        //System.out.println("Current Soil File is:"+soilFileName);
        if (wfc.showDialog(this) == TFileChooser.APPROVE_OPTION) {
            int res = -1;
            java.io.File[] sf = wfc.getSelectedFiles();
            int numFiles = sf.length;
            if (numFiles == 1) {
                if (wfc.getSelectedFile().getAbsolutePath().equals(soilFileName)) {
                    JOptionPane.showMessageDialog(this, "IFC Soil File " + sf[0].getName()
                            + " is currently being used for this project."
                            + "\n Open some other project to delete this one.",
                            "alert", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                res = JOptionPane.showConfirmDialog(this, "Delete " + wfc.getSelectedFile().getName(),
                        "Delete IFC Soil File", JOptionPane.YES_NO_CANCEL_OPTION);
            } else {
                StringBuilder sb = new StringBuilder(sf[0].getName());
                for (int j = 1; j < numFiles; j++) {
                    sb.append("\n");
                    sb.append(sf[j].getName());
                }
                JTextArea jt = new JTextArea(sb.toString());
                jt.setEditable(false);
                JScrollPane sp = new JScrollPane(jt, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
                sp.setPreferredSize(new Dimension(500, 100));
                res = JOptionPane.showConfirmDialog(this, sp, "Delete Soil Files",
                        JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
            }

            switch (res) {
                case JOptionPane.CANCEL_OPTION:
                    return;
                case JOptionPane.YES_OPTION:
                    for (int i = 0; i < numFiles; i++) {
                        Util.deleteAll(new TFile(sf[i]));
                    }
                    break;
                case JOptionPane.NO_OPTION:
                    break;
            }
        } else {
            //System.out.println("W_oKaP: not approved");
        }

    }

    @Override
    public void exitItem_actionPerformed(java.awt.event.ActionEvent event) {
        exitApplication();
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void MI_log_actionPerformed(java.awt.event.ActionEvent evt) {
        new LogViewer().setVisible(true);
    }

    @Override
    public void MI_aboutItem_actionPerformed(java.awt.event.ActionEvent event) {

        try {
            // JAboutDialog Create with owner and show as modal
            AboutDialog JAboutDialog1 = new AboutDialog(this, usda.weru.util.Application.WEPS);
            JAboutDialog1.setModal(true);
            JAboutDialog1.setVisible(true);
        } catch (Exception e) {
        }

    }

    //added by Neha
    @Override
    public void MI_aboutButton_actionPerformed(java.awt.event.ActionEvent event) {
        //we do nothing here-but this button is added in the action listener in addHelp()
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void MI_welcomWizard_actionPerformed(java.awt.event.ActionEvent evt) {
        WelcomeWizard wizard = new WelcomeWizard(true);
        wizard.show();
    }

    @Override
    public void MICurrentSTIRSummary_actionPerformed(java.awt.event.ActionEvent event) {
        if (lastRun.length() == 0) {
            JOptionPane.showMessageDialog(this, "No current run available",
                    "Error (W-005)", JOptionPane.WARNING_MESSAGE);
            return;
        }
        String runDir = (!(new TFile(lastRun).isAbsolute()))
                ? (new TFile(projectDirectory, lastRun)).getAbsolutePath() : lastRun;
        ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_STIR);
    }

// Output reports - current run
    @Override
    public void MICurrentProjectSummary_actionPerformed(java.awt.event.ActionEvent event) {
        if (lastRun.length() == 0) {
            JOptionPane.showMessageDialog(this, "No current run available",
                    "Error (W-005)", JOptionPane.WARNING_MESSAGE);
            return;
        }
        String runDir = (!(new TFile(lastRun).isAbsolute()))
                ? (new TFile(projectDirectory, lastRun)).getAbsolutePath() : lastRun;
        ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_RUN);
    }

    @Override
    public void MICurrentYieldSummary_actionPerformed(java.awt.event.ActionEvent event) {
        if (lastRun.length() == 0) {
            JOptionPane.showMessageDialog(this, "No current run available",
                    "Error (W-005)", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (!(new TFile(lastRun).isAbsolute())) {
            lastRun = (new TFile(projectDirectory, lastRun)).getAbsolutePath();
        }
        ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_CROPSUM);
    }

    @Override
    public void MICurrentCCSummary_ActionPerformed(java.awt.event.ActionEvent event) {
        if (lastRun.length() == 0) {
            JOptionPane.showMessageDialog(this, "No current run available",
                    "Error (W-005)", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (!(new TFile(lastRun).isAbsolute())) {
            lastRun = (new TFile(projectDirectory, lastRun)).getAbsolutePath();
        }
        ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_COVERCROPSUM);
    }

    @Override
    public void MICurrentCISummary_ActionPerformed(java.awt.event.ActionEvent event) {
        if (lastRun.length() == 0) {
            JOptionPane.showMessageDialog(this, "No current run available",
                    "Error (W-005)", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (!(new TFile(lastRun).isAbsolute())) {
            lastRun = (new TFile(projectDirectory, lastRun)).getAbsolutePath();
        }
        ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_CROP_INT_SUM);
    }

    @Override
    public void MICurrentCropDet_actionPerformed(java.awt.event.ActionEvent event) {
        if (lastRun.length() == 0) {
            JOptionPane.showMessageDialog(this, "No current run available",
                    "Error (W-005)", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (!(new TFile(lastRun).isAbsolute())) {
            lastRun = (new TFile(projectDirectory, lastRun)).getAbsolutePath();
        }
        ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_CROPDET);
    }

    @Override
    public void MICurrentCCDetActionPerformed(java.awt.event.ActionEvent event) {
        if (lastRun.length() == 0) {
            JOptionPane.showMessageDialog(this, "No current run available",
                    "Error (W-005)", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (!(new TFile(lastRun).isAbsolute())) {
            lastRun = (new TFile(projectDirectory, lastRun)).getAbsolutePath();
        }
        ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_COVERCROPDET);
    }

    @Override
    public void MI_CurrentCIDetActionPerformed(java.awt.event.ActionEvent event) {
        if (lastRun.length() == 0) {
            JOptionPane.showMessageDialog(this, "No current run available",
                    "Error (W-005)", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (!(new TFile(lastRun).isAbsolute())) {
            lastRun = (new TFile(projectDirectory, lastRun)).getAbsolutePath();
        }
        ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_CROP_INT_DET);
    }

    public void MI_CurrentCIPerDetActionPerformed(java.awt.event.ActionEvent event) {
        if (lastRun.length() == 0) {
            JOptionPane.showMessageDialog(this, "No current run available",
                    "Error (W-005)", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (!(new TFile(lastRun).isAbsolute())) {
            lastRun = (new TFile(projectDirectory, lastRun)).getAbsolutePath();
        }
        ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_CROP_INT_PER_DET);
    }

    /**
     * Opens the Run Manager
     *
     * @param evt
     */
    @Override
    protected void MI_runmanger_actionPerformed(java.awt.event.ActionEvent evt) {
        Wmrm wmrm = new Wmrm(this);
        wmrm.setVisible(true);
        wmrm.init();
    }

    @Override
    public void MICurrentManagementSummary_actionPerformed(java.awt.event.ActionEvent event) {
        if (lastRun.length() == 0) {
            JOptionPane.showMessageDialog(this, "No current run available",
                    "Error (W-005)", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (!(new TFile(lastRun).isAbsolute())) {
            lastRun = (new TFile(projectDirectory, lastRun)).getAbsolutePath();
        }
        ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_MANAGEMENT);
    }

    @Override
    public void MICurrentOutput_actionPerformed(java.awt.event.ActionEvent event) {
        if (lastRun.length() == 0) {
            JOptionPane.showMessageDialog(this, "No current run available",
                    "Error (W-005)", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (!(new TFile(lastRun).isAbsolute())) {
            lastRun = (new TFile(projectDirectory, lastRun)).getAbsolutePath();
        }
        ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_DETAIL);
    }

    @Override
    public void MICurrentRawOutput_actionPerformed(java.awt.event.ActionEvent event) {
        if (lastRun.length() == 0) {
            JOptionPane.showMessageDialog(this, "No current run available",
                    "Error (W-005)", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (!(new TFile(lastRun).isAbsolute())) {
            lastRun = (new TFile(projectDirectory, lastRun)).getAbsolutePath();
        }
        ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_DEBUG);
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void MI_currentConfidenceInterval_actionPerformed(ActionEvent evt) {
        if (lastRun.length() == 0) {
            JOptionPane.showMessageDialog(this, "No current run available",
                    "Error (W-005)", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (!(new TFile(lastRun).isAbsolute())) {
            lastRun = (new TFile(projectDirectory, lastRun)).getAbsolutePath();
        }
        ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_CONFIDENCE_INTERVAL);
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void MI_otherConfidenceInterval_actionPerformed(ActionEvent evt) {
        ReportManager.getDefault().displayReport(projectDirectory, runsLocationPath, ReportManager.REPORT_CONFIDENCE_INTERVAL);
    }

    @Override
    protected void JBIRActionPerformed(java.awt.event.ActionEvent evt) {
        MI_currentConfidenceInterval_actionPerformed(evt);
    }

// Output reports - other run
    @Override
    public void MIOtherYieldSummary_actionPerformed(java.awt.event.ActionEvent event) {
        ReportManager.getDefault().displayReport(projectDirectory, runsLocationPath, ReportManager.REPORT_CROPSUM);
    }

    @Override
    public void MIOtherCropDet_ActionPerformed(java.awt.event.ActionEvent event) {
        ReportManager.getDefault().displayReport(projectDirectory, runsLocationPath, ReportManager.REPORT_CROPDET);
    }

    @Override
    public void MIOtherCCSummary_ActionPerformed(java.awt.event.ActionEvent event) {
        ReportManager.getDefault().displayReport(projectDirectory, runsLocationPath, ReportManager.REPORT_COVERCROPSUM);
    }

    @Override
    public void MIOtherCISummary_ActionPerformed(java.awt.event.ActionEvent event) {
        //For Alex to Finish implementing
        ReportManager.getDefault().displayReport(projectDirectory, runsLocationPath, ReportManager.REPORT_CROP_INT_SUM);
    }

    @Override
    public void MI_OtherCCDetActionPerformed(java.awt.event.ActionEvent event) {
        ReportManager.getDefault().displayReport(projectDirectory, runsLocationPath, ReportManager.REPORT_COVERCROPDET);
    }

    @Override
    public void MI_OtherCIDetActionPerformed(java.awt.event.ActionEvent event) {
        //For Alex to Finish implementing
        ReportManager.getDefault().displayReport(projectDirectory, runsLocationPath, ReportManager.REPORT_CROP_INT_DET);
    }

    public void MI_OtherCIPerDetActionPerformed(java.awt.event.ActionEvent event) {
        //For Alex to Finish implementing
        ReportManager.getDefault().displayReport(projectDirectory, runsLocationPath, ReportManager.REPORT_CROP_INT_PER_DET);
    }

    @Override
    public void MIOtherManagementSummary_actionPerformed(java.awt.event.ActionEvent event) {
        ReportManager.getDefault().displayReport(projectDirectory, runsLocationPath, ReportManager.REPORT_MANAGEMENT);
    }

    @Override
    public void MIOtherSTIREnergyReport_ActionPerformed(java.awt.event.ActionEvent event) {
        ReportManager.getDefault().displayReport(projectDirectory, runsLocationPath, ReportManager.REPORT_STIR);
    }

    @Override
    public void MIOtherSummary_actionPerformed(java.awt.event.ActionEvent event) {
        ReportManager.getDefault().displayReport(projectDirectory, runsLocationPath, ReportManager.REPORT_RUN);
    }

    @Override
    public void MIOtherOutput_actionPerformed(java.awt.event.ActionEvent event) {
        ReportManager.getDefault().displayReport(projectDirectory, runsLocationPath, ReportManager.REPORT_DETAIL);
    }

    @Override
    public void MIOtherRawOutput_actionPerformed(java.awt.event.ActionEvent event) {
        ReportManager.getDefault().displayReport(projectDirectory, runsLocationPath, ReportManager.REPORT_DEBUG);
    }

// Run Menu
    @Override
    public void MIMakeRun_actionPerformed(java.awt.event.ActionEvent event) {
        //System.out.println("run button pressed");
        //static function set in simulation panel if dates are unordered 
        //new run can not happen
        //System.out.println(getDatesUnordered());
        if (getDatesUnordered()) {
            JOptionPane.showMessageDialog(null, "Please Adjust Start Date and End Date."
                    + "\nStart Date must be set before End Date, unable to make Run.",
                    "Date Selection Error.", JOptionPane.WARNING_MESSAGE);
            return;
        }
        RunProgram rp = new RunProgram(this, rfd, cd, false);
        //set the title of the window to the new run - neha
        setTitle(new TFile(projectDirectory).getName());
    }

    @Override
    public void MIMakeCalibrationRun_actionPerformed(java.awt.event.ActionEvent event) {
        //System.out.println("cal button pressed");
        //static function set in simulation panel if dates are unordered 
        //new cal run can not happen
        //System.out.println(getDatesUnordered());
        if (getDatesUnordered()) {
            JOptionPane.showMessageDialog(null, "Please Adjust Start Date and End Date."
                    + "\nStart Date must be set before End Date, unable to make Calibration Run.",
                    "Date Selection Error.", JOptionPane.WARNING_MESSAGE);
            return;
        }
        //System.out.println("MI_mCR_aP : I am in MIMakeCalibrationRun BEFORE action performed");
        new RunProgram(this, rfd, cd, true);
        //System.out.println("MI_mCR_aP : I am in MIMakeCalibrationRun AFTER action performed");
    }

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

        WepsFileChooser wpc = new WepsFileChooser(WepsFileChooser.Filetype.RUN, projectDirectory, WepsFileChooser.SELECT);
        String path = runsLocationPath;
        if (path == null || path.length() <= 0) {
            path = defaultRunsLocationPath;
        }
        TFile currentDirectory = new TFile(path);
        if (!currentDirectory.exists()) {
            JOptionPane.showMessageDialog(this, "Runs location not found:\n" + currentDirectory.getPath(),
                    "Path Warning", JOptionPane.WARNING_MESSAGE);
            currentDirectory = new TFile(ConfigData.getDefault().getDataParsed(ConfigData.CurrentProj));
        }
        wpc.setCurrentDirectory(currentDirectory);
        //set the tooltip of "home" button to "Home" instead of "Desktop"
        wpc.homeToolTip(wpc);
        //remove the NewFolder button
        wpc.disableNewFolder(wpc);
        int retVal = wpc.showDialog(this);
        if (retVal == TFileChooser.APPROVE_OPTION) {
            restoreRun(new TFile(wpc.getSelectedFile()));
        }
    }

    /**
     *
     * @param runFile
     */
    public void restoreRun(TFile runFile) {
        RestoringContext.enter();
        try {
            logger.debug("Restore Run: " + runFile.getPath());
            //Is MCREW open?
            if (Mcrew.isOpen()) {
                logger.debug("MCREW is open.  Canceling restore.");
                JOptionPane.showMessageDialog(this, "Unable to restore run.\nPlease close MCREW.",
                        "WEPS", JOptionPane.WARNING_MESSAGE);
                return;
            }

            //Is soil open?
            if (usda.weru.soil.Soil.isOpen()) {
                logger.debug("Soil editor is open.  Canceling restore.");
                JOptionPane.showMessageDialog(this, "Unable to restore run.\nPlease close the soil editor.",
                        "WEPS", JOptionPane.WARNING_MESSAGE);
                return;
            }

            //Has warnings?        
            if (reviewWarnings) {
                TFile warningsFile = new TFile(runFile, RunFileData.WarningsFile);
                if (warningsFile != null && warningsFile.isFile() && warningsFile.length() > 0) {
                    logger.debug("Warnings file exists for run.");
                    int result = JOptionPane.showConfirmDialog(this, "The run you are restoring generated warnings.\n"
                            + "Would you like to review the warnings?", "WEPS",
                            JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                    switch (result) {
                        case JOptionPane.YES_OPTION:
                            BufferedReader in = null;
                            try {
                                String temp;
                                StringBuilder sb = new StringBuilder();
                                in = new BufferedReader(new TFileReader(warningsFile));
                                while ((temp = in.readLine()) != null) {
                                    sb.append(temp.trim() + "\n");

                                }
                                WepsMessageDialog.showScrollableMessage(this, "Review Generated Warnings",
                                        sb.toString(), projectDirectory, JOptionPane.WARNING_MESSAGE,
                                        WepsMessageDialog.OK_OPTION);

                            } catch (IOException e) {
                                logger.warn("Unable to read warnings file. " + warningsFile.getPath());
                            } finally {
                                try {
                                    in.close();
                                } catch (IOException e) {
                                    logger.error("Unable to close stream. " + warningsFile.getPath(), e);
                                }
                            }

                            break;
                        case JOptionPane.NO_OPTION:
                            break;
                        case JOptionPane.CANCEL_OPTION:
                            return;
                    }
                } else {
                    logger.debug("No warnings to review for run.");
                }
            }
            try {
                System.out.println("running...");
                System.out.println(runFile.getCanonicalPath());
                rfd.readRunFile(runFile.getCanonicalPath());

                changes.firePropertyChange(RunFileData.LastRun, null, runFile.getAbsolutePath());
                changes.firePropertyChange(RunFileData.LastRunAttempt, null, runFile.getAbsolutePath());

                setTitle(new TFile(projectDirectory).getName());
                changes.firePropertyChange(WEPS_RUNRESTORED, null, runFile.getCanonicalPath());
            } catch (IOException e) {
                logger.error("Unknown error while restoring run.", e);
                JOptionPane.showMessageDialog(this, "Unable to restore run.", "Unexpected Error", JOptionPane.ERROR_MESSAGE);
            }
        } finally {
            RestoringContext.exit();
        }
    }
    private String windGenStation = null;
    private String windGenCmdArgs = null;

    /**
     *
     * @param event
     */
    @Override
    public void MIWindStation_actionPerformed(java.awt.event.ActionEvent event) {
        //System.out.println("W_WSaP: " + WindGenDisp.parseWinCmd(windGenCmdArgs) + " " + windGenStation);
        Station station = getRunFileData().getBean().getWindgenStation();
        String data = ConfigData.getDefault().getDataParsed(ConfigData.WinData);

        new WindGenStationDisplay(data, station);
    }

    /**
     * Sending of emails from within the application interface happens via this
     * method as it allows the user to pull the EMAIL dialog made available and
     * perform the activitites useful for application related feedback like
     * runtime exception, a bad RUN file or PROJECT directory related issues
     * that might need the support team to address few issues that did arise
     * during the program execution.
     *
     * @param event The mouse click or keyboard enter action event that triggers
     * this method.
     */
    @Override
    public void MISendEmail_actionPerformed(java.awt.event.ActionEvent event) {
        try {
            /**
             * projectsPath is the directory in which the projects are present
             * projectDirectory is the directory in which the current run is
             * present. These both are needed for the File Choosers in the Email
             *
             */
            if ("1".equals(ConfigData.getDefault().getData(ConfigData.UseDefaultMailClient)) && Util.is64Bit()) {
                URI uri = new URI(String.format("mailto:%s?subject=%s",
                        ConfigData.getDefault().getData(ConfigData.CommentAddr),
                        URLEncoder.encode("WEPS Comments/Questions", "UTF-8")));

                Desktop.getDesktop().mail(uri);

            } else {
                Email.comment("WEPS Comments/Questions", null, null);
            }

        } catch (URISyntaxException | IOException e) {
            logger.error("Unable to open email.", e);
        }
    }

    @Override
    public void MIHelpTopics_actionPerformed(java.awt.event.ActionEvent event) {
    }

    private ConfigPanel c_configPanel;

    @Override
    public void MIEditConfig_actionPerformed(java.awt.event.ActionEvent event) {
        synchronized (this) {
            if (c_configPanel != null) {
                int state = c_configPanel.getExtendedState();
                //remove any iconified bits
                state &= ~JFrame.ICONIFIED;
                c_configPanel.setExtendedState(state);
                //bring it to the front
                c_configPanel.toFront();
                c_configPanel.setVisible(true);
                return;
            }
        }
        try {
            c_configPanel = new ConfigPanel(this);
            c_configPanel.addWindowListener(new WindowAdapter() {

                @Override
                public void windowClosed(WindowEvent e) {
                    synchronized (Weps.this) {
                        c_configPanel = null;
                    }
                }

            });
            c_configPanel.setVisible(true);

        } catch (java.lang.Exception e) {
        }
    }

    /**
     *
     * @param evt
     */
    @Override
    public void windowGainedFocus_actionPerformed(java.awt.event.WindowEvent evt) {
        //System.out.println("WEPS:WINDOW GAINED FOCUS entered");
        this.invalidate();
        this.repaint();
    }
    /*-----------------------------------------------------------------
     *
     * The following methods are called when the respective tool bar button
     * is pressed.  Weps_n makes buttons call the respective menu item as a
     * default action.  All the buttons here started out calling their
     * super so that their definitions can be here but they do the "right"
     * thing.  These items can be overridden at will.
     */

    private PropertyChangeSupport changes = new PropertyChangeSupport(this);

    /**
     * Allows the container to add or register some other components to
     * recognize the changes that occur on this component.
     *
     * @param l The listener that listens and reacts towards the the changes to
     * be reflected
     */
    @Override
    public void addPropertyChangeListener(PropertyChangeListener l) {
        changes.addPropertyChangeListener(l);
    }

    /**
     * Allows the container to remove or de-register some other components and
     * stop recognizing the changes that occur on this component.
     *
     * @param l The listener that does not listen and react towards the the
     * changes to be reflected.
     */
    @Override
    public void removePropertyChangeListener(PropertyChangeListener l) {
        changes.removePropertyChangeListener(l);
    }
    private boolean dataChanged = false;
    private boolean fireallFlg = false;
    private String projectDirectory = "";
    private String projectsPath = "";
    private String lastRun = "";

    /**
     *
     */
    public String runsLocationPath = "";

    /**
     *
     */
    public String defaultRunsLocationPath = "";
    private String measurementUnits = "";
    private String manFileName = "";
    private String soilFileName = "";

    private void setRunLocationText(String text) {
        g_runlocation.setText(text);
    }

    /**
     * We want to pick up the management file, soil file and last project IN
     * THAT ORDER. If any of those are uninitialized, an null will take it's
     * place.
     *
     * @return
     */
    public String[] getExceptionPackage() {
        String[] returnCase = new String[3];
        if (manFileName.equals("")) {
            returnCase[0] = null;
        } else {
            returnCase[0] = manFileName;
        }
        if (soilFileName.equals("")) {
            returnCase[1] = null;
        } else {
            returnCase[1] = soilFileName;
        }
        if (lastRun.equals("")) {
            returnCase[2] = null;
        } else {
            returnCase[2] = lastRun;
        }
        return returnCase;
    }

    /**
     *
     * @return
     */
    public TFile getRunsLocation() {
        if (runsLocationPath != null) {
            return new TFile(runsLocationPath);
        } else {
            String path = ConfigData.getDefault().getDataParsed(ConfigData.DefaultRunsLocation != null ? 
                    ConfigData.DefaultRunsLocation : ConfigData.DefaultRunsLocationTemplate);
            if (path != null) {
                return new TFile(path);
            }
        }
        return null;
    }

    /**
     * Recognizes and takes appropriate actions on registered properties from
     * different screens to update and synchronize data and GUI screens as
     * needed
     *
     * @param e The event itself that is responsible for triggering the change
     * required for registered properties/components.
     */
    @Override
    @Deprecated
    public void propertyChange(PropertyChangeEvent e) {
        if (e.getPropertyName().startsWith(ConfigData.REP)) {
            getButton(e.getPropertyName()).setVisible(cd.getReportVisibility(e.getPropertyName()));
        } else {
            switch (e.getPropertyName()) {
                case ConfigData.SingleProjectMode:
                    if (e.getNewValue().equals("1")) {
                        M_project.setText("File");
                        M_project.remove(newItem);
                        M_project.remove(openItem);
                        M_project.remove(saveAsItem);
                        M_project.remove(deleteProjectItem);
                        c_singleProjectMode = true;
                        newButton.setVisible(false);
                        openButton.setVisible(false);

                    }
                    break;
                case RunFileData.DataChanged:
                    String val = (String) e.getNewValue();
                    if (val.equals("fireall")) {
                        fireallFlg = !fireallFlg;
                    }
                    if (fireallFlg) {
                        return;
                    }
                    dataChanged = val.equals(RunFileData.DataChanged);
                    break;
                case ConfigData.CurrentProj:
                    projectDirectory = e.getNewValue().toString();
                    projectDirectory = Util.parse(projectDirectory);
                    if (runsLocationPath.equals("")) {
                        setRunLocationText(ConfigData.getDefault().getData(ConfigData.DefaultRunsLocation));
                    } else {
                        setRunLocationText(new TFile(runsLocationPath).getAbsolutePath());
                    }
                    updateTitle();
                    break;
                case RunFileData.RunTypeDisp:
                    //                if (e.getNewValue().equals(ConfigData.NRCS)) {
                    MI_currentStirEnergyReport.setVisible(true);
                    MI_otherStirEnergyReport.setVisible(true);
                    //                } else {
                    //                    MI_currentStirEnergyReport.setVisible(false);
                    //                    MI_otherStirEnergyReport.setVisible(false);
                    //                }
                    break;
                case RunFileData.LastRun:
                    lastRun = ((String) e.getNewValue());
                    updateTitle();
                    break;
                case ConfigData.ProjDir:
                    projectsPath = ((String) e.getNewValue());
                    projectsPath = Util.parse(projectsPath);
                    break;
                case ConfigData.Units:
                    measurementUnits = ((String) e.getNewValue());
                    break;
                case RunFileData.ClimateFile:
                    cliGenFile = ((String) e.getNewValue());
                    break;
                case RunFileData.WindFile:
                    winGenFile = ((String) e.getNewValue());
                    break;
                case ConfigData.MantisPassword:
                    mantisPassword = e.getNewValue().toString();
                    break;
                case ConfigData.MantisUser:
                    mantisUser = e.getNewValue().toString();
                    break;
                case ConfigData.MantisURL:
                    mantisURL = e.getNewValue().toString();
                    break;
                case ConfigData.MantisEmail:
                    mantisEmail = e.getNewValue().toString();
                    break;
                case ConfigData.MantisProject:
                    mantisProject = e.getNewValue().toString();
                    break;
                case ConfigData.TTInit:
                    setTTTime((String) e.getNewValue(), 1);
                    break;
                case ConfigData.TTDismiss:
                    setTTTime((String) e.getNewValue(), 2);
                    break;
                case RunFileData.WinGenStation:
                    windGenStation = ((String) e.getNewValue());
                    break;
                case ConfigData.WinCmd:
                    windGenCmdArgs = ((String) e.getNewValue());
                    break;
                case RunFileData.ManageFile:
                    setManageFileName(e);
                    break;
                case RunFileData.SoilFile:
                    setSoilFile(e);
                    break;
                case RunFileData.RunsLocation:
                    if (e.getNewValue() == null || e.getNewValue().toString().equals("NULL")) {
                        runsLocationPath = ConfigData.getDefault().getData(ConfigData.DefaultRunsLocation);
                    } else {
                        runsLocationPath = e.getNewValue().toString();
                    }
                    setRunLocationText(runsLocationPath);
                    break;
                case ConfigData.DefaultRunsLocation:
                    defaultRunsLocationPath = e.getNewValue().toString();
                    break;
                case ConfigData.DoNotReviewWarningsWhenRestoringRun:
                    reviewWarnings = e.getNewValue().toString().equals("0");
                    break;
                case Weps.WEPS_RUNCREATED:
                    changes.firePropertyChange(e);
                    break;
                case ConfigData.DoNotWarnAboutSystemLocale:
                    String value = e.getNewValue().toString();
                    warnAboutLocale = !value.equals("1");
                    break;
                case ConfigData.DoNotEstimateMissingSurgoValues:
                    if (e.getNewValue().equals("0")) {
                        NASIS.setEstimateNullValues(true);
                    } else {
                        NASIS.setEstimateNullValues(false);
                    }
                    break;
                case ConfigData.OMFractionThreshold:
                    try {
                        NASIS.setOmFractionThreshold(Double.parseDouble(e.getNewValue().toString()));
                    } catch (NumberFormatException ex) {
                    }
                    break;
                case ConfigData.ReportsConfidenceIntervalEnabled:
                    MI_currentConfidenceInterval.setVisible(ConfigData.getDefault().isReportConfidenceIntervalEnabled());
                    MI_otherConfidenceInterval.setVisible(ConfigData.getDefault().isReportConfidenceIntervalEnabled());
                    JB_IR.setVisible(ConfigData.getDefault().isReportConfidenceIntervalEnabled());
                    break;
                case ConfigData.ReportsCropIntPerDetEnabled:
                    MI_CurrentCIPDet.setVisible(ConfigData.getDefault().isReportCropIntPerDetEnabled());
                    MI_otherCIPDet.setVisible(ConfigData.getDefault().isReportCropIntPerDetEnabled());
                    break;
            }
        }
    }

    /**
     * Listens for properties and actions from different applications in weps.
     */
    private void setSoilFile(PropertyChangeEvent e) {
        soilFileName = (String) e.getNewValue();
        TFile sf = new TFile(soilFileName);
        if (!sf.exists()) {
            if (soilFileName.equals("")) {
                return;
            }
            soilFileName = "";
            changes.firePropertyChange(RunFileData.SoilFile, null, "");
            return;
        }

        //Make sure the file is in the project        
        logger.debug("soil file: " + sf);
        //System.out.println("AP:JL_MmC:Abs Path of mfn "+mfn.getAbsolutePath());                                   
        TFile pd = new TFile(projectDirectory);
        try {
            if (!isAncestorOf(pd, sf)) {
                logger.info("Soil file is not located in the project.  Copying the file into the project.");
                String fromFile = sf.getCanonicalPath();
                String toFile = new TFile(pd, sf.getName()).getCanonicalPath();
                Util.copyFile(fromFile, toFile);
                changes.firePropertyChange(RunFileData.SoilFile, fromFile, toFile);
            }
        } catch (java.io.IOException ioe) {
            logger.error("Unable to copy soil file.", ioe);
        }
    }

    private void setManageFileName(PropertyChangeEvent e) {
        //Set the name of the current Management File as manFileName
        //If it doesnt exist, then make the string empty
        manFileName = (String) e.getNewValue();
        TFile mf = new TFile(manFileName);
        if (!mf.exists()) {
            manFileName = "";
            changes.firePropertyChange(RunFileData.ManageFile, null, "");
            return;
        }

        //Make sure the file is in the project        
        logger.debug("management file: " + mf);
        //System.out.println("AP:JL_MmC:Abs Path of mfn "+mfn.getAbsolutePath());                                   
        TFile pd = new TFile(projectDirectory);
        try {
            if (!isAncestorOf(pd, mf)) {
                logger.info("Management file is not located in the project.  Copying the file into the project.");
                String fromFile = mf.getCanonicalPath();
                String toFile = new TFile(pd, mf.getName()).getCanonicalPath();
                Util.copyFile(fromFile, toFile);
                changes.firePropertyChange(RunFileData.ManageFile, fromFile, toFile);
            }
        } catch (java.io.IOException ioe) {
            logger.error("Unable to copy management file.", ioe);
        }
    }

    //Returns true if the child is in the parent's directory tree.
    private boolean isAncestorOf(TFile parent, TFile child) {
        //Fix for if the restored run is in the current project
        if (child.getParentFile().getName().endsWith(".wjr")) {
            return false;
        }
        while (parent != null && child != null) {
            if (child.equals(parent)) {
                return true;
            }
            if (child.getParentFile() != null) {
                child = new TFile(child.getParentFile());
            } else {
                child = null;
            }
        }
        return false;
    }
    private boolean ttFlg = false;

    private void setTTTime(String val, int id) {

        switch (id) {
            case 1:
                try {
                    int initDelay = Integer.parseInt(val.trim());
                    ToolTipManager.sharedInstance().setInitialDelay(initDelay);
                    ttFlg = true;
                } catch (NumberFormatException e) {
                    //System.err.println("W_sTTT: error setting initial delay " + val);
                }
                break;
            case 2:
                try {
                    int disDelay = Integer.parseInt(val.trim());
                    ToolTipManager.sharedInstance().setDismissDelay(disDelay);
                    ttFlg = true;
                } catch (NumberFormatException e) {
                    //System.err.println("W_sTTT: error setting dismiss delay " + val);
                }
                break;
            case 3:
                if (ttFlg) {
                    return;
                }
                int tim = ToolTipManager.sharedInstance().getDismissDelay();
                String timStr = "" + tim;
                changes.firePropertyChange(ConfigData.TTDismiss, null, timStr);
                tim = ToolTipManager.sharedInstance().getInitialDelay();
                timStr = "" + tim;
                changes.firePropertyChange(ConfigData.TTInit, null, timStr);
                break;
        }
    }

    private void addHelp() {
        logger.debug("Adding help...");
        loadHelp();
        addCSH(Help.getHelpSet());

        hs = Help.getHelpSet();

        logger.debug("Creating help broker...");
        hb = hs.createHelpBroker();
        logger.debug("Finished adding help.");
    } //end of addhelp()

    private void loadHelp() {
        logger.debug("Loading help...");
        try {
            //Try to load the master help first.  If it can not be found we try a weps specific help.
            //We try to load directories first for development reasons.  This way we see changes without
            //updating the jar files.

            String masterJar = "jar/MasterHelp.jar";
            String masterDir = "help/MasterWeps.hs";

            String wepsJar = "jar/WepsHelp.jar";
            String wepsDir1 = "help/weps.hs";
            String wepsDir2 = "help/weps1/weps.hs";

            if (Help.loadJar(masterJar)) {
                logger.debug("Loaded " + masterJar);
            } else if (Help.loadDirectory(masterDir)) {
                logger.debug("Loaded " + masterDir);
            } else if (Help.loadJar(wepsJar)) {
                logger.debug("Loaded " + wepsJar);
            } else if (Help.loadDirectory(wepsDir1)) {
                logger.debug("Loaded " + wepsDir1);
            } else if (Help.loadDirectory(wepsDir2)) {
                logger.debug("Loaded " + wepsDir2);
            }
        } finally {
            logger.debug("Done loading help.");
        }
    }

    private void addCSH(HelpSet hs) {
        logger.debug("Adding context sensitive help...");
        hb = hs.createHelpBroker();
        hb.enableHelpKey(getRootPane(), "introduction_html", hs);
        hb.enableHelpOnButton(MI_helpTopics, "introduction_html", hs);
        hb.enableHelpOnButton(aboutButton, "introduction_html", hs);
        ActionListener helper = new CSH.DisplayHelpFromSource(hb);
        //System.out.println("I am in the WEPS addHelp()" + helper);
        MI_helpTopics.addActionListener(helper);
        aboutButton.addActionListener(helper);
        helpButton.addActionListener(new CSH.DisplayHelpAfterTracking(hs, "javax.help.Popup", null));
        CSH.setHelpIDString(newButton, "tbNew_html");
        CSH.setHelpIDString(openButton, "tbOpen_html");
        CSH.setHelpIDString(saveButton, "tbSave_html");
        CSH.setHelpIDString(runButton, "tbRunButton_html");
        CSH.setHelpIDString(runCalButton, "tbRunCal_html");
        CSH.setHelpIDString(loadrunButton, "tbLoadRun_html");
        CSH.setHelpIDString(emailButton, "tbEmail_html");
        CSH.setHelpIDString(mantisButton, "tbMantis_html");
        CSH.setHelpIDString(LaunchNrmvToolbar, "tbNRMV_html");
        CSH.setHelpIDString(aboutButton, "tbHelpButton_html");
        CSH.setHelpIDString(helpButton, "tbPopupHelp_html");
        CSH.setHelpIDString(JB_RR, "tbProjectSummary_html");
        CSH.setHelpIDString(JB_MR, "tbManagementSummary_html");
        CSH.setHelpIDString(JB_CR, "tbCropSummary_html");
        CSH.setHelpIDString(JB_CC, "tbCoverCrop_html");
        CSH.setHelpIDString(JB_CI, "tbCropInterval_html");
        CSH.setHelpIDString(JB_SR, "tbSTIREnergySummary_html");
        CSH.setHelpIDString(JB_DR, "tbDetailedSummary_html");
        CSH.setHelpIDString(JB_IR, "tbConfidenceInterval_html");
        CSH.setHelpIDString(MB_main, "menubarPanel_html");
        CSH.setHelpIDString(M_project, "mnuProject_html");
        CSH.setHelpIDString(MI_config, "mnuConfiguration_html");
        CSH.setHelpIDString(M_output, "mnuViewOutput_html");
        CSH.setHelpIDString(M_run, "mnuRun_html");
        CSH.setHelpIDString(M_tools, "mnuTools_html");
        CSH.setHelpIDString(M_help, "mnuHelp_html");
        CSH.setHelpIDString(g_runlocation, "runLocation_html");
        CSH.setHelpIDString(JB_setRunLocation, "runLocation_html");
        CSH.setHelpIDString(JP_not, "notesPanel_html");
        //for the tool bar of Weps screen
        CSH.setHelpIDString(JTB_main, "toolbarPanel_html");
        CSH.setHelpIDString(JTB_main, "toolbarPanel_html");
        //Backup panel help.
        CSH.setHelpIDString(JP_client, "clientPanel_html");
        CSH.setHelpIDString(JP_reg, "regPanel_html");
        CSH.setHelpIDString(JP_loc, "locationPanel_html");
        CSH.setHelpIDString(JP_bar, "barPanel_html");
        CSH.setHelpIDString(JP_aux, "MCREWSoilPanel_html");
        CSH.setHelpIDString(JP_not, "notesPanel_html");
        CSH.setHelpIDString(JP_sim, "simrunPanel_html");
        CSH.setHelpIDString(runLocationPanel, "runLocation_html");
        logger.debug("Done adding context sensitive help.");

    }//end of addCSH
    private String cliGenFile = "";
    private String winGenFile = "";

    private void winCliMode() {
        if (winGenFile.endsWith(RunFileData.DefaultWinGenName) || winGenFile.trim().length() == 0) {
            //changes.firePropertyChange(ConfigData.WindFlag, null, "0");
            //changes.firePropertyChange(RunFileData.WindFlag, null, "0");
            changes.firePropertyChange(RunFileData.WindFile, null, RunFileData.DefaultWinGenName);
        }
        if (cliGenFile.endsWith(RunFileData.DefaultCliGenName) || cliGenFile.trim().length() == 0) {
            //changes.firePropertyChange(ConfigData.ClimateFlag, null, "0");
            //changes.firePropertyChange(RunFileData.ClimateFlag, null, "0");
            changes.firePropertyChange(RunFileData.ClimateFile, null, RunFileData.DefaultCliGenName);
        }
    }

    private void loadCurrentProject(Weps wp) {
        new LoadCP(wp);
    }

    /**
     * This private class may be a bit confusing. It opens and sets * the
     * current project in the constructor. It then adds a shutdown * hook to
     * save the name of the current project when the app * exits. It does NOT
     * load any data.
     *
     */
    private class LoadCP extends Thread {

        private final TFile projFile;
        Weps wp;

        /**
         * Here we are finding the last project that has been modified in the
         * "projects" direcory [which is got from the 'projectsPath'] We check
         * for the modification time of the "weps.ini" file in every project
         * directory[.wpj files] and after getting the last modified weps.ini
         * file we get its parent which is the Project[.wpj] directory and store
         * it in the variable "projectsDir". If there are no projects in the
         * "projects" directory, then call "createProj" method.
         */
        private void findLastProj() {
            //System.out.println("W_LCp_fLP: " + projectsPath);
            TFile projDir = new TFile(projectsPath);
            if (!projDir.isDirectory()) {
                return;
            }
            java.io.File[] projNames = projDir.listFiles(new FilenameFilter() {

                @Override
                public boolean accept(java.io.File dir, String name) {
                    return name.endsWith(".wpj");
                }
            });
            if (projNames.length == 0) {
                createProj();
                return;
            }
            TFile lastProj = new TFile(projNames[0], "weps.ini");
            TFile tmp = null;
            for (java.io.File projName : projNames) {
                //System.out.println("W_LCP_fLP: ||" + projNames[idx].getName());
                tmp = new TFile(projName, "weps.ini");
                if (tmp.lastModified() <= lastProj.lastModified()) {
                    continue;
                }
                lastProj = tmp;
            }
            //System.out.println("W_LCP_fLP: >>" + lastProj.getParent());

            String projectsDir = lastProj.getParentFile().getAbsolutePath();

            wp.changes.firePropertyChange(ConfigData.CurrentProj, null, projectsDir);
            wp.changes.firePropertyChange(RunFileData.LastRun, null, "");

            wp.rfd.readRunData(projectsDir);
            wp.winCliMode();
        }

        /**
         * Ask the user to create a Valid Project Directory and set this value
         * in the Configuration Panel also
         */
        private void createSelectProjDir() {
            int rtnVal = -1;
            if (!c_singleProjectMode) {
                rtnVal = JOptionPane.showOptionDialog(wp,
                        "WEPS needs a default directory location\n"
                        + "specified for it to store WEPS Project information.\n\n"
                        + "Either the directory specified in the configuration file\n"
                        + "is not accessible (read-only) or doesn't exist.\n\n"
                        + "Please \'Create\' a new directory or \'Select\'\n"
                        + "another\"projects\" directory for WEPS to use.\n\n",
                        "Warning (W-303)",
                        JOptionPane.DEFAULT_OPTION,
                        JOptionPane.WARNING_MESSAGE,
                        null,
                        new String[]{"Create", "Select", "Exit"},
                        "Create");
            } else {
                rtnVal = 3;
            }
            switch (rtnVal) {
                case 0:
                    wp.makeProjDir();
                    createProj();
                    Runtime.getRuntime().addShutdownHook(this);
                    break;
                case 1:
                    wp.selectProjDir();
                    checkForLastProj();
                    break;
                case 2:
                    throw new RuntimeException("exit");
                case 3:
                    TFile f = new TFile(wp.projectsPath);
                    f.mkdir();
                    checkForLastProj();
                    changes.firePropertyChange(RunFileData.RunsLocation, null, projectDirectory);
                    break;
            }
        }

        /**
         * If the user selects an existing Projects DIRECTORY, this will be
         * called from createSelectProjDir() and we check for the Last project
         * in this directory
         */
        private void checkForLastProj() {
            if (c_singleProjectMode) {
                TFile dir = new TFile(projectDirectory);
                if (!(dir.exists())) {
                    try {
                        makeProject(projectDirectory, false);

                    } catch (IOException ex) {
                        logger.error("Unable to create project.", ex);
                    } finally {
                        wp.rfd.initialize();
                    }
                } else {
//                    changes.firePropertyChange(ConfigData.CurrentProj, null, projectDirectory);
                    wp.rfd.readRunData(projectDirectory);
                    setTitle(dir.getName());
                }

            } else {
                if (!projFile.exists()) {
                    //JOptionPane.showMessageDialog(wp, "Last used project not recorded","Warning (W-101)",
                    //JOptionPane.WARNING_MESSAGE);
                    findLastProj();
                    /**
                     * getRunTime returns the current runtime object associated
                     * with the current java application. addShutdownHook
                     * returns a new virtual-machine shut down hook.
                     */
                    Runtime.getRuntime().addShutdownHook(this);
                    return;
                }
                BufferedReader in = null;
                try {

                    /**
                     * Reading the "lastproj.txt" file. If the path mentioned in
                     * the file does not refer to an existing file, then show a
                     * warning message, find the last modified project by
                     * calling the findLastProj method and add a Runtime
                     * shutdown Hook.
                     */
                    in = new BufferedReader(new TFileReader(projFile));
                    String temp = in.readLine();

                    if (temp != null) {
                        TFile tmpFile = new TFile(temp);
                        if (!tmpFile.exists()) {
                            //JOptionPane.showMessageDialog(wp, "Last used project not found","Error (W-102)",
                            //JOptionPane.WARNING_MESSAGE);
                            findLastProj();
                            Runtime.getRuntime().addShutdownHook(this);
                            return;
                        }
//                        wp.changes.firePropertyChange(ConfigData.CurrentProj, null, temp);
                        wp.rfd.readRunData(temp);
                    }
                    in.close();
                } catch (IOException e) {
                    //System.err.println("LCP: " + e);
                } finally {
                    try {
                        in.close();
                    } catch (IOException e) {
                        logger.error("Error closing file stream", e);
                    }
                }
            }
            Runtime.getRuntime().addShutdownHook(this);
        }//end of checkForLastProj()

        private void checkForRunsLocation() {
            //only auto create for single project mode
            if (c_singleProjectMode) {
                runsLocationPath = runsLocationPath == null ? this.wp.cd.getData(
                        ConfigData.DefaultRunsLocation) : runsLocationPath.equals("") 
                        ? this.wp.cd.getData(ConfigData.DefaultRunsLocation) : 
                        runsLocationPath;
                TFile dir = new TFile(runsLocationPath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
            }
        }

        /**
         * Ask the user to create a new project or otherwise Exit.
         */
        private void createProj() {

            int rtnVal = JOptionPane.showOptionDialog(wp,
                    "No initial WEPS project found.\nPlease \'Create\' a new WEPS project.",
                    "Warning (W-302)",
                    JOptionPane.DEFAULT_OPTION,
                    JOptionPane.WARNING_MESSAGE,
                    null,
                    new String[]{"Create", "Exit"},
                    "Create");
            switch (rtnVal) {
                case 0:
                    wp.newItem_actionPerformed(null);
                    break;
                case 1:
                    throw new RuntimeException("exiting");
            }

            if (!(new TFile(projectDirectory)).exists()) {
                JOptionPane.showMessageDialog(wp, "No project specified\nWEPS will exit",
                        "Error (W-301)", JOptionPane.WARNING_MESSAGE);
                throw new RuntimeException("Error W-301");
            }
        }

        /**
         * Read the last project recorded in the "lastproj.txt" file in the
         * "cfg" directory. If the file "lastproj.txt" is not found then call
         * findLastProj method.
         */
        LoadCP(Weps wp) {
            this.wp = wp;
            // The lastproj.txt is created in the present working Project Directory.
            projFile = new TFile(About.getUserWeps(), "lastproject.txt");
            /**
             * If the Project DIRECTORY "projects" does not exist or if the
             * Project Directory is Read-Only, then create a Project Directory,
             * set this as the default projects directory and then proceed to
             * create a Project in this new directory
             */

            if (!wp.c_singleProjectMode) {
                TFile projDir = new TFile(wp.projectsPath).getCanOrAbsFile();
                if (!projDir.exists() || !projDir.canWrite()) {
                    //System.out.println("The Projects directory does not exist");
                    createSelectProjDir();
                    // createProj();
                    // Runtime.getRuntime().addShutdownHook(this);
                    return;
                }
            }
            checkForLastProj();
            checkForRunsLocation();
        }

        /**
         * This run method executes when the WEPS system exits.It writes into
         * the file "lastproj.txt" the name of the last project exected.
         */
        @Override
        public void run() {
            if (wp.c_singleProjectMode) {
                //don't save the last project if we're in single project mode
                return;
            }
            try {
                //Update the lastproj.txt file with the latest project path
                try (PrintWriter out = new PrintWriter(new BufferedWriter(new TFileWriter(projFile)))) {
                    out.println(wp.projectDirectory);
                }
            } catch (IOException e) {
                //System.err.println("LCP_r: " + e);
            }
        }
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void MIDiff_actionPerformed(java.awt.event.ActionEvent evt) {
        DifferFrame differ = new DifferFrame();
        cd.addPropertyChangeListener(differ);
        cd.fireAll(differ);
        differ.setVisible(true);
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void JB_DR_actionPerformed(java.awt.event.ActionEvent evt) {
        MICurrentOutput_actionPerformed(evt);
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void JB_CR_actionPerformed(java.awt.event.ActionEvent evt) {
        MICurrentYieldSummary_actionPerformed(evt);
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void JB_MR_actionPerformed(java.awt.event.ActionEvent evt) {
        MICurrentManagementSummary_actionPerformed(evt);
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void JB_RR_actionPerformed(java.awt.event.ActionEvent evt) {
        MICurrentProjectSummary_actionPerformed(evt);
    }

    @Override
    protected void JB_CC_ActionPerformed(java.awt.event.ActionEvent evt) {
        MICurrentCCSummary_ActionPerformed(evt);
    }

    @Override
    protected void JB_CI_ActionPerformed(java.awt.event.ActionEvent evt) {
        //For Alex to Finish implementing
        MICurrentCISummary_ActionPerformed(evt);
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void JB_SR_actionPerformed(java.awt.event.ActionEvent evt) {
        MICurrentSTIRSummary_actionPerformed(evt);
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void setRunLocation_actionPerformed(java.awt.event.ActionEvent evt) {
        WepsFileChooser wfc = new WepsFileChooser(WepsFileChooser.Filetype.RUNDIR, projectDirectory, WepsFileChooser.SELECT);

        if (runsLocationPath != null && runsLocationPath.length() > 0) {
            wfc.setSelectedFile(new TFile(runsLocationPath));
        } else if (defaultRunsLocationPath != null && defaultRunsLocationPath.length() > 0) {
            wfc.setSelectedFile(new TFile(defaultRunsLocationPath));
        } else {
            wfc.setCurrentDirectory(new TFile(projectDirectory));
        }

        wfc.setAccessory(new ResetRunLocationPanel(cd, rfd, wfc));

        if (wfc.showDialog(this) == WepsFileChooser.APPROVE_OPTION) {
            String temp = wfc.getSelectedFile().getAbsolutePath();
            rfd.setData(RunFileData.RunsLocation, temp);
        }
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void JTF_mostRecentRun_mouseMoved(java.awt.event.MouseEvent evt) {
        String tip = "<HTML><b>Most Recent Run</b><br>" + lastRun + " <br></HTML>";
        String current = JTF_mostRecentRun.getToolTipText();
        if (current == null || current.equals(tip) == false) {
            JTF_mostRecentRun.setToolTipText(tip);
        }
    }

//    protected void JP_center_componentResized(java.awt.event.ComponentEvent evt) {
//        int x=JP_center.getSize().width / 2 - JP_main.getSize().width / 2;
//        int y=JP_center.getSize().height / 2 - JP_main.getSize().height / 2;
//        JP_main.setLocation(x, y);
//
//    }
    /**
     *
     * @param evt
     */
    @Override
    protected void MI_userGuideActionPerformed(java.awt.event.ActionEvent evt) {
        TFile guidef = new TFile("readme/WEPSUserGuide.pdf");
        try {
            java.awt.Desktop.getDesktop().open(guidef);
        } catch (IOException ex) {
            try {
                javax.swing.JOptionPane.showMessageDialog(this, guidef.getCanonicalPath() + " not found",
                        "WEPS User Guide not found", javax.swing.JOptionPane.ERROR_MESSAGE);
            } catch (HeadlessException | IOException he) {
                ex.printStackTrace();
            }
        }
    }

    String mantisURL;
    String mantisUser;
    String mantisPassword;
    String mantisEmail;
    String mantisProject;

    /**
     *
     * @param evt
     */
    @Override
    protected void JMI_mantisActionPerformed(java.awt.event.ActionEvent evt) {
        usda.weru.util.Mantis man = new usda.weru.util.Mantis(rfd, mantisURL, mantisEmail, mantisUser,
                mantisPassword, "default", mantisProject, null);
        man.setVisible(true);
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void JMI_cropsreport_actionPerformed(java.awt.event.ActionEvent evt) {
        ReportManager.getDefault().displayReport(ReportManager.REPORT_DATABASE_CROPS);
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void JMI_opsreport_actionPerformed(java.awt.event.ActionEvent evt) {
        ReportManager.getDefault().displayReport(ReportManager.REPORT_DATABASE_OPERATIONS);
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void JMI_manreport_actionPerformed(java.awt.event.ActionEvent evt) {
        ReportManager.getDefault().displayReport(ReportManager.REPORT_DATABASE_MANAGEMENTS);
    }

    /**
     * Commented out to get rid of NRMV. code :GRONRMV12
     *
     * @Override protected void RunNRMV() { try { nrmv.nrmv.main(new String[]
     * {"DISPOSE_ON_CLOSE"}); /* try { System.out.println("NRMV launching");
     *
     * Runtime rt = Runtime.getRuntime();
     *
     * String[] cmd = {"java", "-jar", "jar/NRMV_Standalone.jar"}; //
     * NRMV_UPGM.jar requires Java 7 to run Process proc = rt.exec(cmd);
     *
     * InputStream stderr = proc.getErrorStream(); if (stderr.available() > 0) {
     * System.out.println("<ERROR>"); for (int i = 0; i < stderr.available();
     * i++) { System.out.println("" + stderr.read()); }
     * System.out.println("</ERROR>"); }
     *
     * } catch (IOException t) { t.printStackTrace(); }
     */
    /**
     * } catch (Exception ex) { Exceptions.printStackTrace(ex); } }
     */
    @Override
    protected void ClearNRMVFiles() {
        List<java.io.File> nrmvFolders = FindDirectoriesWithSameName("nrmvfiles", new java.io.File(runsLocationPath));
        for (java.io.File f : nrmvFolders) {
            if (!delete(f)) {
                System.out.println("Error deleting directory: " + f.toString());
            }
        }
    }

    private static List<java.io.File> FindDirectoriesWithSameName(String name, java.io.File root) {
        List<java.io.File> result = new ArrayList<>();

        for (java.io.File file : root.listFiles()) {
            if (file.isDirectory()) {
                if (file.getName().equals(name)) {
                    result.add(file);
                }
                result.addAll(FindDirectoriesWithSameName(name, file));
            }
        }
        return result;
    }

    /**
     * deletes a file or the contents of a directory returns true if successful
     */
    private static boolean delete(java.io.File file) {
        boolean success = true;
        if (file.isDirectory()) {

            //directory is empty, then delete it
            if (file.list().length == 0) {
                if (!file.delete()) {
                    success = false;
                }
                System.out.println("Directory deleted : " + file.getAbsolutePath());

            } else {

                for (java.io.File temp : file.listFiles()) {

                    //recursive delete
                    if (!delete(temp)) {
                        success = false;
                    }
                }

                //check the directory again, if empty then delete it
                if (file.list().length == 0) {
                    if (!file.delete()) {
                        success = false;
                    }
                    System.out.println("Directory deleted : " + file.getAbsolutePath());
                }
            }
        } else //if file, then delete it
        {
            if (!file.delete()) {
                success = false;
            } //System.out.println("\tFile deleted : " + file.getAbsolutePath());
        }
        return success;
    }

    @Override
    protected void createNrmvFiles(boolean summaries) {

        WepsFileChooser wpc = new WepsFileChooser(WepsFileChooser.Filetype.RUN, projectDirectory, WepsFileChooser.SELECT);
        String path = runsLocationPath;
        if (path == null || path.length() <= 0) {
            path = defaultRunsLocationPath;
        }
        java.io.File currentDirectory = new TFile(path);
        if (!currentDirectory.exists()) {
            JOptionPane.showMessageDialog(this, "Runs location not found:\n" + currentDirectory.getPath(),
                    "Path Warning", JOptionPane.WARNING_MESSAGE);
            currentDirectory = new java.io.File(ConfigData.getDefault().getDataParsed(ConfigData.CurrentProj));
        }
        wpc.setCurrentDirectory(currentDirectory);
        // set the tooltip of "home" button to "Home" instead of "Desktop"
        wpc.homeToolTip(wpc);
        // remove the NewFolder button
        wpc.disableNewFolder(wpc);
        int retVal = wpc.showDialog(this);

        if (retVal == TFileChooser.APPROVE_OPTION) {
            ConvertAllToNrmv catn = new ConvertAllToNrmv(wpc.getSelectedFile().getName(), wpc.getSelectedFile().toString());
            catn.shouldDoAverages(summaries);
            catn.run();
        }
    }
}
