/*
 * MCREWWindow.java
 *
 * Created on February 11, 2004, 11:35 AM
 */
package usda.weru.mcrew;

import de.schlichtherle.truezip.file.TFile;
import de.schlichtherle.truezip.file.TVFS;
import de.schlichtherle.truezip.file.swing.TFileChooser;
import de.schlichtherle.truezip.fs.FsSyncException;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.EventQueue;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.help.CSH;
import javax.help.HelpBroker;
import javax.help.HelpSet;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JToggleButton;
import org.apache.commons.io.FileUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openide.util.Exceptions;
import usda.weru.mcrew.SkelManConverter.XMLSkelFilter;
import usda.weru.mcrew.gui.MCREWWindow_n;
import usda.weru.mcrew.timeline.ComboTimeline;
import usda.weru.mcrew.timeline.TimelineControls;
import usda.weru.mcrew.timeline.TimelinePanel;
import usda.weru.remoteDataAccess.csip.CsipLmodUtil;
import usda.weru.remoteDataAccess.csip.CsipLmodUtil.lmodType;
import usda.weru.remoteDataAccess.remoteFiles.inetFile.CrLmodFile;
import usda.weru.resources.Resources;
import usda.weru.util.About;
import usda.weru.util.AboutDialog;
import usda.weru.util.ConfigData;
import usda.weru.util.Help;
import usda.weru.util.Util;
import usda.weru.util.wepsFileChooser2.WepsFileChooser2;
import usda.weru.util.wepsFileChooser2.WepsFileTypes2;
import usda.weru.weps.Weps;

/**
 * This class will be responsible for containing both the table objects and the
 * timeline objects, and interfacing between the two.
 * @author  jonathanhornbaker
 */
public class MCREWWindow extends MCREWWindow_n {
    
    private static final Logger LOGGER = LogManager.getLogger(MCREWWindow.class);
    TablePanel tableObject;
    TimelinePanel timelineObject;
    ComboTimeline timelineStoragePanel;
    public static final long serialVersionUID = 23789423789L;
    private boolean standaloneFlg = false;
    private List<String> c_guiViews;
    /**
     * The HelpBroker is the default presentation of a HelpSet. A HelpBroker is an abstraction of
     * the presentation for a HelpSet; a straight-forward implementation is a JHelp() on the
     * HelpSet. A HelpBroker can be asked to show a given Navigational View, and can display a given
     * ID (help topic).
     */
    public HelpBroker hb_mcrew;
    static {
        openMcrewWindows = new ArrayList<>();
    }
    static List<MCREWWindow> openMcrewWindows;
    /**
     * Absolute Project directory path
     */
    private String projectDir = null;
    private ConfigData cd;
    private int dataChanged;
    
     /**
     * Side offsets used when the MCREW frame is resized and other components sitting in the
     * container are to be automatically resized to make the application look evenly spaced in with
     * reference the edges.
     */
    public static final int sideOffSet = 10;
    /**
     * Component offset is used when the MCREW frame is resized and other components sitting in the
     * container are to be automatically resized and spaced for uniformity with respect to the
     * adjecent components in the container.
     */
    public static final int componentOffSet = 5;
    /**
     * Minimum Width of the main MCREW screen. Cannot reduce the scrren width below this width even
     * if done manually.
     */
    public static final int MIN_WIDTH = 875;
    /**
     * Minimum Height of the main MCREW screen. Cannot reduce the scrren height below this height
     * even if done manually.
     */
    public static final int MIN_HEIGHT = 575;
    //the table view of the data ...this is where everything happens
    private String columnConfig = "My Config Frame";
    /**
     * This shows the column config frame
     */
    private ConfigFrame configFrame = new ConfigFrame(columnConfig);//NEEDS HANDLING
    // Used by addNotify
    boolean frameSizeAdjusted = false;
    public static final String MCR = "MCREW-";
    public static final String WINDOW_OPEN = MCR + "WindowOpen";
    public static final String FILE_NAME = MCR + "FileName";
    public static final String WINDOW_CLOSING = MCR + "WindowClosing";
    
    private SkelManConverter sMC;
    
    /**
     * Most basic constructor.Not guaranteed to be Accurate.
     * @param files
     */
    public MCREWWindow(String[] files) {
        this("MCREW Timeline Version 1.0", ConfigData.getDefault().getData(ConfigData.ProjDir), files, ConfigData.getDefault());
    }

    /**
     * Common constructor for MCREW.Gives a title, sets project directory, etc.
     * @param title
     * @param projectDirectory
     * @param files
     * @param conDat
     */
    public MCREWWindow(String title, String projectDirectory, String[] files, ConfigData conDat) {
        super();
        projectDir = projectDirectory;
        cd = conDat;
        this.setTitle(title);
        System.setProperty("line.separator", "\n");
        MCREWConfig.initialize(cd);
        JTB_autoSort.setSelected(MCREWConfig.autosort);
        c_guiViews = new ArrayList<>();

        timelineObject = new TimelinePanel(files, this);
        TimelineControls controls = new TimelineControls(timelineObject);
        timelineObject.linkControls(controls);
        
        tableObject = timelineObject.getTablePanel(0);
        if (tableObject == null) {
            this.dispose();
            return;
        }

        if (files == null || files[0].equals(projectDirectory + "/") || (files.length == 1 && files[0].trim().equals(""))) {
            tableObject.setDataChanged(false);
            this.newOverwrite();
            tableObject.savePath = projectDirectory;
        }
        
        timelineStoragePanel = new ComboTimeline(timelineObject, controls);
        timelineContainer.add(timelineStoragePanel);
        javax.swing.GroupLayout timePanelLayout = new javax.swing.GroupLayout(timelineContainer);
        timelineContainer.setLayout(timePanelLayout);
        timePanelLayout.setHorizontalGroup(
                timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(timelineStoragePanel).addGap(10, 10, Short.MAX_VALUE)
        );
        timePanelLayout.setVerticalGroup(
                timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(timelineStoragePanel).addGap(10, 10, Short.MAX_VALUE)
        );
        
        timelineStoragePanel.setVisible(true);

        tableContainer.add(tableObject);
        javax.swing.GroupLayout tabelPanelLayout = new javax.swing.GroupLayout(tableContainer);
        tableContainer.setLayout(tabelPanelLayout);

        tabelPanelLayout.setHorizontalGroup(
                tabelPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addComponent(tableObject).addGap(10, 10, Short.MAX_VALUE)
        );
        tabelPanelLayout.setVerticalGroup(
                tabelPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addComponent(tableObject).addGap(10, 10, Short.MAX_VALUE)
        );
        
        tableObject.setLocation(10, 10);
        tableObject.addToMain(tableObject.table);
        tableObject.setVisible(true);
        tableObject.table.focusTable();
        this.setVisible(true);
        this.addHelp();
        this.setupViews();
        this.setSize(tableObject.table.getWidth() + 70, 575);
        
        DefaultViewJMI_actionPerformed(new ActionEvent(this, 0, ""));
        
        if (ConfigData.isSingleFileMode()) {
            singleFileMode();
        }
        if (conDat.getData(ConfigData.McrewEdit).trim().equals("0")) {
            disableOpens();
        }

        Util.loadToolTips((Container) this, new TFile("mcrew_cfg", "mcrewtooltips.cfg"));
        openMcrewWindows.add(this);
        tableObject.setDataChanged(false);
    }
    
    /**
     * Brings the currently selected table panel to the forefront (i.e. makes it visible)
     */
    public void refocus() {
        refocus(timelineObject.getSelectedIndex());
    }

