package usda.weru.weps;


import de.schlichtherle.io.File;
import de.schlichtherle.io.FileInputStream;
import de.schlichtherle.io.FileReader;
import de.schlichtherle.io.FileWriter;


import de.schlichtherle.io.swing.JFileChooser;
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.net.URI;
import java.net.URL;
import java.net.URLEncoder;
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 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 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 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 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_RUNLreOCATION = WEPS + "run location";
    /**
     * Static defintions for WEPS system.
     */
    public RunFileData rfd;
    protected ConfigData cd;
    //private ConfigPanel cp;
    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;

    public static Weps getInstance(){
        return c_instance;
    }
    /**
     * Default constructor for the main WEPS GUI application.
     */
    public Weps() {
        super();
        c_instance = this;
        //setIconImage(wepsIcon.getImage());

        addHelp();

        MI_currentStirEnergyReport.addActionListener(new ActionListener() {

            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 File(lastRun).isAbsolute())) ? (new File(projectDirectory, lastRun)).getAbsolutePath() : lastRun;                
                ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_STIR);
            }
        });
        MI_otherStirEnergyReport.addActionListener(new ActionListener() {

            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 (Exception e) {
        }
//		super.exitApplication();
    }

    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(File 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 (Exception 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;
            File file = new File(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 (Exception 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 (Exception e) {
                            fileDate = new Date(file.lastModified());
                        }

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

                    }
                    return false;
                }
            };

            if (file != null) {
                File dir = (File) file.getParentFile();
                if (dir != null) {
                    File[] logs = dir.listFiles(filter, dir.getArchiveDetector());
                    for (File log : logs) {
                        log.delete();
                    }
                }
            }
        }
    }

    
    /**
     * 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
            String requiredVersion = "1.6";
            String currentVersion = System.getProperty("java.specification.version");

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

            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;

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

            if (working != null){
                working = Util.parse(working);
                File workingFile = new File(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);
                File userWepsFile = new File(userWeps).getCanOrAbsFile();
                About.setUserWepsRoot(userWepsFile);
            }

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


            mainConfig = Util.parse(mainConfig);
            File mainConfigFile = new File(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.




            File logConfigFile = new File(logConfig).getCanOrAbsFile();

            About.setLogConfig(logConfigFile);

            File logFile = new File(log);

            //add the current time to the log file, this allows for a log per instance
            File logDir = (File) 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 File(logDir, logName);



            if (logConfigFile.exists()) {
                try {
                    Properties logProps = new Properties();
                    InputStream in = new FileInputStream(logConfigFile);
                    logProps.load(in);
                    logProps.setProperty("log4j.appender.file.File", logFile.getAbsolutePath());
                    PropertyConfigurator.configure(logProps);
                    logger.info("Configuring logger.");
                } catch (Exception ex) {
                    //error loading the cfg
                    configureDefaultLoggers(logFile, ex);
                }
            } else {
                //the log cfg file does not exist
                configureDefaultLoggers(logFile, null);
            }
            logger.info("WEPS application starting.");
            logger.info("Log Config: " + logConfigFile.getAbsolutePath());
            logger.info("Log File: " + logFile.getAbsolutePath());
            logger.info("Product Version: " + Application.WEPS.getName() + " " + About.getVersion());
            logger.info("Product Release: " + About.getBuildRelease());
            logger.info("Build : " + About.getBuildNumber());
            logger.info("Build Date: " + (About.getBuildDate() != null ? About.getBuildDate().toString() : ""));
            logger.info("Build Revsion: " + About.getBuildRevision() );
            logger.info("Java: " + About.getJava());
            logger.info("User: " + About.getUserName());
            logger.info("Machine: " + About.getHostName() + " (" + About.getHostAddress() + ")");


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


            //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?
                    File previousWepsDir = PreviousVersionResolver.findPreviousSettingsDirectory(new File(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(Exception 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(Exception e){
                logger.error("Unable to import previous settings", e);
            }


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

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

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

            //Locale change.  We only support US
            Locale current = Locale.getDefault();
            boolean changedLocale = false;
            if (current.equals(Locale.US) == false) {
                //Change the locale to US
                Locale.setDefault(Locale.US);
                changedLocale = true;
                logger.warn("Changed locale to US.");
            }

            logger.info("Working Directory: " + System.getProperty("user.dir"));
            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();
                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);
                wp.JP_aux.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();
                //splash.setVisible(false);
                //splash.dispose(); //dispose the splash screen


                wp.dataChanged = false;




                //Locale Message.
                if (changedLocale && wp.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(wp, panel, "System Locale Warning", JOptionPane.WARNING_MESSAGE);
                    if (panel.jcb_displayWarning.isSelected()) {
                        wp.cd.setData(ConfigData.DoNotWarnAboutSystemLocale, "1");
                        wp.cd.save();
                    }
                }

                wp.loadCurrentProject(wp);

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





    ////System.out.println("W_m: " + wp.projectDirectory);

                Util.loadToolTips((Container) wp, new File("cfg", "tooltips.cfg"));
                Util.adjustLabelWidths(wp);

                //wp.winCliMode();

                String myprojFile = new File(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);

                final Weps weps4EDT = wp;
                final boolean showWizard4EDT = showWizard;
                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 = new Thread("File Reference Cecking") {
                                                        @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) {

                                                    @Override
                                                    public int getMaxCharactersPerLineCount() {
                                                        return 80;
                                                    }
                                                };
                                                JDialog waringDialog = warningPane.createDialog("File Reference Error");
                                                waringDialog.setAlwaysOnTop(true);
                                                waringDialog.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) {

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

                                        }
                                    } catch (Exception e) {
                                    }
                                }

                            }
                        };
                        task.start();
                    }
                });
            //wp.setMcrewConfigFile();
            } catch (java.lang.OutOfMemoryError e) {
                JOptionPane.showMessageDialog(wp, "JVM has used all available memory\nPlease restart to reset memory pool",
                        "Out of memory", JOptionPane.ERROR_MESSAGE);
                logger.error("Out of memory.", e);
            } catch (Throwable t) {
                logger.error(t.getMessage(), t);
                //Ensure the application exits with an error condition.
                System.exit(1);
            }

            wp.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); //set the cursor back to default on the main Weps screen
            //        "    User Current working directory:"+System.getProperty("user.dir"));
            //wp.cd.setData(RunFileData.LastRunAttempt, null);

            //Setup thread to watch for deleted management/soil files.
            final Weps wp2 = wp;
            final AuxPanel ap2 = ap;
            wp2.fileWatcher = new Thread("File Watcher") {

                @Override
                public void run() {
                    try {
                        while (wp2 != null) {
                            if (wp2.manFileName != null && wp2.manFileName.length() > 0) {
                                File manFile = new File(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) {
                                File soilFile = new File(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) {
                    }
                }
            };

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

    }
    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){
            File project = new File(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 File(lastRun).getName();
            mostRecentRunName = mostRecentRunName.replace(".wjr", "");
        }
        JTF_mostRecentRun.setText(mostRecentRunName);


    }

    private void selectProjDir() {

        WepsFileChooser wpc = new WepsFileChooser(WepsFileChooser.PROJDIR, ".",
                WepsFileChooser.SELECT);
        wpc.setCurrentDirectory(new File("."));
        //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) == JFileChooser.APPROVE_OPTION) {
            // //System.out.println("Selecting a project directory location");
            try {
                File selProj = new File(wpc.getSelectedFile().getCanonicalPath());
                if (!selProj.isAbsolute()) {
                    selProj = new File(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);
            }
        } else {
            return;
        }

    }//end of selectProjDir()

    private void makeProjDir() {

        java.io.File current = new File(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.PROJDIR, current.getAbsolutePath(),
                WepsFileChooser.CREATE);
        wpc.setCurrentDirectory(new File("."));
        //set the tooltip of "home" button to "Home" instead of "Desktop"
        wpc.homeToolTip(wpc);
        if (wpc.showDialog(this) == JFileChooser.APPROVE_OPTION) {
            // work with the picked item
            JOptionPane.showMessageDialog(this, wpc.getSelectedFile().getAbsolutePath(),
                    "WEPS Project Directory to create", JOptionPane.PLAIN_MESSAGE);
        } else {
            return;
        }
        try {

            File mU = new File(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 File(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;
            }
        }
        File mU = new File(projName);
        if (!mU.isAbsolute()) {
            mU = new File(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) {
        // to do: code goes here.
        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;
            }
        }

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


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

        WepsFileChooser wpc = new WepsFileChooser(WepsFileChooser.PROJECT, projectsPath,WepsFileChooser.CREATE);
        wpc.setCurrentDirectory(new de.schlichtherle.io.File(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) == JFileChooser.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) {
        // to do: code goes here.
        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;
            }
        }

        File projectsFolder = new de.schlichtherle.io.File(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.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 de.schlichtherle.io.File(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;
        }


        ////System.out.println("W_oI_aP: " + projectsPath + " " + new de.schlichtherle.io.File(projectsPath));

        //if (wfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        ////System.out.println("W_oI_aP: " + projectsPath + " " + new de.schlichtherle.io.File(projectsPath));
        if (wfc.showDialog(this) != JFileChooser.APPROVE_OPTION) {
            ////System.out.println("W_oKaP: not approved");
            return;
        }


        File sf = new File(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);

            //ConfigData.getDefault().setData(ConfigData.CurrentProj, projectsDir);
            changes.firePropertyChange(ConfigData.CurrentProj, null, projectsDir);
            changes.firePropertyChange(RunFileData.LastRun, null, "");

            LoadingContext.enter();
            try{
                rfd.initialize();
                File runData=new File(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) {
        // to do: code goes here.
        rfd.writeRunDataXML(projectDirectory);
        dataChanged = false;
    }

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

        wpc.setCurrentDirectory(new de.schlichtherle.io.File(projectsPath));
        if (wpc.showDialog(this) == JFileChooser.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);
        }

    }

    protected void openDatabasesItem_actionPerformed(java.awt.event.ActionEvent evt) {
        try{
            Desktop.getDesktop().open(About.getWepsDatabases());
        }
        catch(Exception 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);
        }
    }
    
    protected void resetProjectItem_ActionPerformed(java.awt.event.ActionEvent evt) {
        int response = JOptionPane.showConfirmDialog(this, "Reset current settings and delete files?\nRun settings will return to defaults.\nManagement and soil files will be deleted.","Reset", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        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
                File dir = new File(projectDirectory);
                for (File file : dir.listFiles(File.getDefaultArchiveDetector())){
                    deleteNonRuns(file);
                }                
                changes.firePropertyChange(ConfigData.CurrentProj, null, projectDirectory);
            }
            finally{
                setCursor(Cursor.getDefaultCursor());
            }
            
        }
        else{
            return;
        }
    }
    
    private void deleteNonRuns(File file){
        if (file.getName().toLowerCase().endsWith(RunFileData.RunSuffix)){
            //is a run, exit
            return;
        }
        
        if (file.isDirectory()){
            //try to delete all the children first
            for (File child : file.listFiles(File.getDefaultArchiveDetector())){
                deleteNonRuns(child);
            }            
        }
        
        if (!file.isDirectory() || file.listFiles().length == 0){
            //only delete if we no longer have any children left.
            boolean deleted = file.delete();
            if (!deleted){
                logger.debug("Unable to delete file: \"" + file.getAbsolutePath() + "\".  Delete will be scheduled for application exit.");
                file.deleteOnExit();
            }
                
        }
        
    }

    @Override
    public void deleteProjectItem_actionPerformed(java.awt.event.ActionEvent event) {
        //to do: code goes here.
        // //System.out.println("The current running project is- projectDirectory value"+projectDirectory);

        WepsFileChooser wfc = null;
        try {
            wfc = new WepsFileChooser(WepsFileChooser.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 de.schlichtherle.io.File((new de.schlichtherle.io.File(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) == JFileChooser.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 File(sf[i]));
                    }
                    break;
                case JOptionPane.NO_OPTION:
                    break;
            }
        } else {
            ////System.out.println("W_oKaP: not approved");
            return;
        }


    }

    @Override
    public void deleteRunItem_actionPerformed(java.awt.event.ActionEvent event) {
        //to do: code goes here.

        WepsFileChooser wfc = null;
        try {
            wfc = new WepsFileChooser(WepsFileChooser.RUNDIR, runsLocationPath,WepsFileChooser.DELETE);
            wfc.setCurrentDirectory(new File(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);
//            wfc.setCurrentDirectory(new de.schlichtherle.io.File((new de.schlichtherle.io.File(projectDirectory)).getAbsolutePath()));
        } 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) == JFileChooser.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;
            }
        } 
    }

    public void deleteRun(java.io.File... files) {

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

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


            boolean deleted = Util.deleteAll(new File(file), lockedFiles);
        }

        if (!lockedFiles.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for(File 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());

    }

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

    @Override
    public void deleteMgmtItem_actionPerformed(java.awt.event.ActionEvent evt) {
        WepsFileChooser wfc = null;
        try {
            wfc = new WepsFileChooser(WepsFileChooser.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 de.schlichtherle.io.File((new de.schlichtherle.io.File(projectDirectory)).getAbsolutePath()));
        } 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) == JFileChooser.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 File(sf[i]));
                    }
                    break;
                case JOptionPane.NO_OPTION:
                    break;
            }
        } else {
            ////System.out.println("W_oKaP: not approved");
            return;
        }


    }

    @Override
    public void deleteSoilItem_actionPerformed(java.awt.event.ActionEvent evt) {
        // TO DO: code goes here:
        WepsFileChooser wfc = null;
        try {
            wfc = new WepsFileChooser(WepsFileChooser.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 de.schlichtherle.io.File((new de.schlichtherle.io.File(projectDirectory)).getAbsolutePath()));
        } 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) == JFileChooser.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 File(sf[i]));
                    }
                    break;
                case JOptionPane.NO_OPTION:
                    break;
            }
        } else {
            ////System.out.println("W_oKaP: not approved");
            return;
        }

    }

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

    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) {
        // to do: code goes here.

        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) {
        //to do:code goes here
        //we do nothing here-but this button is added in the action listener in addHelp()
    }


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

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

    @Override
    public void MICurrentYieldSummary_actionPerformed(java.awt.event.ActionEvent event) {
        // to do: code goes here.
        if (lastRun.length() == 0) {
            JOptionPane.showMessageDialog(this, "No current run available",
                    "Error (W-005)", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (!(new File(lastRun).isAbsolute())) {
            lastRun = (new File(projectDirectory, lastRun)).getAbsolutePath();
        }
        ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_CROP);

    }

    /**
     * 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) {
        // to do: code goes here.
        if (lastRun.length() == 0) {
            JOptionPane.showMessageDialog(this, "No current run available",
                    "Error (W-005)", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (!(new File(lastRun).isAbsolute())) {
            lastRun = (new File(projectDirectory, lastRun)).getAbsolutePath();
        }
        ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_MANAGEMENT);
    }

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

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

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

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

    @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) {
        // to do: code goes here.
        new RunProgram(this, rfd, cd, false);
        //set the title of the window to the new run - neha
        setTitle(new File(projectDirectory).getName());
    }

    @Override
    public void MIMakeCalibrationRun_actionPerformed(java.awt.event.ActionEvent event) {
        // Add your handling code here:
        //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");
    }

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

        WepsFileChooser wpc = new WepsFileChooser(WepsFileChooser.RUN, projectDirectory, WepsFileChooser.SELECT);
        String path = runsLocationPath;
        if (path == null || path.length() <= 0) {
            path = defaultRunsLocationPath;
        }
        File currentDirectory = new de.schlichtherle.io.File(path);
        if(!currentDirectory.exists()){
            JOptionPane.showMessageDialog(this, "Runs location not found:\n" + currentDirectory.getPath(), "Path Warning", JOptionPane.WARNING_MESSAGE);
            currentDirectory = new 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 == JFileChooser.APPROVE_OPTION) {
            restoreRun(new File(wpc.getSelectedFile()));
        }

    }
        

    public void restoreRun(File 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) {
                File warningsFile = new File(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.\nWould 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;
    //                            String warnings="";
                                StringBuffer sb = new StringBuffer();
                                in = new BufferedReader(new FileReader(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 (Exception 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 {

                rfd.readRunFile(runFile.getCanonicalPath());

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

                setTitle(new File(projectDirectory).getName());            
                changes.firePropertyChange(WEPS_RUNRESTORED, null, runFile.getCanonicalPath());
            } catch (Exception 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);

    }

    /**
     * Sneding 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
     * relaated 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")));
                //URI uri = new URI("mailto",ConfigData.getDefault().getData(ConfigData.CommentAddr), null, "subject=WEPS Comments/Questions", null);                
                
                Desktop.getDesktop().mail(uri);
                
                
            }
            else{                
                Email.comment("WEPS Comments/Questions", null, null);
            }
            
            
        } catch (java.lang.Exception e) {
            logger.error("Unable to open email.", e);
        }
    }

    @Override
    public void MIHelpTopics_actionPerformed(java.awt.event.ActionEvent event) {
        //to do: code goes here.
        //		try {
//			// NotImplemented Create and show the NotImplemented
//			(new NotImplemented("Help Topics")).setVisible(true);
//		} catch (java.lang.Exception e) {
//		}
    }

    private ConfigPanel c_configPanel;
    @Override
    public void MIEditConfig_actionPerformed(java.awt.event.ActionEvent event) {
        // to do: code goes here.
        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 {
            //cp.setVisible(true);
            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) {
        }

    }

    @Override
    public void windowGainedFocus_actionPerformed(java.awt.event.WindowEvent evt) {
        // TODO add your handling code here:
        //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_b 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.
     */
    /**
     * void openButton_actionPerformed(java.awt.event.ActionEvent event)
     * {
     * super.openButton_actionPerformed(event);
     * }
     *
     * void saveButton_actionPerformed(java.awt.event.ActionEvent event)
     * {
     * super.saveButton_actionPerformed(event);
     * }
     *
     * void aboutButton_actionPerformed(java.awt.event.ActionEvent event)
     * {
     * //		super.aboutButton_actionPerformed(event);
     * aboutButton_actionPerformed_Interaction1(event);
     * }
     *
     * void aboutButton_actionPerformed_Interaction1(java.awt.event.ActionEvent event)
     * {
     * try {
     * // MI_aboutItem Click the JMenuItem
     * //MI_aboutItem.doClick();
     * MI_helpTopics.doClick();
     * } catch (java.lang.Exception e) {
     * }
     * }
     *
     * void newButton_actionPerformed(java.awt.event.ActionEvent event)
     * {
     * super.newButton_actionPerformed(event);
     * }
     *
     * void runButton_actionPerformed(java.awt.event.ActionEvent event)
     * {
     * super.runButton_actionPerformed(event);
     * }
     *
     * void loadrunButton_actionPerformed(java.awt.event.ActionEvent event)
     * {
     * super.loadrunButton_actionPerformed(event);
     * }
     *
     * void emailButton_actionPerformed(java.awt.event.ActionEvent event)
     * {
     * //super.emailButton_actionPerformed(event);
     * try {
     * MI_sendEmail.doClick();
     * //OR// (new Email("Send Email to WEPS Support", cd)).setVisible(true);
     * } catch (java.lang.Exception e) {
     * }
     * }  */
    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);
    }

    public File getRunsLocation(){
        if(runsLocationPath != null){
            return new File(runsLocationPath);
        }
        else{
            String path = ConfigData.getDefault().getDataParsed(ConfigData.DefaultRunsLocation);
            if(path != null){
                return new File(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.
     */
    public void propertyChange(PropertyChangeEvent e) {
        if (e.getPropertyName().equals(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);
                
            }
        } else if (e.getPropertyName().equals(RunFileData.DataChanged)) {
            String val = (String) e.getNewValue();
            if (val.equals("fireall")) {
                fireallFlg = !fireallFlg;
            }
            if (fireallFlg) {
                return;
            }
            if (val.equals(RunFileData.DataChanged)) {
                dataChanged = true;
            } else {
                dataChanged = false;
            }
        } else if (e.getPropertyName().equals(ConfigData.CurrentProj)) {
            projectDirectory = e.getNewValue().toString();
            projectDirectory = Util.parse(projectDirectory);
            if (runsLocationPath.equals("")) {
                setRunLocationText(ConfigData.getDefault().getData(ConfigData.DefaultRunsLocation));
            } else {
                setRunLocationText(new File(runsLocationPath).getAbsolutePath());
            }
            updateTitle();
        } else if (e.getPropertyName().equals(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);
            }
        } else if (e.getPropertyName().equals(RunFileData.LastRun)) {
            lastRun = ((String) e.getNewValue());
            updateTitle();
        } else if (e.getPropertyName().equals(ConfigData.ProjDir)) {
            projectsPath = ((String) e.getNewValue());            
            projectsPath = Util.parse(projectsPath);
        } else if (e.getPropertyName().equals(ConfigData.Units)) {
            measurementUnits = ((String) e.getNewValue());
        } else if (e.getPropertyName().equals(RunFileData.ClimateFile)) {
            cliGenFile = ((String) e.getNewValue());
        } else if (e.getPropertyName().equals(RunFileData.WindFile)) {
            winGenFile = ((String) e.getNewValue());
        } else if (e.getPropertyName().equals(ConfigData.MantisPassword)) {
            mantisPassword = e.getNewValue().toString();
        } else if (e.getPropertyName().equals(ConfigData.MantisUser)) {
            mantisUser = e.getNewValue().toString();
        } else if (e.getPropertyName().equals(ConfigData.MantisURL)) {
            mantisURL = e.getNewValue().toString();
        } else if (e.getPropertyName().equals(ConfigData.MantisEmail)) {
            mantisEmail = e.getNewValue().toString();
        } else if (e.getPropertyName().equals(ConfigData.MantisProject)) {
            mantisProject = e.getNewValue().toString();
        } else if (e.getPropertyName().equals(ConfigData.TTInit)) {
            setTTTime((String) e.getNewValue(), 1);
        } else if (e.getPropertyName().equals(ConfigData.TTDismiss)) {
            setTTTime((String) e.getNewValue(), 2);
        } else if (e.getPropertyName().equals(RunFileData.WinGenStation)) {
            windGenStation = ((String) e.getNewValue());
        } else if (e.getPropertyName().equals(ConfigData.WinCmd)) {
            windGenCmdArgs = ((String) e.getNewValue());
        } else if (e.getPropertyName().equals(RunFileData.ManageFile)) {
            setManageFileName(e);
        } else if (e.getPropertyName().equals(RunFileData.SoilFile)) {
            setSoilFile(e);
        } else if (e.getPropertyName().equals(RunFileData.RunsLocation)) {            
            if (e.getNewValue().toString().equals("NULL")) {
                runsLocationPath = ConfigData.getDefault().getData(ConfigData.DefaultRunsLocation);
            } else {
                runsLocationPath = e.getNewValue().toString();
            }
                
            setRunLocationText(runsLocationPath);            
            
        } else if (e.getPropertyName().equals(ConfigData.DefaultRunsLocation)) {
            defaultRunsLocationPath = e.getNewValue().toString();
        } else if (e.getPropertyName().equals(ConfigData.DoNotReviewWarningsWhenRestoringRun)) {
            reviewWarnings = e.getNewValue().toString().equals("0");
        } //Forward some from the runprogram class
        else if (e.getPropertyName().equals(Weps.WEPS_RUNCREATED)) {
            changes.firePropertyChange(e);
        } else if (e.getPropertyName().equals(ConfigData.DoNotWarnAboutSystemLocale)) {
            String value = e.getNewValue().toString();
            if (value.equals("1")) {
                warnAboutLocale = false;
            } else {
                warnAboutLocale = true;
            }
        } else if (e.getPropertyName().equals(ConfigData.DoNotEstimateMissingSurgoValues)) {
            if (e.getNewValue().equals("0")) {
                NASIS.setEstimateNullValues(true);
            } else {
                NASIS.setEstimateNullValues(false);
            }
        } else if (e.getPropertyName().equals(ConfigData.OMFractionThreshold)) {
            try {
                NASIS.setOmFractionThreshold(Double.parseDouble(e.getNewValue().toString()));
            } catch (Exception ex) {
            }
        }


    }

    /**
     * Listens for properties and actions from different applications in weps.
     */
    private void setSoilFile(PropertyChangeEvent e) {
        soilFileName = (String) e.getNewValue();
        File sf = new File(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());                                   
        File pd = new File(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 File(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();
        File mf = new File(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());                                   
        File pd = new File(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 File(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(File parent, File 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 File(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);
                return;
            } else if (Help.loadDirectory(masterDir)) {
                logger.debug("Loaded " + masterDir);
                return;
            } else if (Help.loadJar(wepsJar)) {
                logger.debug("Loaded " + wepsJar);
                return;
            } else if (Help.loadDirectory(wepsDir1)) {
                logger.debug("Loaded " + wepsDir1);
                return;
            } else if (Help.loadDirectory(wepsDir2)) {
                logger.debug("Loaded " + wepsDir2);
                return;
            }
        }
        finally{
            logger.debug("Done loading help.");
        }
    }

    private void addCSH(HelpSet hs) {
        logger.debug("Adding context sensitive help...");
        hb = hs.createHelpBroker();
        //hb = hs.getHelpBroker();
        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, "tbRun_html");
        CSH.setHelpIDString(loadrunButton, "tbLoadRun_html");
        CSH.setHelpIDString(emailButton, "tbEmail_html");
        //   CSH.setHelpIDString(aboutButton, "tbHelp_html");
        CSH.setHelpIDString(helpButton, "tbPopupHelp_html");
        CSH.setHelpIDString(MB_main, "menubarPanel_html");
        CSH.setHelpIDString(M_project, "mnuProject_html");
        CSH.setHelpIDString(M_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");
        //for the tool bar of Weps screen
        CSH.setHelpIDString(JTB_main, "toolbarPanel_html");
        CSH.setHelpIDString(JTB_main, "toolbarPanel_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 File projFile = new File("cfg", "lastproj.txt");
        private File 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);
            File projDir = new File(projectsPath);
            if (!projDir.isDirectory()) {
                return;
            }
            java.io.File[] projNames = projDir.listFiles(new FilenameFilter() {

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

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

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

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

        /**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:
                    File f = new File(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) {
                File dir = new File(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 FileReader(projFile));
                    String temp = in.readLine();

                    if (temp != null) {
                        File tmpFile = new File(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 (Exception 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) {
                File dir = new File(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 File(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 File(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){
                File projDir = new File(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
                PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(projFile)));
                out.println(wp.projectDirectory);
                out.close();
            } catch (IOException e) {
                //System.err.println("LCP_r: " + e);
            }
        }
    }

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

    @Override
    protected void JB_DR_actionPerformed(java.awt.event.ActionEvent evt) {        
        ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_DETAIL);
    }

    @Override
    protected void JB_CR_actionPerformed(java.awt.event.ActionEvent evt) {
        ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_CROP);        
    }

    @Override
    protected void JB_MR_actionPerformed(java.awt.event.ActionEvent evt) {
        ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_MANAGEMENT);        
    }

    @Override
    protected void JB_RR_actionPerformed(java.awt.event.ActionEvent evt) {
        ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_RUN);
    }
    
    protected void JB_SR_actionPerformed(java.awt.event.ActionEvent evt) {
        ReportManager.getDefault().displayReport(lastRun, ReportManager.REPORT_STIR);
    }

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

        if (runsLocationPath != null && runsLocationPath.length() > 0) {
            wfc.setSelectedFile(new File(runsLocationPath));
        } else if (defaultRunsLocationPath != null && defaultRunsLocationPath.length() > 0) {
            wfc.setSelectedFile(new File(defaultRunsLocationPath));
        } else {
            wfc.setCurrentDirectory(new File(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);            
        }
    }

    @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);
//
//    }
    @Override
    protected void MI_userGuideActionPerformed(java.awt.event.ActionEvent evt) {
        File guidef = new File("readme/WEPSUserGuide.pdf");
        try {
            java.awt.Desktop.getDesktop().open(guidef);
        } catch (Exception ex) {
            try {
                javax.swing.JOptionPane.showMessageDialog(this, guidef.getCanonicalPath() + " not found",
                        "WEPS User Guide not found", javax.swing.JOptionPane.ERROR_MESSAGE);
            } catch (HeadlessException he) {
                ex.printStackTrace();
            } catch (IOException ioe) {
                ex.printStackTrace();
            }
        }
    }
    
    String mantisURL;
    String mantisUser;
    String mantisPassword;
    String mantisEmail;
    String mantisProject;
            
    @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);

    }

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

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