    /**
     * Brings the table at the specified index in the timeline to the forefront.
     */
    public void refocus(int index)
    {
        tableContainer.remove(tableObject);
        TablePanel mp = timelineObject.getTablePanel(index);
        tableContainer.add(mp);
        javax.swing.GroupLayout tabelPanelLayout = new javax.swing.GroupLayout(tableContainer);
        tableContainer.setLayout(tabelPanelLayout);
        tabelPanelLayout.setHorizontalGroup(
            tabelPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mp).addGap(10, 10, Short.MAX_VALUE)
        );
        tabelPanelLayout.setVerticalGroup(
            tabelPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mp).addGap(10, 10, Short.MAX_VALUE)
        );
        mp.setLocation(10, 10);
        mp.addToMain(mp.table);
        mp.setVisible(true);
        tableObject = mp;
        tableObject.table.focusTable();
    }
    
    public static boolean isOpen() {
        return MCREWWindow.openMcrewWindows.size() > 0;
    }
    
    public String getProjectPath() {
        return projectDir;
    }
    
    public ConfigData getCD() {
        return cd;
    }
    
    /**
     * This is some legacy functionality.  When the enabled full MCREW editing functionality
     * is off, we need to disable opens that touch the project directory.  Don't know why.
     */
    public void disableOpens()
    {
        JMI_open.setEnabled(false);
        JMI_addOpen.setEnabled(false);
        JMI_overOpen.setEnabled(false);
        tableObject.JB_open.setEnabled(false);
    }

      
    /**
     * Transforms a table in WEPS Rotation View into Crop Interval View.
     */
    @Override
    protected void JMI_RtI_ActionPerformed(java.awt.event.ActionEvent evt)
    {
        if(tableObject.rotToIntSort())
        {
            JMI_RotSort.setEnabled(tableObject.table.getData().intView());
            JMI_IntSort.setEnabled(!tableObject.table.getData().intView());
            JMI_cycleBwd.setEnabled(false);
            JMI_cycleFwd.setEnabled(false);
            tableObject.changeTableLabel(TablePanel.intMode);
        }
    }
    
    /**
     * Transforms a table in Crop Interval View to WEPS Rotation View.
     */
    @Override
    protected void JMI_ItR_ActionPerformed(java.awt.event.ActionEvent evt)
    {
        try { tableObject.intToRotSort(); }
        catch(Exception ex)
        {
            String val = ex.getMessage();
            int newRotYears;
            try { newRotYears = Integer.parseInt(val); }
            catch(NumberFormatException nfe) { newRotYears = tableObject.table.getData().kRotationYears + 1; }
            if(JOptionPane.showConfirmDialog(null, "Number of years in rotation greater than"
                    + "\nNumber of years specified.  Do you wish to set the number of rotation\n"
                    + "years to " + newRotYears + "?",
                    "Invalid Date", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
            {
                tableObject.table.getData().setRotationYears(newRotYears);
                JMI_ItR_ActionPerformed(evt);
                return;
            }
            else return;
        }
        JMI_RotSort.setEnabled(tableObject.table.getData().intView());
        JMI_IntSort.setEnabled(!tableObject.table.getData().intView());
        JMI_cycleBwd.setEnabled(true);
        JMI_cycleFwd.setEnabled(true);
        tableObject.changeTableLabel(TablePanel.rotMode);
    }

    /**
     * This method notifies when the window or frame is resized and the components need to be
     * re-arranged so they are evenly spaced relative to each other.
     */
    @Override
    public void addNotify() {
        //Dimension size = getSize();
        super.addNotify();

        if (frameSizeAdjusted) {
            return;
        }
        frameSizeAdjusted = true;

    }

    /**
     * Prints the table.
     */
    @Override
    public void PrintJMI_actionPerformed(java.awt.event.ActionEvent event) {
       tableObject.doPrint();
    }

    /**
     * This method is called when the exit option is selected
     */
    @Override
    @SuppressWarnings("fallthrough")
    public void ExitJMI_actionPerformed(java.awt.event.ActionEvent event) {
        tableObject.commitEdit();

        int option = -1;
        boolean closeWindow = false;
        
        Object[] options = {"Yes", "No", "View Each", "Cancel"};
        
        if(ConfigData.isSingleFileMode() && (dataChanged > 0) )
        {
            option = JOptionPane.showConfirmDialog(this, "Save current Management File ? ");
            switch (option) 
            {
                case JOptionPane.YES_OPTION:
                    saveAll();
                    closeWindow = true;
                    break;
                case JOptionPane.NO_OPTION:
                    closeWindow = true;
                    break;
                default:
            }
        }
        else if(dataChanged > 0)
        {
            int selection = JOptionPane.showOptionDialog(this, "Save All Modified "
                + "Management Files?", "Save All?", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, 
                null, options, options[3]);
            switch(selection)
            {
                case 0:
                    saveAll();
                    closeWindow = true;
                case 1: /*FALLTHROUGH*/
                    closeWindow = true;
                    break;
                case 2:
                    closeWindow = checkandSaveAll();
                    break;
                default:
            }
        }
        else closeWindow = true;

        if (closeWindow) {
            closeMcrew();
        }
    }
    public void closeMcrew(){
        tableObject.firePropertyChange(WINDOW_CLOSING, null, "true");
        clearAndDispose();
        openMcrewWindows.remove(this);
        for (int index = 0; index < timelineObject.getNumFiles(); index++) {
            TablePanel tempTable = timelineObject.getTablePanelNoSelect(index);
            tempTable.table.setKillFlag(true);
        }
        this.setVisible(false);
        this.dispose();
        if (standaloneFlg) {
            System.exit(0);
        }
    }

    /**
     * Opens the MCREW Configuration window.
     */
    @Override
    public void ConfigurationJMI_actionPerformed(java.awt.event.ActionEvent event) {
        // Display Configuration screen
        configFrame.setVisible(true);
    }

    /**
     * Opens the MCREW Configuration window.
     */
    @Override
    public void ColumnOptionsJMI_actionPerformed(java.awt.event.ActionEvent event) {
        // //System.out.println("Setting up Column Configuration panel " );
        configFrame.setVisible(true);
    }

    @Override
    public void HelpJMI_actionPerformed(java.awt.event.ActionEvent event) {
        // implement it
    }

    /**
     * Loads the about dialogue.  
     */
    @Override
    public void AboutJMI_actionPerformed(java.awt.event.ActionEvent event) {
        try {
            // JAboutDialog Create with owner and show as modal
            AboutDialog JAboutDialog1 = new AboutDialog(this, usda.weru.util.Application.MCREW);
            JAboutDialog1.setModal(true);
            JAboutDialog1.setVisible(true);
        } catch (Exception e) {
        }
    }

    /**
     * This function updates WEPS Management individual files -added by Neha
     */
    @Override
    public void UpdateFilesJMI_actionPerformed(java.awt.event.ActionEvent evt) {
        try {
            // Step 1: Prompt for the .man files that need to be updated
            String m_fileName = "";
            WepsFileChooser2 fileChooser = WepsFileChooser2.create(WepsFileChooser2.Action.Select, null, false, true, null,
                    WepsFileTypes2.Management, WepsFileTypes2.Rotation);
            fileChooser.setFileSelectionMode(WepsFileChooser2.SelectionType.FILES_ONLY);
            fileChooser.setMultiSelectionEnabled(true);
            fileChooser.setAcceptAllFileFilterUsed(false);
            fileChooser.enableFolderButtons();
            fileChooser.setIsUpdatingManFileChooser(true);
            fileChooser.setDialogTitle("Select WEPS management files that are to be updated");
            fileChooser.enableDbButton(false);
            fileChooser.enableCfgDefLocButton(false);
            fileChooser.enableInPlaceCheckBox(true);
            fileChooser.setFileFilter(WepsFileTypes2.Management.getFileFilter());
//            String dir = MCREWConfig.getDirectoryName(XMLConstants.smanagement_template);
            String sourceFolder = "";
            String dir = projectDir;
            fileChooser.setCurrentDirectory(dir);
            fileChooser.setDefaultDirectory(new TFile(Util.parse(dir)));
            java.io.File[] sourceFiles = null;
            int returnVal = fileChooser.showDialog(this);
            if (returnVal == WepsFileChooser2.APPROVE_OPTION) {
                sourceFiles = fileChooser.getSelectedFiles();
                sourceFolder = fileChooser.getSelectedFile().getParent();
            } else {
                return;
            }
            
            // This is where we choose the destination if the update is not happening
            // in place. 
//            java.io.File[]
                    String destFolder = null;
                    String tempDest = null;
            if(!fileChooser.isInPlace()){
                WepsFileChooser2 fileChooser2 = new WepsFileChooser2(WepsFileTypes2.Dir, "", WepsFileChooser2.Action.Select);// WepsFileChooser2.create(WepsFileChooser2.Action.Select, null, false, true, null,
//                WepsFileTypes2.Management, WepsFileTypes2.Rotation);
//                fileChooser2.setFileSelectionMode(WepsFileChooser2.SelectionType.DIRECTORIES_ONLY);
//                fileChooser2.setMultiSelectionEnabled(true);
//                fileChooser2.setAcceptAllFileFilterUsed(false);
                fileChooser2.setTitleText("Folder Location");
                fileChooser2.enableFolderButtons();
                fileChooser2.setDialogTitle("Select Location for WEPS management files to go");
                fileChooser2.enableDbButton(false);
                fileChooser2.enableCfgDefLocButton(false);
                fileChooser2.enableInPlaceCheckBox(true);
                fileChooser2.setFileFolderText(WepsFileChooser2.ApproveText.FOLDER);

//                dir = MCREWConfig.getDirectoryName(XMLConstants.smanagement_template);
                dir = projectDir;

                fileChooser2.setCurrentDirectory(dir);
                fileChooser2.setDefaultDirectory(new TFile(Util.parse(dir)));
                
                returnVal = fileChooser2.showDialog(this);
                if (returnVal == WepsFileChooser2.APPROVE_OPTION) {
                    if(fileChooser2.getSelectedFiles().length<1){
//                        System.out.println("herestart");
                        destFolder = fileChooser2.getStartDirectory();
                    }else{
                        if(fileChooser2.getSelectedFiles()[0].isFile()){
//                            System.out.println("hereselected");
                            destFolder = fileChooser2.getSelectedFiles()[0].getParent() + File.separator;
                        }else{
//                            System.out.println("herenotfile" + Arrays.toString(fileChooser2.getSelectedFiles())+ "  " + fileChooser2.getSelectedFile().getParent());
                            if(!fileChooser2.getSelectedFiles()[0].getParent().equals(fileChooser2.getSelectedFile())){
                                destFolder = fileChooser2.getSelectedFile() + File.separator;
                            }else{
                                destFolder = fileChooser2.getSelectedFiles()[0].getAbsolutePath() + File.separator;
                            }
                        }
                    }
                    
//                    destFolder = fileChooser2.getSelectedFiles()[0].getAbsolutePath();
//                    System.out.println("heredestfolder: " + destFolder);
                } else {
                    return;
                }
                
                tempDest = destFolder;
            }

            if(destFolder==null){
                tempDest = sourceFolder;
            }
//            else{
//                tempDest = sourceFolder;
//            }
            if ( JOptionPane.showConfirmDialog(this, "This will update all WEPS management files "
        	+ "selected from this source directory with current information from CRLMOD operation and crop/residue records.\n\n"
                + "  Source: " + sourceFolder + "\n\n"
                + "The updated contents from the source folder will be placed within this destination folder:\n\n"
                + "  Destination: " + tempDest + "\n\n"
                + "If the \"Recursive\" option is set, all mgt files residing within subfolders of the source folder will also be updated.\n"
                + "If the \"In Place\" option is set, the destination folder will match the source folder.\n"
		+ "For \"not In Place\" scenarios, the source folder name must be created and selected as the destination, if so desired.\n"
		+ "(The source folder name is not automatically appended to the destination folder location)\n\n"
                + "Do you want to update the WEPS management files now?",
                "Update WEPS Management Files:",
                JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
            return;
        }
            //Check if all the files selected are management files and put them in a vector
            boolean doUpdate = true;
            List<String> manFiles = new ArrayList<String>();
            for (int i = 0; sourceFiles != null && i < sourceFiles.length; i++) {
                try {
                    m_fileName = sourceFiles[i].getCanonicalPath();
                    doUpdate = WepsFileTypes2.Management.getFileFilter().accept(sourceFiles[i]) || WepsFileTypes2.Rotation.getFileFilter().accept(sourceFiles[i]);
                    if (doUpdate == false) {
                        JOptionPane.showMessageDialog(this, m_fileName
                                + "\n\nSelection is not a WEPS management or rotation file.\n\nNo Files Updated.",
                                "WEPS Information", JOptionPane.ERROR_MESSAGE);
                    }
                    manFiles.add(m_fileName);
                } catch (HeadlessException | IOException e) {
                    System.out.println("Error: " + e);
                }
            }

            if (doUpdate == false) {
                return;
            }

            TFile fs = new TFile(MCREWConfig.getDirectoryName(XMLConstants.smanagement_skeleton));
            if ((!fs.exists()) || (!fs.isDirectory())) {
                JOptionPane.showMessageDialog(this, "Skeleton directory is not valid: \n\n"
                        + MCREWConfig.getDirectoryName(XMLConstants.smanagement_skeleton),
                        "Error", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            //Give the doUpdate() function the vector containing the names of the man files to be updated.
            XMLManagementUpdater updateMan = new XMLManagementUpdater();
            updateMan.isIndv = true;
//            System.out.println("here1: " + destFolder + " " + sourceFolder+File.separator + " " + destFolder.equals(sourceFolder+File.separator));
            if(!fileChooser.isInPlace() && !destFolder.equals(sourceFolder+File.separator)){
                updateMan.doUpdateWaitInPlace(this, manFiles, destFolder.toString());
            }else{
                updateMan.doUpdate(this, manFiles);
            }
//            
            
            
            TVFS.umount();
        } catch (FsSyncException ex) {
            LOGGER.log(Level.ERROR, ex.getMessage());
        }
    }
    
    /**
     * Prints out the selected file in the 1.5 management file format.
     */
    @Override
    public void BackConvertSingleJMI_actionPerformed(ActionEvent evt)
    {
        TFile sourceFile = null;
        TFile destinationDirectory = null;
        
        WepsFileChooser2 fileChooser = new WepsFileChooser2(WepsFileTypes2.Dir, "", WepsFileChooser2.Action.Select);
        fileChooser.setFileSelectionMode(WepsFileChooser2.SelectionType.FILES_ONLY);
        fileChooser.setMultiSelectionEnabled(false);
        fileChooser.setDialogTitle("Select a directory where all WEPS management files will be updated");
        fileChooser.setTitleText("Select folder containing WEPS mgt files for updating");
        fileChooser.setAcceptAllFileFilterUsed(false);

//        dir = MCREWConfig.getDirectoryName(XMLConstants.smanagement_template);
        String dir = projectDir;
        fileChooser.setCurrentDirectory(dir);
        fileChooser.setDefaultDirectory(new TFile(dir));
        fileChooser.enableFolderButtons();
        fileChooser.setFileFilter(WepsFileTypes2.Management.getFileFilter());
        fileChooser.enableDbButton(false);
        fileChooser.enableRecCheckbox(false);
        fileChooser.enableCfgDefLocButton(false);
        fileChooser.enableInPlaceCheckBox(true);
        
        int returnVal = fileChooser.showDialog(this);
        
        /**
         * 
         * "here" to be deleted on cleanup!!!!!!
        WepsFileChooser2 fileChooser = new WepsFileChooser2(WepsFileTypes2.File, "", WepsFileChooser2.Action.Select);
        fileChooser.setFileSelectionMode(WepsFileChooser2.SelectionType.FILES_ONLY);
        fileChooser.setMultiSelectionEnabled(false);
        fileChooser.enableFolderButtons();
        fileChooser.enableDbButton(false);
        XMLSkelFilter filter = new XMLSkelFilter("man", "WEPS Management Files");
        fileChooser.setFileFilter(filter);
        fileChooser.setDialogTitle("Select a WEPS management file");

        fileChooser.setCurrentDirectory(tableObject.savePath);
        fileChooser.enableInPlaceCheckBox(true);
        
        boolean isInPlace = fileChooser.isInPlace();
        int returnVal = fileChooser.showDialog(this);
**/
        if (returnVal == WepsFileChooser2.APPROVE_OPTION) 
        {
            try { sourceFile = new TFile(fileChooser.getSelectedFile()); } 
            catch (Exception e) { System.err.println("Error: " + e); }
        } else {
            return;
        }
        boolean isInPlace = fileChooser.isInPlace();
        if(!isInPlace){
            fileChooser = new WepsFileChooser2(WepsFileTypes2.Dir, "", WepsFileChooser2.Action.Select);
            fileChooser.setFileSelectionMode(WepsFileChooser2.SelectionType.DIRECTORIES_ONLY);
            fileChooser.setMultiSelectionEnabled(false);
            fileChooser.setDialogTitle("Select a destination directory.");
            fileChooser.setAcceptAllFileFilterUsed(false);

            fileChooser.setCurrentDirectory(tableObject.savePath);

            returnVal = fileChooser.showDialog(this);

            if (returnVal == WepsFileChooser2.APPROVE_OPTION) 
            {
                try { destinationDirectory = new TFile(fileChooser.getSelectedFile().getCanonicalPath() + TFile.separator); } 
                catch (Exception e) { System.err.println("Error: " + e); }
            } else {
                return;
            }
        }else{ 
            destinationDirectory = new TFile(sourceFile.getParent()); 
        }
        
    if((sourceFile == null) || (destinationDirectory == null)) return;
        String destPath = destinationDirectory.getAbsolutePath() + TFile.separator + sourceFile.getName();
//        if(sourceFile.getParent().equals(destinationDirectory.getAbsolutePath()))
//        {
//            destPath = destPath.trim().substring(0, destPath.lastIndexOf("."))
//                    + "Ver15.man";
//        }
        
        TFile destFile = new TFile(destPath);
        ManageData temp = new ManageData();
        temp.readDataFile(sourceFile.getAbsolutePath());
        temp.writeOldFile(destFile.getAbsolutePath());
        
        filesReverted(1, sourceFile.getAbsolutePath()); 
    }
            
    /**
     * Prints out a directory of management files in the 1.5 management file format.
     */
    @Override
    public void BackConvertRecursiveJMI_actionPerformed(ActionEvent evt)
    {
        TFile sourceDirectory = null;
        TFile destinationDirectory = null;
        boolean inPlace = false;
        boolean isRec = false;
        {
            WepsFileChooser2 fileChooser = new WepsFileChooser2(WepsFileTypes2.Dir, "", WepsFileChooser2.Action.Select);
            fileChooser.setFileSelectionMode(WepsFileChooser2.SelectionType.DIRECTORIES_ONLY);
            fileChooser.setMultiSelectionEnabled(false);
            fileChooser.setDialogTitle("Select a source directory.");
            fileChooser.setAcceptAllFileFilterUsed(false);
            fileChooser.enableFolderButtons();
            fileChooser.enableDbButton(false);
            fileChooser.setCurrentDirectory(tableObject.savePath);
            fileChooser.enableInPlaceCheckBox(true);
            fileChooser.enableRecCheckbox(true);
            int returnVal = fileChooser.showDialog(this);
            
            if (returnVal == WepsFileChooser2.APPROVE_OPTION) 
            {
                try { sourceDirectory = new TFile(fileChooser.getSelectedFile().getCanonicalPath() + TFile.separator); } 
                catch (Exception e) { System.err.println("Error: " + e); }
            } 
            else return;
            
            inPlace = fileChooser.isInPlace();
            isRec = fileChooser.isRecurive();
        }
        
        if(!inPlace){
            WepsFileChooser2 fileChooser = new WepsFileChooser2(WepsFileTypes2.Dir, "", WepsFileChooser2.Action.Select);
            fileChooser.setFileSelectionMode(WepsFileChooser2.SelectionType.DIRECTORIES_ONLY);
            fileChooser.setMultiSelectionEnabled(false);
            fileChooser.setDialogTitle("Select a destination directory.");
            fileChooser.setAcceptAllFileFilterUsed(false);
            
            fileChooser.setCurrentDirectory(tableObject.savePath);

            int returnVal = fileChooser.showDialog(this);

            if (returnVal == WepsFileChooser2.APPROVE_OPTION) 
            {
                try { destinationDirectory = new TFile(fileChooser.getSelectedFile().getCanonicalPath() + TFile.separator); } 
                catch (Exception e) { System.err.println("Error: " + e); }
            } 
            else return;
        }else{
            destinationDirectory = sourceDirectory;
        }
        if((sourceDirectory == null) || (destinationDirectory == null)) return;
        String extension = ".man";
//        if(sourceDirectory.getAbsolutePath().equals(destinationDirectory.getAbsolutePath()))
//        {
//            extension = "Ver15.man";
//        }
        
        if(isRec){
            convertDirectoryToArchiveRec(sourceDirectory, destinationDirectory, extension);
        }else{
            convertDirectoryToArchiveNonRec(sourceDirectory, destinationDirectory, extension);
        }
    }
    
    /**
     * This method handles the meat and potatoes of converting a directory of management
     * files into the 1.5 management file format.
     */
    public void convertDirectoryToArchiveNonRec(TFile sourceDirectory, TFile destinationDirectory, String newExtension)
    {
        String finalStr = "";
        int finalSize = 0;
        for(TFile sourceFile : sourceDirectory.listFiles())
        {
            if(sourceFile.isDirectory())
            {
//                String newDestPath = destinationDirectory.getAbsolutePath() + 
//                        TFile.separator + sourceFile.getName() + TFile.separator;
//                TFile newDest = new TFile(newDestPath);
//                convertDirectoryToArchive(sourceFile, newDest, newExtension);
            }
            else if(sourceFile.getAbsolutePath().trim().endsWith(".man"))
            {
                String destPath = destinationDirectory.getAbsolutePath() + 
                        TFile.separator + sourceFile.getName();
                destPath = destPath.trim().substring(0, destPath.lastIndexOf("."))
                    + newExtension;
                TFile destFile = new TFile(destPath);
                ManageData temp = new ManageData();
                temp.readDataFile(sourceFile.getAbsolutePath());
                temp.writeOldFile(destFile.getAbsolutePath());
                finalStr+= destFile.getAbsolutePath() +"\n";
                finalSize++;
            }
        }
        filesReverted(finalSize, finalStr);        //popup for finished files
    }
    private ArrayList<TFile> result = new ArrayList<TFile>();
    private void searchFolders(final String pattern, final File folder, List<TFile> result) {
        for (final File f : folder.listFiles()) {

            if (f.isDirectory()) {
                searchFolders(pattern, f, result);
            }

            if (f.isFile()) {
                if (f.getName().matches(pattern)) {
                    result.add(new TFile(f.getAbsolutePath()));
                }
            }

        }
    }
    
    
    /**
     * This method handles the meat and potatoes of converting a directory of management
     * files into the 1.5 management file format.
     */
    public void convertDirectoryToArchiveRec(TFile sourceDirectory, TFile destinationDirectory, String newExtension)
    {
        String finalStr = "";
        int finalSize =0;
        String[] st = {".man"};
        searchFolders(".*\\.man", sourceDirectory, result);

        for(TFile sourceFile : result)
        {
            String sourceName =sourceFile.getName();
            boolean makeDirs = false;
            if(!sourceFile.getParentFile().equals(sourceDirectory)){
                makeDirs = true;
                 sourceName = sourceFile.getAbsolutePath().split(
                         StringEscapeUtils.escapeJava(sourceDirectory.getAbsolutePath()))[1].substring(1);
            }

            if(sourceFile.getAbsolutePath().trim().endsWith(".man")){

                String destPath = destinationDirectory.getAbsolutePath() + 
                        TFile.separator +sourceName;
                destPath = destPath.trim().substring(0, destPath.lastIndexOf("."))
                    + newExtension;
                System.out.println("here" + destPath);
                TFile destFile = new TFile(destPath);
                if(makeDirs){destFile.getParentFile().mkdirs();}
                ManageData temp = new ManageData();
                temp.readDataFile(sourceFile.getAbsolutePath());
                temp.writeOldFile(destFile.getAbsolutePath());
                finalStr+= destFile.getAbsolutePath() +"\n";
                finalSize++;
            }
        }
        filesReverted(finalSize, finalStr);        //popup for finished files
    }

    /**
     * This function updates the WEPS Management files recursively.
     */
    @Override
    public void UpdateWEPSJMI_actionPerformed(java.awt.event.ActionEvent event) {
        String dir;
        String destinationDirectory; // Needed for !inPlace updates
      
        WepsFileChooser2 fileChooserMan = new WepsFileChooser2(WepsFileTypes2.Dir, "", WepsFileChooser2.Action.Select);
        fileChooserMan.setFileSelectionMode(WepsFileChooser2.SelectionType.DIRECTORIES_ONLY);
        fileChooserMan.setMultiSelectionEnabled(false);
        fileChooserMan.setIsUpdatingManFileChooser(true);
        fileChooserMan.setDialogTitle("Select a directory where all WEPS management files will be updated");
        fileChooserMan.setTitleText("Select folder containing WEPS mgt files for updating");
        fileChooserMan.setAcceptAllFileFilterUsed(false);

//        dir = MCREWConfig.getDirectoryName(XMLConstants.smanagement_template);
        dir = projectDir;
        fileChooserMan.setCurrentDirectory(dir);
        fileChooserMan.setDefaultDirectory(new TFile(dir));
        fileChooserMan.enableFolderButtons();
        fileChooserMan.setFileFilter(WepsFileTypes2.Management.getFileFilter());
        fileChooserMan.enableDbButton(false);
        fileChooserMan.enableRecCheckbox(false);
        fileChooserMan.enableCfgDefLocButton(false);
        fileChooserMan.enableRecCheckbox(true);
        fileChooserMan.enableInPlaceCheckBox(true);
        int returnVal = fileChooserMan.showDialog(this);
        if (returnVal == WepsFileChooser2.APPROVE_OPTION) {
            try {
                try {
                    dir = fileChooserMan.getSelectedFile().getCanonicalPath() + TFile.separator;
                } catch (IOException ex) {
                    Exceptions.printStackTrace(ex);
                }
                TFile testdir = new TFile(dir);
                if ((!testdir.exists()) || testdir.isFile()) {
                    JOptionPane.showMessageDialog(this, dir + "\n\nSelection is not a directory.", "WEPS Information",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }
            } catch (HeadlessException e) {
                System.out.println("Error: " + e);
            }
            destinationDirectory = dir; //Set for popup message text. "!inPlace" conversions will update as necessary.
        } else {
            return;
        }
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); //set the cursor to wait cursor on the Mcrew screen
        
        XMLManagementUpdater updater = new XMLManagementUpdater();
        boolean isRecursive = fileChooserMan.isRecurive();
        boolean isInPlace = fileChooserMan.isInPlace();
        if(!isInPlace){
        WepsFileChooser2 fileChooser = new WepsFileChooser2(WepsFileTypes2.Dir, "", WepsFileChooser2.Action.Select);
        fileChooser.setFileSelectionMode(WepsFileChooser2.SelectionType.DIRECTORIES_ONLY);

        fileChooser.setMultiSelectionEnabled(false);
        fileChooser.setDialogTitle("Select a destination directory.");
        fileChooser.setAcceptAllFileFilterUsed(false);
        fileChooser.enableDbButton(false);
        fileChooser.enableInPlaceCheckBox(false);
        fileChooser.setFileFolderText(WepsFileChooser2.ApproveText.FOLDER);
        fileChooser.enableAllManButtons(cd);
        
        fileChooser.setDefaultDirectory(new TFile(dir));
//        fileChooser.setCurrentDirectory(tableObject.savePath);
        fileChooser.setCurrentDirectory(dir);
        
        returnVal = fileChooser.showDialog(this);

        if (returnVal == WepsFileChooser2.APPROVE_OPTION) 
        {
            //if they are the same act as though we are doing an in place update
            if(destinationDirectory.equals(dir)){
                isInPlace = true;
            }
            try { destinationDirectory = new TFile(fileChooser.getSelectedFile().getCanonicalPath() + TFile.separator).getAbsolutePath();
                updater.setDestTemp(destinationDirectory);
            } 
            catch (Exception e) { System.err.println("Error: " + e); }
        } else {
            return;
        }
        }
        if ( JOptionPane.showConfirmDialog(this, "This will update all WEPS management files "
        	+ "selected from this source directory with current information from CRLMOD operation and crop/residue records.\n\n"
                + "  Source: " + dir + "\n\n"
                + "The updated contents from the source folder will be placed within this destination folder:\n\n"
                + "  Destination: " + destinationDirectory + "\n\n"
                + "If the \"Recursive\" option is set, all mgt files residing within subfolders of the source folder will also be updated.\n"
                + "If the \"In Place\" option is set, the destination folder will match the source folder.\n"
		+ "For \"not In Place\" scenarios, the source folder name must be created and selected as the destination, if so desired.\n"
		+ "(The source folder name is not automatically appended to the destination folder location)\n\n"
                + "Do you want to update the WEPS management files now?",
                "Update WEPS Management Files:",
                JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
            return;
        }
//        if ( JOptionPane.showConfirmDialog(this, "This will update all WEPS management files "
//        	+ "selected from this source directory with current information from CRLMOD operation and crop/residue records.\n\n"
//                + "  Source: " + dir + "\n\n"
//                + "The updated contents from the source folder will be placed within this destination folder:\n\n"
//                + "  Destination: " + destinationDirectory + "\n\n"
//                + "If the \"Recursive\" option is set, all mgt files residing within subfolders of the source folder will also be updated.\n"
//                + "If the \"In Place\" option is set, the destination folder will match the source folder.\n"
//		+ "For \"not In Place\" scenarios, the source folder name must be created and selected as the destination, if so desired.\n"
//		+ "(The source folder name is not automatically appended to the destination folder location)\n\n"
//                + "Do you want to update the WEPS management files now?",
//                "Update WEPS Management Files:",
//                JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
//            return;
//        }
        updater.setInPlace(isInPlace);
        
        
        updater.updateDirectory(this, dir, isRecursive);
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); //set the cursor back to default on the Mcrew screen
    }

    
    private void filesReverted(int finalCount, String finalStrList){
        javax.swing.JDialog jdog = new javax.swing.JDialog();
//        jdog.setLayout(new GridLayout(2,
//          1,10,10));
        javax.swing.JTextArea textArea = new javax.swing.JTextArea(finalCount + " WEPS Management Files Updated\n"+finalStrList);
        javax.swing.JButton button;
        button = new javax.swing.JButton("CLOSE");
     
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e)
        {
            jdog.dispose();
        }
    });
//    textArea.add(button);
        javax.swing.JScrollPane scrollPane = new javax.swing.JScrollPane(textArea,javax.swing.JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);  
        
//        textArea.setLineWrap(true);  
//        textArea.setWrapStyleWord(true); 
        textArea.setPreferredSize( new java.awt.Dimension( 500, 250 ) );
        textArea.setEditable(false);
        scrollPane.setPreferredSize( new java.awt.Dimension( 500, 250 ) );
        button.setMargin(null);
        
    button.setSize(120, 30);
//    scrollPane.
     
        
         javax.swing.JPanel sizePanel = new javax.swing.JPanel();
     sizePanel.add(button);
     //parameterPanel.add(parameterButton);
//     parameterPanel.add(sizePanel);
    
        jdog.setTitle("Files Being updated");
//        jdog.setSize(new Dimension( 500, 250 ));
        jdog.setResizable(true);
        jdog.add(scrollPane);
//        jdog.add(sizePanel, BorderLayout.SOUTH);
//        jdog.add(sizePanel);
//        jdog.add
//        jdog.add(scrollPane);
        jdog.pack();
        jdog.setModal(true);
        
//    scrollPane.pack();
//        jdog.add()
    
//    jdog.setLocation(parent.getX()-50, parent.getY()-50);
    jdog.setVisible(true);
    }
    
    @Override
    protected void HelpJB_actionPerformed(java.awt.event.ActionEvent event) {
        HelpJMI_actionPerformed(event);
    }

    /**
     * Closes the MCREW Window.
     */
    @Override
    public void JBClose_actionPerformed(java.awt.event.ActionEvent evt) {
        ExitJMI_actionPerformed(evt);
    }
    
    /**
     * Takes the currently selected rows and adds them to the clipboard.
     */
    @Override 
    protected void CopyJMI_actionPerformed(ActionEvent evt) {
        tableObject.CopyJMI_actionPerformed(evt);
    } 
    
    /**
     * Makes the last year in the table year one, and increments all other years.
     */
    @Override 
    protected void CycleFwdJMI_actionPerformed(ActionEvent evt) { tableObject.CycleFwdJMI_actionPerformed(evt); }
    
    /**
     * Makes the first year in the table the number of years in the rotation and
     * decrements all other years.
     */
    @Override 
    protected void CycleBwdJMI_actionPerformed(ActionEvent evt) {
        tableObject.CycleBwdJMI_actionPerformed(evt);
    }
    
    /**
     * Adds a blank row into the table above the highest currently selected row.
     */
    @Override 
    protected void InsertJMI_actionPerformed(ActionEvent evt) {
        tableObject.InsertJMI_actionPerformed(evt);
    } 
    /**
     * Presents the user with a file chooser, so that they can select a .oprn file
     * to insert.  It then loads the data in that file into the row above.
     */
    @Override
    protected void InsertOperationJMI_actionPerformed(java.awt.event.ActionEvent evt) {
        tableObject.InsertOperationJMI_actionPerformed(evt);
    }
    
    /**
     * Iterates through each row in the table and places them in ascending order
     * by date.
     */
    @Override 
    protected void SortJMI_actionPerformed(ActionEvent evt) {
        tableObject.SortJMI_actionPerformed(evt);
    }
    
    /**
     * This operation will remove the selected rows from the table.
     */
    @Override 
    protected void DeleteJMI_actionPerformed(ActionEvent evt) {
        tableObject.DeleteJMI_actionPerformed(evt);
    }
    
    /**
     * If the operation immediately previous was delete, this will undo the 
     * changes made by that operation.
     */
    @Override
    public void UndoDeleteJMI_ActionPerformed(java.awt.event.ActionEvent evt) {
        tableObject.UndoDeleteJMI_ActionPerformed(evt);
    }

    /**
     * Inserts the rows on the clipboard above the highest currently selected row.
     */
    @Override 
    protected void PasteJMI_actionPerformed(ActionEvent evt) {
        tableObject.PasteJMI_actionPerformed(evt); 
    } 

    /**
     * Takes the currently selected rows and adds them to the clipboard, then
     * deletes those rows.
     */
    @Override 
    protected void CutJMI_actionPerformed(ActionEvent evt) {
        tableObject.CutJMI_actionPerformed(evt); 
    } 
    
    @Override 
    protected void NotesJMI_actionPerformed(ActionEvent evt) {
        tableObject.NotesJMI_actionPerformed(evt); 
    }
   
    @Override
    protected void DefaultViewJMI_actionPerformed(java.awt.event.ActionEvent evt) {
        for (String name : c_guiViews) {
            JCheckBoxMenuItem cmi = tableObject.getCmis(name);
            JToggleButton tb = tableObject.getTbs(name);

            if (cmi != null) {
                cmi.setSelected(false);
            }

            if (tb != null) {
                tb.setSelected(false);
            }

            tableObject.handleViewToggle(name, false);
        }
        tableObject.handleViewToggle("default", true);
    }
    
    @Override
    public void refreshDropdowns() {
        MCREWConfig.refreshDropdowns();
        System.out.println("Refreshing Crop/Operation Dropdown Menu Items");
        //Table newT = new Table(tableObject, tableObject.data);
        //tableObject.table.
    }
    
    /**
     * A coordinator method for making sure all open template buttons are disabled
     * when they should be.
     */
    public void disableOpenButtons()
    {
        JMI_openCT.setEnabled(false);
    }
    
    /**
     * Coordinator method for ensuring all undo buttons and items are disabled
     * when undo delete is not an option.
     */
    public void setUndoDeleteStatus(boolean enabled)
    {
        JMI_undoDelete.setEnabled(enabled);
    }
  
    /**
     * Appends an empty management to the table.  Sets the current table view
     * to that management.
     */
    @Override
    public void addNew()
    {
        timelineObject.appendNewFile();
        
        //Set the current view to the new data.

        invalidate();
        repaint();
    }
    
    /**
     * Overwrite the currently selected Managedata with a new (empty) dataset.
     */
    @Override
    public void newOverwrite() {
        if (!tableObject.checkSaveOnExit()) {
            return;
        }
        tableObject.newFile();
        timelineObject.resynchSelected();

        invalidate();
        repaint();
    }
    
    /**
     * Adds an existing management file to the current dataset, makes that
     * the currently selected dataset.
     */
    @Override
    public void addExisting()
    {
        
        String path = findManFile(tableObject.getSavePath());
        if(path == null) return;
        else timelineObject.appendExistingFile(path, tableObject.getTable().getData().intView());
        //Sycnh table.

        invalidate();
        repaint();
    }
    
    /**
     * Overwrite the currently selected ManageData with the manageData chosen by
     * the user in the file chooser.
     */
    @Override
    public void existingOverwrite()
    {
        try {
            if(!tableObject.checkSaveOnExit()) return;
            
            String path = ConfigData.getDefault().getDataParsed(ConfigData.MCREW_OPEN_DEFAULT);
            if (path == null) { // null check first so no crash and burn
                path = tableObject.getSavePath();
            } else if (path.equals("")) {
                path = tableObject.getSavePath();
            }
            boolean usingUpgm = ConfigData.checkParmValue("CD-upgm-manx", "1");
            WepsFileTypes2[] types;
            if (usingUpgm) {
                types = new WepsFileTypes2[] {WepsFileTypes2.Management, WepsFileTypes2.MANX};
            }
            else {
                types = new WepsFileTypes2[] {WepsFileTypes2.Management};
            }
            
            WepsFileChooser2 mfc = new WepsFileChooser2(types, path, WepsFileChooser2.Action.Select);;
            
            mfc.homeToolTip(mfc);//set the tooltip of "home" button to "Home" instead of "Desktop"
            mfc.disableNewFolder(mfc); //remove the NewFolder button
            mfc.enableFolderButtons();
            mfc.enableCfgDefLocButton(false);
            mfc.enableDbButton(false);
            mfc.setTitleText("Select Existing Management File");
            // Sets filter type - WEPS mgt files (*.man)
            mfc.setFileFilter(WepsFileTypes2.Management.getFileFilter());
            // Sets FileChooser's default location - should be current Project dir if not specified
            //mfc.setCurrentDirectory();
            // Sets "Def Loc" button location
            mfc.setDefaultDirectory(new File(projectDir));
            // Sets File selection mode - mgt files only, no folders here
            mfc.setFileSelectionMode(WepsFileChooser2.SelectionType.FILES_ONLY);
            if (!(mfc.showDialog(this) == WepsFileChooser2.APPROVE_OPTION)) {
                return;
            }
            
            path = (new TFile(mfc.getSelectedFile())).getAbsolutePath();
            //String path = findManFile(tableObject.getSavePath());
            TFile selectedFile = new TFile(mfc.getSelectedFile());
            
            String fileDir = selectedFile.getCanonicalPath();
            String m_fileName = selectedFile.getName();
            String copyToFilePath;
            
            copyToFilePath = projectDir + TFile.separator + m_fileName;
            // MEH
            if (!copyToFilePath.contentEquals(selectedFile.getPath())) {
                if (usda.weru.util.Util.copyFile(fileDir, copyToFilePath) == false) {
                    JOptionPane.showMessageDialog(this, "Something wrong in copying the template file."
                            + "Try opening the file through Open File option", "Open copy of template", JOptionPane.OK_OPTION);
                    return;
                }
            }
//            if(!Util.isReadOnly(copyToFilePath)){
//                tableObject.openFile(copyToFilePath);
//            }
            
            
            if(path == null) return;
            if(!Util.isReadOnly(copyToFilePath)){
                tableObject.openFile(copyToFilePath);
            }else{
                JOptionPane.showMessageDialog(this, "Read Only File Detected \nPlease Provide MCREW With a Writable File","Read Only File Detected", JOptionPane.ERROR_MESSAGE);
            }
            timelineObject.resynchSelected();
            
            
//            TFile file = new TFile(fileDir);
//            tableObject.saveTemplatePath = file.getParent();


invalidate();
repaint();
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
        
    }

   
    /**
     * Overwrite the currently selected ManageData generated from the WEPP
     * Management file the user selects.
     */
    @Override
    public void weppOverwrite()
    {
        if(!tableObject.checkSaveOnExit()) return;
        String path = findAltFile(tableObject.getSavePath(), WepsFileTypes2.WEPP);
        if(path == null) return;
        else 
        {
            SkelImportPanel weppImport = new SkelImportPanel(this, "Operation or crop not found", true, ManageData.WriteFileMode.FROM_NRCS);
            String opDBDir = MCREWConfig.getDirectoryName(XMLConstants.soperation);
            String cropDBDir = MCREWConfig.getDirectoryName(XMLConstants.scrop);

            if (!weppImport.setDatabases(opDBDir, cropDBDir)) {
                //something went wrong, quit
                return;
            }
            weppImport.wepp2man(path, projectDir);
            if(!Util.isReadOnly(weppImport.getDestFile())){
                tableObject.openFile(weppImport.getDestFile()); 
            }
            else{
            JOptionPane.showMessageDialog(this, "Read Only File Detected \nPlease Provide MCREW With a Writable File","Read Only File Detected", JOptionPane.ERROR_MESSAGE);
            }   
            
        }
        timelineObject.resynchSelected();

        invalidate();
        repaint();
    }
    
    /**
     * Non broken weppOverwrite using temp files. Loads wepp .json file into 
     * the MCREW window from the drop down tab under file.
     */
    @Override
    public void weppOverwrite_butBetter() {
        if(!tableObject.checkSaveOnExit()) return;
        
        // This uses a WepsFileChooser2 menu to have the user select a .json file
        String path = findAltFile(tableObject.getSavePath(), WepsFileTypes2.WEPP, WepsFileTypes2.MGT);

        if (path == null) {
            return; // No file selected, error, etc.
        }
        else {
            SkelImportPanel weppImport = new SkelImportPanel(this, "Operation or crop not found", true, ManageData.WriteFileMode.FROM_NRCS);
            // Load up the databases for translation
            String opDBDir = MCREWConfig.getDirectoryName(XMLConstants.soperation);
            String cropDBDir = MCREWConfig.getDirectoryName(XMLConstants.scrop);

            if (!weppImport.setDatabases(opDBDir, cropDBDir)) {
                //something went wrong, quit
                return;
            }
            
            /* Translate the file */
            
            // This creates a temp file that deletes on exit of program. 
            JSONUpdater json = new JSONUpdater(this);
            java.io.File tempSkelFile = json.write_to_MAN(path);
            
            // if file null, failure
            if (tempSkelFile == null) {
                return;
            }

            try {
                java.io.File tempMan = java.io.File.createTempFile("tempManMCREW", ".man");
                tempMan.deleteOnExit();

                // Set for this method and file name. Need to just get the name.
                java.io.File f = new java.io.File(path);
                weppImport.setWEPPconversion(true, f.getName());  
                
                weppImport.skel2man(tempSkelFile.getAbsolutePath(), projectDir);
            } catch (IOException io ) {
                System.err.println("Failure to generate temp file for translation");
            } finally {
                weppImport.setWEPPconversion(false, "AAA");
            }
            
            // open into table
            if(!Util.isReadOnly(weppImport.getDestFile())){
                tableObject.openFile(weppImport.getDestFile()); 
            }
            else{
            JOptionPane.showMessageDialog(this, "Read Only File Detected \nPlease Provide MCREW With a Writable File","Read Only File Detected", JOptionPane.ERROR_MESSAGE);
            }
        }
        timelineObject.resynchSelected();
        invalidate();
        repaint();
    }
    
    /**
     * Add an existing template file to the current dataset, sets the table view to that.
     */
    @Override
    public void addTemplate()
    {
        TFile dirXML = new TFile(MCREWConfig.getDirectoryName(XMLConstants.smanagement_template));
        String dirXMLPath = dirXML.getAbsolutePath();
        String path = findManFile(dirXMLPath);
        if(path == null) return;
        else
        {
            TFile selectedFile = new TFile(path);
            try 
            {
                String fileDir = selectedFile.getCanonicalPath();
                String m_fileName = selectedFile.getName();
                String copyToFilePath;

                copyToFilePath = projectDir + TFile.separator + m_fileName;
                if (usda.weru.util.Util.copyFile(fileDir, copyToFilePath) == false) {
                    JOptionPane.showMessageDialog(this, "Something wrong in copying the template file."
                            + "Try opening the file through Open File option", "Open copy of template", JOptionPane.OK_OPTION);
                    return;
                }
                timelineObject.appendExistingFile(copyToFilePath, tableObject.getTable().getData().intView());
                TFile file = new TFile(fileDir);
                tableObject.saveTemplatePath = file.getParent();
            } catch (IOException e) {
                System.err.println("Error in opening file " + e);
            }
        }
    }
    
    /**
     * Overwrite the currently selected ManageData with the managedata generated by loading
     * the user specified template file.
     */
    @Override
    public void templateOverwrite()
    {
        if(!tableObject.checkSaveOnExit()) return;
        TFile dirXML = new TFile(MCREWConfig.getDirectoryName(XMLConstants.smanagement_template));
        String dirXMLPath = ConfigData.getDefault().getDataParsed(ConfigData.MCREW_OPEN_COPY_OF_SYSTEM_TEMPLATE_DEFAULT);
        if (dirXMLPath == null) { // check for null first so as to not brick if null
            dirXMLPath = dirXML.getAbsolutePath();
        } else if (dirXMLPath.equals("")) {
            dirXMLPath = dirXML.getAbsolutePath();
        }
        
        String path = findManFileTemplate(dirXMLPath);
        if(path == null) return;
        else
        {
            TFile selectedFile = new TFile(path);
            try 
            {
                String fileDir = selectedFile.getCanonicalPath();
                String m_fileName = selectedFile.getName();
                String copyToFilePath;

                copyToFilePath = projectDir + TFile.separator + m_fileName;
                // MEH
                if (!copyToFilePath.contentEquals(selectedFile.getPath())) {
                    if (usda.weru.util.Util.copyFile(fileDir, copyToFilePath) == false) {
                        JOptionPane.showMessageDialog(this, "Something wrong in copying the template file."
                                + "Try opening the file through Open File option", "Open copy of template", JOptionPane.OK_OPTION);
                        return;
                    }
                }
                if(!Util.isReadOnly(copyToFilePath)){
                    tableObject.openFile(copyToFilePath);
                }
                else{
                    JOptionPane.showMessageDialog(this, "Read Only File Detected \nPlease Provide MCREW With a Writable File","Read Only File Detected", JOptionPane.ERROR_MESSAGE);
                }
                timelineObject.resynchSelected();
                TFile file = new TFile(fileDir);
                tableObject.saveTemplatePath = file.getParent();
            } catch (IOException e) {
                System.err.println("Error in opening file " + e);
            }
        }
    }
    
    @Override
    public void localTemplateOverwrite() {
        System.out.println("Overwriting with local template.");
        if(!tableObject.checkSaveOnExit()) return;
        String path = findManFileLocalTemplate(Util.parse(Weps.getInstance().cd.getData(ConfigData.LocalManDB)));
        if(path == null) return;
        else
        {
            TFile selectedFile = new TFile(path);
            try 
            {
                String fileDir = selectedFile.getCanonicalPath();
                String m_fileName = selectedFile.getName();
                String copyToFilePath;

                copyToFilePath = projectDir + TFile.separator + m_fileName;
                // MEH
                if (!copyToFilePath.contentEquals(selectedFile.getPath())) {
                    if (usda.weru.util.Util.copyFile(fileDir, copyToFilePath) == false) {
                        JOptionPane.showMessageDialog(this, "Something wrong in copying the template file."
                                + "Try opening the file through Open File option", "Open copy of template", JOptionPane.OK_OPTION);
                        return;
                    }
                }
                if(!Util.isReadOnly(copyToFilePath)){
                    tableObject.openFile(copyToFilePath);
                }
                else{
                    JOptionPane.showMessageDialog(this, "Read Only File Detected \nPlease Provide MCREW With a Writable File","Read Only File Detected", JOptionPane.ERROR_MESSAGE);
                }
                timelineObject.resynchSelected();
                TFile file = new TFile(fileDir);
                tableObject.saveTemplatePath = file.getParent();
            } catch (IOException e) {
                System.err.println("Error in opening file " + e);
            }
        }
    }
    
    public void sharedTemplateOverwrite() {
        System.out.println("Overwriting with shared template.");
        if(!tableObject.checkSaveOnExit()) return;
        String path = findManFileSharedTemplate(Util.parse(Weps.getInstance().cd.getData(ConfigData.SharedManDB)));
        if(path == null) return;
        else
        {
            TFile selectedFile = new TFile(path);
            try 
            {
                String fileDir = selectedFile.getCanonicalPath();
                String m_fileName = selectedFile.getName();
                String copyToFilePath;

                copyToFilePath = projectDir + TFile.separator + m_fileName;
                // MEH
                if (!copyToFilePath.contentEquals(selectedFile.getPath())) {
                    if (usda.weru.util.Util.copyFile(fileDir, copyToFilePath) == false) {
                        JOptionPane.showMessageDialog(this, "Something wrong in copying the template file."
                                + "Try opening the file through Open File option", "Open copy of template", JOptionPane.OK_OPTION);
                        return;
                    }
                }
                if(!Util.isReadOnly(copyToFilePath)){
                    tableObject.openFile(copyToFilePath);
                }
                else{
                    JOptionPane.showMessageDialog(this, "Read Only File Detected \nPlease Provide MCREW With a Writable File","Read Only File Detected", JOptionPane.ERROR_MESSAGE);
                }
               
                timelineObject.resynchSelected();
                TFile file = new TFile(fileDir);
                tableObject.saveTemplatePath = file.getParent();
            } catch (IOException e) {
                System.err.println("Error in opening file " + e);
            }
        }
    }

    public void crlmodOverwrite(){
        System.out.println("Overwriting with CrLmod Management.");
        if(!tableObject.checkSaveOnExit()) return;
        String path = findCrLmodFile();
        if(path == null) return;
        else {    
            TFile selectedFile = new TFile(path);
            try 
            {
                String fileDir = selectedFile.getCanonicalPath();
                String m_fileName = selectedFile.getName();
                String copyToFilePath;

                copyToFilePath = projectDir + TFile.separator + m_fileName;
                // MEH
                if (!copyToFilePath.contentEquals(selectedFile.getPath())) {
                    if (usda.weru.util.Util.copyFile(fileDir, copyToFilePath) == false) {
                        String error_msg = 
                                "FILE PATH:    " + selectedFile.getAbsolutePath() + "\n" +
                                "PROJECT PATH: " + copyToFilePath;
                        System.out.println("[ERROR] FILE FAILED TO COPY:\n" + error_msg);
                        int response = JOptionPane.showConfirmDialog(this, "Copying the downloaded file to the project directory failed.\n" +
                                "\n" + error_msg +
                                "\n\nWould you like to try this copy operation again?", path, JOptionPane.YES_NO_OPTION);
                        
                        if (response == JOptionPane.YES_OPTION) {
                            if (usda.weru.util.Util.copyFile(selectedFile.getAbsolutePath(), copyToFilePath) == false) {
                                JOptionPane.showMessageDialog(this, "Something went wrong again in copying the template file.\n"
                                + "Try opening the file through \"Open File\" option", "Open copy of template", JOptionPane.OK_OPTION);
                                return;
                            } else {
                                JOptionPane.showMessageDialog(this, "The second copy was successful! Continuing to load file.", "Open copy of template", JOptionPane.OK_OPTION);
                            }
                        } else {
                            JOptionPane.showMessageDialog(this, "Please try to open this downloaded file from the location:\n" +
                                    selectedFile.getAbsolutePath() + "\n" + 
                                    "or manually copy to Project directory and open from there.", "Open copy of Template", JOptionPane.OK_OPTION);
                            return;
                        }
                    }
                }
                if(!Util.isReadOnly(copyToFilePath)){
                    tableObject.openFile(copyToFilePath);
                }
                else{
                    JOptionPane.showMessageDialog(this, "Read Only File Detected \nPlease Provide MCREW With a Writable File","Read Only File Detected", JOptionPane.ERROR_MESSAGE);
                } 
                timelineObject.resynchSelected();
                TFile file = new TFile(fileDir);
                tableObject.saveTemplatePath = file.getParent();
            } catch (IOException e) {
                System.err.println("Error in opening file " + e);
            }
        }
    }
    /**
     * Saves the current table into memory;  Uses table object to achieve result.
     */
    @Override
    public void saveCurrent() {
        tableObject.SaveJB_actionPerformed(null);
        
    }
    
    /**
     * Saves the current table into memory with a different name.
     */
    @Override
    public void saveCurrentAs() {
        // It is possible to get here from constructor, before tableObject has been initialized
        if (tableObject != null) {
            tableObject.saveCurrentAs();
        }
        //Do we have to fire a change at the timeline?
    }
    
    /**
     * Saves the current table into memory as a local template.
     */
    @Override
    public void saveCurrentAsTemplate() 
    {
        tableObject.saveCurrentAsTemplate();
        //Do we have to fire a change at the timeline?
    }
    
    /**
     * Saves the current table into memory as a shared template.
     */
    @Override
    public void saveCurrentAsSharedTemplate() {
        tableObject.saveCurrentAsSharedTemplate();
    }
    
    /**
     * Saves all currently open management files.
     */
    @Override
    public void saveAll() {
        timelineObject.saveAllFiles();
    }
    
    /**
     * Save all currently open management files, appending the user specified string
     * onto the end of the name and moving the files to the specified location.
     */
    @Override
    public void saveAllAs()
    {
        if(EventQueue.isDispatchThread())
        {
            Thread th = new Thread()
            {
                @Override
                public void run()
                {
                    ExtensionSelector ext = new ExtensionSelector(tableObject.savePath);
                    if(!ext.recieveInput())  return; 
                    for(int index = 0; index < timelineObject.getNumFiles(); index ++)
                    {
                        TablePanel tabPan = timelineObject.getTablePanelNoSelect(index);
                        tabPan.saveCurrentWithName(ext.getDestination() + TFile.separator 
                                + (tabPan.fileName.trim().endsWith(".man") ? 
                                tabPan.fileName.trim().substring(0, tabPan.fileName.lastIndexOf("."))
                                : tabPan.fileName) + ext.getExtension());
                    }
                }
            };
            th.start();
        }
    }
    
    /**
     * Saves all the currently open management files as templates.
     */
    @Override
    public void saveAllAsTemplate()
    {
        if(EventQueue.isDispatchThread())
        {
            Thread th = new Thread()
            {
                @Override
                public void run()
                {
                    String tempSaveAsPath = MCREWConfig.getDirectoryName(usda.weru.util.ConfigData.LocalManDB);
                    String tempPath = MCREWConfig.getDirectoryName(XMLConstants.smanagement_template);
                    TFile dirXML = null;
                    if (tempSaveAsPath != null && tempSaveAsPath.length() > 0 
                            && MCREWConfig.getHasManTempSaveAsDir()) dirXML = new TFile(tempSaveAsPath);
                    else dirXML = new TFile(tempPath);
                    ExtensionSelector ext = new ExtensionSelector(dirXML.getAbsolutePath());
                    if(!ext.recieveInput())  return; 
                    for(int index = 0; index < timelineObject.getNumFiles(); index ++)
                    {
                        TablePanel tabPan = timelineObject.getTablePanelNoSelect(index);
                        tabPan.saveCurrentWithName(ext.getDestination() + TFile.separator 
                                + (tabPan.fileName.trim().endsWith(".man") ? 
                                tabPan.fileName.trim().substring(0, tabPan.fileName.lastIndexOf("."))
                                : tabPan.fileName) + ext.getExtension());
                    }
                }
            };
            th.start();
        }
    }
    
    /**
     * Allows the user to select the file they want to open, etc. using a file
     * chooser.
     */
    public String findManFile(String path)
    {
        if(ConfigData.checkParmValue(ConfigData.crlmodEnabled, "1")) {
            return findCrLmodFile();
        }
        
       // CrLmodFile rootFile = new CrLmodFile("CrLmod Managements", lmodType.lmodManagement);
        //rootFile.listFiles();
        WepsFileChooser2 mfc;
        if(ConfigData.checkParmValue("CD-upgm-manx", "1"))
        {
            mfc = WepsFileChooser2.create(WepsFileChooser2.Action.Select, 
                    new TFile(path), false, true, null,
                    WepsFileTypes2.Management, WepsFileTypes2.Rotation, WepsFileTypes2.MANX);
        }
        else
        {
            mfc = WepsFileChooser2.create(WepsFileChooser2.Action.Select, 
                    new TFile(path), false, true, null,
                    WepsFileTypes2.Management, WepsFileTypes2.Rotation);
        } 
        
        //set the tooltip of "home" button to "Home" instead of "Desktop"
        mfc.homeToolTip(mfc);
        //remove the NewFolder button
        mfc.disableNewFolder(mfc);
//        if ((tableObject.getSavePath() == null) || (tableObject.getSavePath().length()
//                == 0)) mfc.setCurrentDirectory(new TFile(MCREWConfig.getDirectoryName(
//                            XMLConstants.smanagement_template)));
//        else mfc.setCurrentDirectory(new TFile(tableObject.getSavePath()));
        mfc.enableFolderButtons();
        mfc.enableDbButton(false);
        mfc.enableCfgDefLocButton(false);
        //mfc.setCurrentDirectory();
        mfc.setDefaultDirectory(new File(projectDir));
        mfc.setFileFilter(WepsFileTypes2.Management.getFileFilter());
        mfc.setFileSelectionMode(WepsFileChooser2.SelectionType.FILES_ONLY);
        if (!(mfc.showDialog(this) == WepsFileChooser2.APPROVE_OPTION)) {
            return null;
        }
        return (new TFile(mfc.getSelectedFile())).getAbsolutePath();
    }
    
     /**
     * Allows the user to select the file they want to open, etc. using a file
     * chooser.
     */
    public String findManFileTemplate(String path)
    {
        WepsFileChooser2 mfc;
        if(cd.isFormatXMLAllowed())
        {
            mfc = WepsFileChooser2.create(WepsFileChooser2.Action.Select, 
                    new TFile(path), false, true, null,
                    WepsFileTypes2.Management, WepsFileTypes2.Rotation, WepsFileTypes2.XML);
        }
        else
        {
            mfc = WepsFileChooser2.create(WepsFileChooser2.Action.Select, 
                    new TFile(path), false, true, null,
                    WepsFileTypes2.Management, WepsFileTypes2.Rotation);
        }
        //set the tooltip of "home" button to "Home" instead of "Desktop"
        mfc.homeToolTip(mfc);
        //remove the NewFolder button
        mfc.disableNewFolder(mfc);
//        if ((tableObject.getSavePath() == null) || (tableObject.getSavePath().length()
//                == 0)) mfc.setCurrentDirectory(new TFile(MCREWConfig.getDirectoryName(
//                            XMLConstants.smanagement_template)));
//        else mfc.setCurrentDirectory(new TFile(tableObject.getSavePath()));
        mfc.enableFolderButtons();
        mfc.enableDbButton(false);
        mfc.enableCfgDefLocButton(false);
        mfc.setCurrentDirectory(path); 
        mfc.setDefaultDirectory(new TFile(path));
        mfc.setFileFilter(WepsFileTypes2.Management.getFileFilter());
        TFile shaMan = new TFile(Weps.getInstance().cd.getDataParsed(ConfigData.SharedManDB));
        //System.out.println("shaMan path: " + shaMan.getAbsolutePath());
        //System.out.println("Is shaMan a directory? " + shaMan.isDirectory());
        TFile locMan = new TFile(Weps.getInstance().cd.getDataParsed(ConfigData.LocalManDB));
        //System.out.println("locMan path: " + locMan.getAbsolutePath());
        //System.out.println("Is locMan a directory? " + locMan.isDirectory());
        mfc.getPath().addItem(shaMan);
        mfc.getPath().addItem(locMan);
        mfc.setFileSelectionMode(WepsFileChooser2.SelectionType.FILES_ONLY);
        if (!(mfc.showDialog(this) == WepsFileChooser2.APPROVE_OPTION)) {
            return null;
        }
        return (new TFile(mfc.getSelectedFile())).getAbsolutePath();
    }
    
    private TFile InsertFileCRLMOD() {
        setWaiting(true);
        try {

            ManageData dataToInsert = new ManageData();
            CrLmodFile rootFile = new CrLmodFile("CrLmod Managements", CsipLmodUtil.lmodType.lmodManagement);
            rootFile.listFiles();
            WepsFileChooser2 mfc = new WepsFileChooser2(WepsFileTypes2.Management, rootFile,
            WepsFileChooser2.Action.Select);
            mfc.setCurrentDirectory_remote_file(rootFile);
            mfc.setDefaultDirectory(rootFile);
            mfc.setFileFilter(WepsFileTypes2.Management.getFileFilter());

            TFile shaMan = new TFile(Util.parse(Weps.getInstance().cd.getData(ConfigData.SharedManDB)));
            TFile locMan = new TFile(Util.parse(Weps.getInstance().cd.getData(ConfigData.LocalManDB)));
            TFile sysMan = new TFile(Util.parse(MCREWConfig.getDirectoryName(ConfigData.ManTemp)));
            mfc.getPath().addItem(shaMan);
            mfc.getPath().addItem(locMan);
            mfc.getPath().addItem(sysMan);
            mfc.enableDbButton(false);
            mfc.enableCfgDefLocButton(false);
            //set the tooltip of "home" button to "Home" instead of "Desktop"
            mfc.homeToolTip(mfc);
            //remove the NewFolder button
            mfc.disableNewFolder(mfc);
            mfc.enableFolderButtons();
            mfc.enableDbButton(false);
            mfc.getPath().addAndSelectItem(rootFile);
            if (!(mfc.showDialog(null) == WepsFileChooser2.APPROVE_OPTION)) {
                return null;
            }
            TFile selectedFile = new TFile(mfc.getSelectedFile());
            
            return selectedFile;
           
        } finally {
            setWaiting(false);
        }
    }
    
    public String findCrLmodFile()
    {
        String CRLMOD_config = ConfigData.getDefault().getDataParsed(ConfigData.MGT_T_BUTTON_DEFAULT);
        WepsFileChooser2 mfc = null;
        boolean crlmod = false;
        CrLmodFile rootFile = null;
        
        if (CRLMOD_config == null) 
            crlmod = true;
        if (!crlmod) if (CRLMOD_config.equals("CRLMOD Managements") || CRLMOD_config.equals("CrLmod Managements") ||
                    CRLMOD_config.equals("") || crlmod) {
                crlmod = true;
            }
        
        // check that file actually exists
        if (!crlmod) {
            if (!(new TFile(CRLMOD_config)).exists()) {
                // if file doesn't exist, then use default crlmod
                crlmod = true;
            }
        }
        
        if (crlmod){
//            System.out.println("Opening CrLmod File");
//            rootFile = new CrLmodFile("CrLmod Managements", lmodType.lmodManagement);
//            rootFile.listFiles();
//            mfc = new WepsFileChooser2(WepsFileTypes2.Management, rootFile,
//                    WepsFileChooser2.Action.Select);
//            mfc.setCurrentDirectory_remote_file(rootFile);
//            mfc.setDefaultDirectory(rootFile);
//            mfc.setTitleText("MCREW - Open Copy of CRLMOD Template");
//            System.out.println("Root File Path:" + rootFile.getAbsolutePath());
        } else {
            System.out.println("Opening to directory from configuration parameter.");
            mfc = new WepsFileChooser2(WepsFileTypes2.Management, new TFile(CRLMOD_config),
                    WepsFileChooser2.Action.Select);
            mfc.setCurrentDirectory(CRLMOD_config);
            mfc.setDialogTitle("Open copy of Management file");
            mfc.setTitleText("MCREW - Open Copy of CRLMOD Template");
            mfc.setFileFilter(WepsFileTypes2.Management.getFileFilter());
            
            TFile shaMan = new TFile(Weps.getInstance().cd.getDataParsed(ConfigData.SharedManDB));
            TFile locMan = new TFile(Weps.getInstance().cd.getDataParsed(ConfigData.LocalManDB));
            TFile sysMan = new TFile(MCREWConfig.getDirectoryName(ConfigData.ManTemp));
            mfc.getPath().addItem(sysMan);
            mfc.getPath().addItem(locMan);
            mfc.getPath().addItem(shaMan);
            //set the tooltip of "home" button to "Home" instead of "Desktop"
            mfc.homeToolTip(mfc);
            //remove the NewFolder button
            mfc.disableNewFolder(mfc);
            mfc.enableFolderButtons();
            mfc.enableDbButton(false);
            mfc.enableCfgDefLocButton(false);
            mfc.setFileSelectionMode(WepsFileChooser2.SelectionType.FILES_ONLY);
        }
        
        
        if (crlmod) {
//            mfc.getPath().addAndSelectItem(rootFile);
//            mfc.setDefaultDirectory(rootFile);
            TFile selectedFile =InsertFileCRLMOD();
            if(selectedFile==null){return null;}
            return selectedFile.getAbsolutePath();
        } else {
            mfc.setDefaultDirectory(new TFile(CRLMOD_config));
            mfc.setFileFilter(WepsFileTypes2.Management.getFileFilter());
        }
        if (!(mfc.showDialog(this) == WepsFileChooser2.APPROVE_OPTION)) {
            return null;
        }
        return (new TFile(mfc.getSelectedFile())).getAbsolutePath();
    }
    
         /**
     * Allows the user to select the file they want to open, etc. using a file
     * chooser.
     */
    public String findManFileLocalTemplate(String path)
    {
        WepsFileChooser2 mfc;
        if(cd.isFormatXMLAllowed())
        {
            mfc = WepsFileChooser2.create(WepsFileChooser2.Action.Select, 
                    new TFile(path), false, true, null,
                    WepsFileTypes2.Management, WepsFileTypes2.Rotation, WepsFileTypes2.XML);
        }
        else
        {
            TFile tffff = new TFile(Weps.getInstance().cd.getData(ConfigData.LocalManDB));
            System.out.println(tffff.getAbsolutePath());
            mfc = WepsFileChooser2.create(WepsFileChooser2.Action.Select, 
                    new TFile(path), false, true, null,
                    WepsFileTypes2.Management, WepsFileTypes2.Rotation);
        }
        //set the tooltip of "home" button to "Home" instead of "Desktop"
        mfc.homeToolTip(mfc);
        //remove the NewFolder button
        mfc.disableNewFolder(mfc);
//        if ((tableObject.getSavePath() == null) || (tableObject.getSavePath().length()
//                == 0)) mfc.setCurrentDirectory(new TFile(MCREWConfig.getDirectoryName(
//                            XMLConstants.smanagement_template)));
//        else mfc.setCurrentDirectory(new TFile(tableObject.getSavePath()));
        mfc.enableFolderButtons();
        mfc.enableCfgDefLocButton(false);
        mfc.enableDbButton(false);
        mfc.setCurrentDirectory(path);
        mfc.setDefaultDirectory(new TFile(path));
        mfc.setFileFilter(WepsFileTypes2.Management.getFileFilter());
        TFile shaMan = new TFile(Weps.getInstance().cd.getDataParsed(ConfigData.SharedManDB));
        //System.out.println("shaMan path: " + shaMan.getAbsolutePath());
        //System.out.println("Is shaMan a directory? " + shaMan.isDirectory());
        TFile sysMan = new TFile(MCREWConfig.getDirectoryName(ConfigData.ManTemp));
        //System.out.println("sysMan path: " + sysMan.getAbsolutePath());
        //System.out.println("Is sysMan a directory? " + sysMan.isDirectory());
        mfc.getPath().addItem(shaMan);
        mfc.getPath().addItem(sysMan);
        mfc.setFileSelectionMode(WepsFileChooser2.SelectionType.FILES_ONLY);
        if (!(mfc.showDialog(this) == WepsFileChooser2.APPROVE_OPTION)) {
            return null;
        }
        return (new TFile(mfc.getSelectedFile())).getAbsolutePath();
    }

    public String findManFileSharedTemplate(String path)
    {
        WepsFileChooser2 mfc;
        if(cd.isFormatXMLAllowed())
        {
            mfc = WepsFileChooser2.create(WepsFileChooser2.Action.Select, 
                    new TFile(path), false, true, null,
                    WepsFileTypes2.Management, WepsFileTypes2.Rotation, WepsFileTypes2.XML);
        }
        else
        {
            mfc = WepsFileChooser2.create(WepsFileChooser2.Action.Select, 
                    new TFile(path), false, true, null,
                    WepsFileTypes2.Management, WepsFileTypes2.Rotation);
        }
        //set the tooltip of "home" button to "Home" instead of "Desktop"
        mfc.homeToolTip(mfc);
        //remove the NewFolder button
        mfc.disableNewFolder(mfc);
//        if ((tableObject.getSavePath() == null) || (tableObject.getSavePath().length()
//                == 0)) mfc.setCurrentDirectory(new TFile(MCREWConfig.getDirectoryName(
//                            XMLConstants.smanagement_template)));
//        else mfc.setCurrentDirectory(new TFile(tableObject.getSavePath()));
        mfc.enableFolderButtons();
        mfc.enableDbButton(false);
        mfc.enableCfgDefLocButton(false);
        mfc.setCurrentDirectory(path);
        mfc.setDefaultDirectory(new TFile(path));
        mfc.setFileFilter(WepsFileTypes2.Management.getFileFilter());
        TFile locMan = new TFile(Weps.getInstance().cd.getDataParsed(ConfigData.LocalManDB));
        //System.out.println("shaMan path: " + shaMan.getAbsolutePath());
        //System.out.println("Is shaMan a directory? " + shaMan.isDirectory());
        TFile sysMan = new TFile(MCREWConfig.getDirectoryName(ConfigData.ManTemp));
        //System.out.println("sysMan path: " + sysMan.getAbsolutePath());
        //System.out.println("Is sysMan a directory? " + sysMan.isDirectory());
        mfc.getPath().addItem(locMan);
        mfc.getPath().addItem(sysMan);
        mfc.setFileSelectionMode(WepsFileChooser2.SelectionType.FILES_ONLY);
        if (!(mfc.showDialog(this) == WepsFileChooser2.APPROVE_OPTION)) {
            return null;
        }
        return (new TFile(mfc.getSelectedFile())).getAbsolutePath();
    }
    
    /**
     * Allows the user to select the file they want to open, etc. using a file
     * chooser.  Configurable extension filters.
     */
    public String findAltFile(String path, WepsFileTypes2... types)
    {
        WepsFileChooser2 mfc = WepsFileChooser2.create(WepsFileChooser2.Action.Select, 
                    new TFile(path), false, true, null, types);
        //set the tooltip of "home" button to "Home" instead of "Desktop"
        mfc.homeToolTip(mfc);
        //remove the NewFolder button
        mfc.disableNewFolder(mfc);
        mfc.enableFolderButtons();
        mfc.enableDbButton(false);
        mfc.enableCfgDefLocButton(false);
        mfc.setCurrentDirectory(path);
        mfc.setFileFilter(WepsFileTypes2.Management.getFileFilter());
        mfc.setFileSelectionMode(WepsFileChooser2.SelectionType.FILES_ONLY);
        if (!(mfc.showDialog(this) == WepsFileChooser2.APPROVE_OPTION)) {
            return null;
        }
        
        return (new TFile(mfc.getSelectedFile())).getAbsolutePath();
    }
    
    /**
     * Overridden so as to force a call to repaint the timeline, as the timeline
     * won't paint unless repaint is called. 
     */
    @Override
    public void repaint()
    {
        super.repaint();
        if(timelineObject != null) timelineObject.repaint();
    }
    
    /**
     * Initializes the view menu.
     */
    private void setupViews()
    {
        for (final MCREWConfig.TableView view : MCREWConfig.getTableViews()) {
            //The default view is a special case and hardcoded into the menus
            if (view.getName().equals("default")) {
                continue;
            }
            JCheckBoxMenuItem cmi = null;
            JToggleButton tb = null;

            if (view.getMenuText() != null && view.getMenuText().length() > 0) {
                cmi = new JCheckBoxMenuItem(view.getMenuText());
                JM_view.add(cmi);
                tableObject.addCmis(view.getName(), cmi);
            }

            if (view.getToolbarImage() != null && view.getToolbarImage().length() > 0) {

                addToggleButton(new ImageIcon(Resources.getImage(view.getToolbarImage())), view.getName());
                tb = new JToggleButton();
            }

            if (cmi != null || tb != null) {
                //It is gui
                c_guiViews.add(view.getName());
            }

            final JCheckBoxMenuItem cmi2 = cmi;
            final JToggleButton tb2 = tb;

            if (cmi != null) {
                cmi.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        tableObject.handleViewToggle(view.getName(), cmi2.isSelected());
                    }
                });
            }

            if (tb != null) {
                tb.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        tableObject.handleViewToggle(view.getName(), tb2.isSelected());
                    }
                });
            }

        }
    }
    
    /**
     * Adds the specific toggle button to the button bar of the table.
     */
    private void addToggleButton(ImageIcon icon, String name)
    {
        for(int index = 0; index < timelineObject.getNumFiles(); index ++)
        {
            JToggleButton tb = new JToggleButton(icon);
            timelineObject.getTablePanelNoSelect(index).addtoToolbar(tb);
            timelineObject.getTablePanelNoSelect(index).addTbs(name, tb);
            tb.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    tableObject.handleViewToggle(name, tb.isSelected());
                }
            });
        }
    }
    
    /**
     * Attaches the necessary help to relevant fields in the coordinator and fires
     * the add help in the subcomponents of MCREW (Table and Timeline).
     */
    private void addHelp() {
        //If the mcrew helpset has already been loaded we can skip this.
        if (Help.hasHelpSet("MCREW") == false) {
            loadHelp();
        }

        addCSH(Help.getHelpSet());
    }

    /**
     * Attempts all valid options for finding the help jar.  
     */
    private void loadHelp() {
        //Possible locations for the mcrew help files.
        String jarFilePath = "jar/MasterHelp.jar";
        String mcrewJarPath = "jar/McrewHelp.jar";
        String dirFilePath = "help/mcrew1/mcrew.hs";

        if (Help.loadJar(jarFilePath, "mcrew1/mcrew.hs")) {
        } else if (Help.loadJar(mcrewJarPath)) {
        } else if (Help.loadDirectory(dirFilePath)) {
        }
    }
    
    /**
     * Adds help to the frame.
     */
    private void addCSH(HelpSet hs_mcrew) 
    {
        hb_mcrew = hs_mcrew.createHelpBroker();
        //hb_mcrew = hs_mcrew.getHelpBroker();
        hb_mcrew.enableHelpKey(getRootPane(), "McrewIntro_html", hs_mcrew);
        hb_mcrew.enableHelpOnButton(JMI_help, "McrewIntro_html", hs_mcrew);
        hb_mcrew.enableHelpOnButton(aboutButton, "introduction_html", hs_mcrew);
        ActionListener helper = new CSH.DisplayHelpFromSource(hb_mcrew);

        ////System.out.println("I am in the WEPS addHelp()" + helper);
        JMI_help.addActionListener(helper);
        //contextsensitive help
        helpButton.addActionListener(new CSH.DisplayHelpAfterTracking(hs_mcrew, "javax.help.Popup", null));
        CSH.setHelpIDString(JS_bar, "mcrewMenuBar_html");//FIXME
        CSH.setHelpIDString(JM_fileOld, "mcrewMenuFile_html");
        CSH.setHelpIDString(JM_edit, "mcrewMenuEdit_html");
        CSH.setHelpIDString(JM_view, "mcrewMenuView_html");
        CSH.setHelpIDString(JM_configure, "mcrewMenuConfigure_html");
        CSH.setHelpIDString(JM_tools, "mcrewMenuTools_html");
        CSH.setHelpIDString(JM_help, "mcrewMenuHelp_html");
        CSH.setHelpIDString(JMB_main, "mcrewMenuBar_html");
        CSH.setHelpIDString(aboutButton, "mcrewHelpButton_html");
        CSH.setHelpIDString(helpButton, "mcrewInfoButton_html");
        CSH.setHelpIDString(JB_close, "mcrewCloseButton_html");
        tableObject.addCSH(hs_mcrew);
        timelineObject.addCSH(hs_mcrew);
    }
    
    /**
     * Iterates over every table in the timeline, loading each table that has been
     * changed into view and prompting the user asking if they wish to save said
     * table.
     */
    @SuppressWarnings("fallthrough")
    private boolean checkandSaveAll() {
        boolean saveSuccess = true;
        boolean continued = true;
        for (int index = 0; index < timelineObject.getNumFiles(); index++) {
            TablePanel tempTable = timelineObject.getTablePanelNoSelect(index);
            if (tempTable.table.getDataChanged()) {
                refocus(index);
            } else {
                continue;
            }
            if (tableObject.table.getDataChanged()) {
                int option = JOptionPane.showConfirmDialog(this, "Save current Management File?");
                switch (option) {
                    case JOptionPane.CANCEL_OPTION:
                        this.setVisible(true);
                        continued &= false;
                        break;
                    case JOptionPane.YES_OPTION:
                        if (!tableObject.table.checkAllConditions()) {
                            saveSuccess &= false;
                        }
                        if ((tableObject.fileName == null) || (tableObject.fileName.
                                length() == 0) || (tableObject.fileName.equals(
                                        TablePanel.sUntitledFileName))) {
                            saveCurrentAs();
                        } else {
                            saveCurrent();
                        }
                        saveSuccess &= tableObject.saveSuccess;
                        break;
                    case JOptionPane.NO_OPTION:
                        break;
                }
            }
        }
        return saveSuccess && continued;
    }
    /**
     * Iterates through all the tables in the timeline and clears all of the data
     * contained within them to free up memory.
     */
    public void clearAndDispose()
    {
        for(int index = 0; index < timelineObject.getNumFiles(); index ++)
        {
            TablePanel tempTable = timelineObject.getTablePanelNoSelect(index);
            tempTable.cleanup();
        }
    }

    /**
     * Receives a data changed event, and increments or decrements the counter for
     * number of tables changed based on true or false.
     * @param input - true if data is changed, false to decrement
     */
    public void dataChange(boolean input) {
        if (input) {
            dataChanged++;
        } else {
            dataChanged--;
        }
    }
    
    /**
     * Passes the waiting event to the proper table.
     */
    public boolean setWaiting(boolean input) {
        try {
            tableObject.setWaiting(input);
            return true;
        } catch(NullPointerException e) {
            return false;
        }
    }
    
    /**
     * Returns the label state of the active table.
     */
    public boolean getLabelState() {
        return tableObject.getLabelState();
    }
    
    /**
     * Returns the absolute path to the file currently open in the table that
     * currently holds focus.
     */
    public String getAbsoluteFileName() {
        return tableObject.absFileName;
    }
    
    /**
     * Returns the name of the file currently open in the table that currently 
     * holds focus.
     */
    public String getFileName() {
        return tableObject.fileName;
    } 
    
    /**
     * Makes visible/invisible all components which only exist in full timeline
     * mode or only in single file mode, moves components to their proper location
     * that are shared between the two.
     */
    private void singleFileMode()
    {
        //Set all timeline components invisible.
        JM_file.setVisible(false);
        JM_fileOld.setVisible(true);
        timelineContainer.setVisible(false);
        JP_toolBar.setVisible(false);
        
        //Move necessary buttons back to MCREW.
        tableObject.JTB_main.add(aboutButton);
        tableObject.JTB_main.add(helpButton);
        tableObject.JTB_main.add(JB_close);
        JM_fileOld.add(JMI_print);
        JM_fileOld.add(JMI_exit);
    }
    
    /**
     * Receives date changes, and fire a repaint for both the table and the timeline,
     * as the date change is the only operation that will significantly affect
     * both the table and the timeline.
     */
    public void dateChange(Object origin)
    {
        if((origin instanceof TimelinePanel))
        {
            if(MCREWConfig.autosort) 
            {
                for(int index = 0; index < timelineObject.getNumFiles(); index ++)
                {
                    timelineObject.getTablePanelNoSelect(index).SortJMI_actionPerformed(null);
                }
            }
        }
        else
        {
            timelineObject.recalibrateDates();
        }
        timelineObject.repaint();
        tableObject.repaint();
    }
    
    /**
     * Passes the table the given property change listener, so that events will
     * be properly relayed between MCREW and WEPS.
     */
    @Override
    public void addPropertyChangeListener(PropertyChangeListener l) 
    { 
        for(int index = 0; index < timelineObject.getNumFiles(); index ++)
        {
            timelineObject.getTablePanelNoSelect(index).addPropertyChangeListener(l);
        }
    }
    
    public void addPropertyChangeListenerToTablePanel (String prop, PropertyChangeListener l) {
        tableObject.addPropertyChangeListener(prop, l);
    }
    
    /**
     * Calls a translator from WEPP .json man files to NRCS XML .skel files
     * @param evt
     * @param singleFileOnly 
     */
    @Override
    protected void JSONtoMAN_actionPreformed(ActionEvent evt, boolean singleFileOnly) {
        // initialize converter if not yet
        if(sMC == null) sMC = new SkelManConverter(this);
        
        sMC.ManToNRCS_XML(evt, singleFileOnly);
    } 
    
    @Override
    protected void JSONtoMAN_rec_actionPreformed(ActionEvent evt) {
        // initialize converter if not yet
        if(sMC == null) sMC = new SkelManConverter(this);
        
        sMC.WEPP_jsonToSkel(evt);
    }
    
    @Override
    protected void JSONtoMAN_selectIndividualActionPerformed(java.awt.event.ActionEvent evt) {
        // Initialize if not yet
        if(sMC == null) sMC = new SkelManConverter(this);
        
        sMC.Man_WEPP_To_Man_WEPS(evt, false);
    }
    
    @Override
    protected void JSONtoMAN_recursiveActionPerformed(java.awt.event.ActionEvent evt) {      
        // Initialize if not yet
        if(sMC == null) sMC = new SkelManConverter(this);
        
        sMC.WEPP_jsonToWEPS_managment(evt);
    }
    
    @Override
    protected void SkelToManRec_actionPerformed(ActionEvent evt)
    {
        if(sMC == null) sMC = new SkelManConverter(this);
        sMC.SkelToManRec_actionPerformed(evt);
    }

    @Override
    protected void ManToSkelRec_actionPerformed(ActionEvent evt)
    {
        if(sMC == null) sMC = new SkelManConverter(this);
        sMC.ManToSkelRec(evt);
        
    }
    
    @Override
    protected void ManToSkelNonRec_actionPerformed(ActionEvent evt)
    {
        if(sMC == null) sMC = new SkelManConverter(this);
        sMC.ManToSkelNonRec(evt);
    }
    
    
    @Override
    protected void ManToSkelJMI_actionPerformed(ActionEvent evt, boolean singleFileOnly)
    {
        if(sMC == null) sMC = new SkelManConverter(this);
        sMC.ManToSkel(evt, singleFileOnly);
    }

    @Override
    protected void SkelToManJMI_actionPerformed(ActionEvent evt, boolean singleFileOnly)
    {
        if(sMC == null) sMC = new SkelManConverter(this);
        sMC.SkelToMan(evt, singleFileOnly);
    }
    
    public static void main(String[] args)
    {
        String mainConfig = "";
        String fileOrDir = "";
        for(int index = 0; index < args.length; index ++)
        {
            if(args[index].trim().equals("-cfg"))
            {
                index ++;
                mainConfig = args[index].trim();
            }
            if(args[index].trim().equals("-f")) 
            {
                index ++;
                fileOrDir = args[index];
            }
        }
        
        if(!mainConfig.equals(""))
        {
            mainConfig = Util.parse(mainConfig);
            TFile mainConfigFile = new TFile(mainConfig).getCanOrAbsFile();
            String userConfig = About.getUserWeps().getAbsolutePath() + "/" + mainConfigFile.getName();
            ConfigData.getDefault().load(mainConfigFile, new TFile(userConfig).getCanOrAbsFile());
        }
        String masterJar = "jar/MasterHelp.jar";
        Help.loadJar(masterJar);
        MCREWConfig.initialize(ConfigData.getDefault());
        System.setProperty("line.separator", "\n"); // make file line separator unix compatible
        // create an instance of mcrew
        
        String projDir = null;
        String[] fA = new String[0];
        if(!fileOrDir.equals(""))
        {
            TFile dest = new TFile(fileOrDir);
            if(dest.isDirectory()) projDir = dest.getAbsolutePath();
            else
            {
                fA = new String[1];
                fA[0] = dest.getAbsolutePath();
                projDir = dest.getParentFile().getAbsolutePath();
            }
        }
        
        if(projDir == null)
        {
            projDir = ConfigData.getDefault().getData(ConfigData.CurrentProj);
            if(projDir == null)
            {
                projDir = About.getUserDocuments().getAbsolutePath();
                int rtnVal = JOptionPane.showOptionDialog(null,
                        "MCREW needs a default directory location\n"
                        + "specified for it to store temporary files\n"
                        + "and to place save files.\n\n"
                        + "By default, this location is:\n"
                        + projDir,
                        "Warning (W-303)",
                        JOptionPane.DEFAULT_OPTION,
                        JOptionPane.WARNING_MESSAGE,
                        null,
                        new String[]{"Select", "Default"},
                        "Select");
                if(rtnVal == 0)
                {
                    WepsFileChooser2 wpc = new WepsFileChooser2(WepsFileTypes2.Dir, ".", WepsFileChooser2.Action.Select);
                    wpc.enableFolderButtons();
                    wpc.enableDbButton(false);
                    wpc.enableCfgDefLocButton(false);
                    wpc.setCurrentDirectory(projDir);
                    wpc.homeToolTip(wpc);
                    if (wpc.showDialog(null) == TFileChooser.APPROVE_OPTION) 
                    {
                        try 
                        {
                            TFile selProj = new TFile(wpc.getSelectedFile().getCanonicalPath());
                            projDir = selProj.getAbsolutePath();
                        } 
                        catch (IOException e) {}
                    }
                }
                
                ConfigData.getDefault().setData(ConfigData.CurrentProj, projDir);
                ConfigData.getDefault().save();
            }
        }
        MCREWWindow wind = new MCREWWindow("MCREW", projDir, fA, ConfigData.getDefault());
       
        wind.standaloneFlg = true;

        /* Disable Open copy of Template and Save as Template menu options when running standalone */
        wind.JMI_openCT.setEnabled(false);
        //mp.SaveAsTJMI.setEnabled(false);
        //When running stand-alone,the return arrow should not be displayed
        wind.JB_close.setVisible(false);
    }
}
