package usda.weru.mcrew;

import com.klg.jclass.table.JCTableDataEvent;
import com.klg.jclass.table.JCTableDataListener;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

import de.schlichtherle.truezip.file.TFile;
import de.schlichtherle.truezip.file.TFileReader;
import de.schlichtherle.truezip.file.TFileWriter;
import de.schlichtherle.truezip.file.TVFS;
import de.schlichtherle.truezip.fs.FsSyncException;

import java.awt.EventQueue;
import java.awt.HeadlessException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.Vector;
import java.util.logging.Level;
import javax.help.CSH;
import javax.help.HelpBroker;
import javax.help.HelpSet;
import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToggleButton;
import javax.swing.MenuElement;
import javolution.context.Context;
import org.apache.log4j.Logger;
import org.openide.util.Exceptions;
import usda.weru.resources.Resources;
import usda.weru.util.About;
import usda.weru.util.AboutDialog;
import usda.weru.util.Help;
import usda.weru.util.Util;
import usda.weru.util.WepsFileChooser;
import usda.weru.util.WepsFileTypes;
import usda.weru.util.WepsMessage;
import usda.weru.util.WepsMessageDialog;
import usda.weru.util.WepsMessageLog;
import usda.weru.weps.Email;
import usda.weru.weps.RunFileData;

/**
 * This is the main classs for the MCREW (Management/Crop Rotation Editor for WEPS)
 * and will serve as the entry point for it. It also sets up
 * the management and has all the functions associated with it.
 *
 * The visual components are derived from Mcrew_b.java class author : Sudhir Kaul, Sada, Manmohan
 * date : Dec 2004
 */
public class Mcrew extends usda.weru.mcrew.gui.Mcrew_n implements ActionListener, ItemListener, JCTableDataListener {

    private static final long serialVersionUID = 1L;

    private static final Logger LOGGER = Logger.getLogger(Mcrew.class);
    /**
     * Flag that tells whether data was modified on the crop or operation dialog screens or the main
     * MCREW table so that we can save the new data if needed.
     */
    private boolean dataChanged = false;
    /**
     * This flag is not being used currently.
     */
    private String refreshMcrewScreen = "false";
    /**
     * Use this flag when running MCREW in standalone mode.
     */
    private boolean standaloneFlg = false;

    /**
     * This flag tells if the label was set for the MCREW screen.
     */
    private boolean c_labelState = false;

    //This flag is used to see if a save has been made successfully or not
    //and then whether to close the Mcrew Window-ExitJMI_actionPerformed() method.
    /**
     * Tells whether the modified data from crop, operation or main MCREW table was saved
     * successfully in the underlying datastructure.
     */
    public boolean saveSuccess = false;
    /**
     * This string tells us the whether the file to be saved has a title or not.
     */
    public static final String sUntitledFileName = "Untitled";
    /**
     * This is the version of this software & not of the man files
     */
    public static final String sVersionLine = "Version: 1.1";
    /**
     * Sets the default extension for the files that are saved in.
     */
    public static final String sDefaultFileExtension = XMLConstants.sWepsFileExtension;
    /**
     * These constants allow convertRec() method to differentiate between the 2 types of
     * conversions. Here - WEPS Management file to Skeleton files.
     */
    public static final int MAN2SKELREC = 0;
    /**
     * These constants allow convertRec() method to differentiate between the 2 types of
     * conversions. Here - Skeleton files to WEPS Management files. Similar to the above on .. but
     * just opposite way conversion.
     */
    public static final int SKEL2MANREC = 1;
    /**
     * These two directory names are used in the recursive conversion of skeleton files to WEPS
     * Management files and vice versa. This is the source directory tfrom where we can get the
     * files for conversion.
     */
    private String sourceDirName = null;
    /**
     * Directory name is used in recursive conversion of skeleton files to WEPS Management file and
     * vice versa. This is the target directory that stores the converted files.
     */
    private String targetDirName = null;
    /**
     * Directory path where the files are saved.
     */
    private String savePath = "";
    /**
     * Absolute Template directory path
     */
    public String saveTemplatePath;
    /**
     * Absolute Project directory path
     */
    private String projectDir = null;
    /**
     * Name of the present open Management file in Mcrew
     */
    public String fileName = null;
    /**
     * Name of the absolute path of the Present SAVED Management file in Mcrew so that this can be
     * sent to AuxPanel
     */
    public String absFileName = null;
    /**
     * Name of the absolute path of the present Management file OPENED in MCREW
     */
    public String filePathName = null;
    /**
     * This will be the instance of the data connected to this mcrew
     */
    public ManageData data;
    /**
     * This shows the column config frame
     */
    private ConfigFrame configFrame;
    /**
     * Table object associated with the main MCREW screen and the subsequent Crop & operation dialog
     * screens that hold the data in various rows.
     */
    Table table;
    /**
     * Notes related to Weps manageent file go here in the text area held by this dialog box which
     * can be pulled any time and modifications made here are saved for future retrival.
     */
    public NotesMan notes;
    /**
     * 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 = 630;
    /**
     * Minimun Height of the main MCREW screen. Cannot reduce the scrren height below this height
     * even if done manually.
     */
    public static final int MIN_HEIGHT = 380;
    /**
     * 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;
    //the table view of the data ...this is where everything happens
    private String columnConfig = "My Config Frame";
    /**
     * Popup is the default popup menu which is shown on single /multiple row selections.
     */
    private JPopupMenu popup;

    /**
     *
     * @return
     */
    public JPopupMenu getPopup() {
        return popup;
    }
    /**
     * datePopup is the default popup menu which is shown on single /multiple row selections in the
     * date column of the main MCREW table.
     */
    private JPopupMenu datePopup;

    /**
     *
     * @return
     */
    public JPopupMenu getDatePopup() {
        return datePopup;
    }
    /**
     * Popup for operation cell to get to the operation dialog box or accessing the functions
     * provided for the operation cell in main MCREW screen. This popup is the default popup menu
     * which is shown on single /multiple row selections in the operation column of the main MCREW
     * table.
     */
    private JPopupMenu operationCellPopup;

    /**
     *
     * @return
     */
    public JPopupMenu getOperationPopup() {
        return operationCellPopup;
    }
    /**
     * Popup for crop cell to get to the crop dialog box or accessing the functions provided for the
     * crop cell in main MCREW screen. This popup is the default popup menu which is shown on single
     * /multiple row selections in the crop column of the main MCREW table.
     */
    private JPopupMenu cropCellPopup;

    /**
     *
     * @return
     */
    public JPopupMenu getCropPopup() {
        return cropCellPopup;
    }
    //column config string 111010000 is the default
    //private String years;
    /**
     * Popup for tillage cell of a crop to access the update functions for the tillage operation in
     * main MCREW screen. This popup is the default popup menu which is shown on single row
     * selections in the tillage column of the main MCREW table.
     */
    private JPopupMenu tillageCellPopup;

    /**
     *
     * @return
     */
    public JPopupMenu getTillagePopup() {
        return tillageCellPopup;
    }
    /**
     * These vectors are created when the requirement to show combined menus arise. i.e for eg When
     * a complete row(s) is(are) selected and the user right clicks in the operation column, then it
     * should display a combination of operationCellPopup and operationPopup. The combination of
     * thse two menu have to be created every time, or after the first time, the individual popup or
     * operationCellPopup will show nothing Also, showing one menu directly below the other will not
     * work either.
     */
    private Vector<MenuElement> popupVec;

    /**
     *
     * @return
     */
    public List<MenuElement> getPopupElements() {
        return popupVec;
    }
    /**
     * Holds all the pop-up options for the right click event on the cells in date column
     */
    private Vector<MenuElement> datePopupVec;

    /**
     *
     * @return
     */
    public List<MenuElement> getDatePopupElements() {
        return datePopupVec;
    }
    /**
     * Holds all the pop-up options for the right click event on the cells in operation column
     */
    private Vector<MenuElement> operationCellPopupVec;

    /**
     *
     * @return
     */
    public List<MenuElement> getOperationPopupElements() {
        return operationCellPopupVec;
    }
    /**
     * Holds all the pop-up options for the right click event on the cells in crop column
     */
    private Vector<MenuElement> cropCellPopupVec;

    /**
     *
     * @return
     */
    public List<MenuElement> getCropPopupElements() {
        return cropCellPopupVec;
    }
    /**
     * Holds all the pop-up options for the right click event on the cells in tillage column
     */
    private Vector<MenuElement> tillageCellPopupVec;

    /**
     *
     * @return
     */
    public List<MenuElement> getTillagePopupElements() {
        return tillageCellPopupVec;
    }

    private MouseListener popupListener;
    private boolean calibIcon = false;
    /**
     * Prefixe indicating parent application.
     */
    public static final String MCR = "MCREW-";
    /**
     * Prefixing to indicate parent object's window close event.
     */
    public static final String WindowClosing = MCR + "WindowClosing";
    /**
     * Prefixing to indicate parent object's window is open
     */
    public static final String WindowOpen = MCR + "WindowOpen";
    /**
     * Prefixing to indicate to which parent does the file belong.
     */
    public static final String FileName = MCR + "FileName";

    // variables for help system
    private HelpSet hs_mcrew;
    /**
     * 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 Vector<Mcrew>();
    }
    static Vector<Mcrew> openMcrewWindows;

    /**
     *
     * @return
     */
    public static boolean isOpen() {
        return Mcrew.openMcrewWindows.size() > 0;
    }

    /**
     * Default constructor that initializes the object that holds the data, adds pop-up menu, loads
     * tooltips file, adds help to the application, etc.
     */
    public Mcrew() {
        super(); //call to super mcrew_b       
        openMcrewWindows.add(this);
        data = new ManageData();
        data.addTableDataListener(this);

        JTF_rotYears.setText(Integer.toString(data.getRotationYears()));

        addPopupMenu();
        configFrame = new ConfigFrame(columnConfig);
        /*
         mcrew.configFrame = new ConfigFrame(mcrew.columnConfig);
         */
        Util.loadToolTips((Container) this, new TFile("mcrew_cfg", "mcrewtooltips.cfg"));
        addHelp(); //call help method
    }

    /**
     * Single argument constructor that initializes the object that holds the data, adds pop-up
     * menu, loads tooltips file, adds help to the application, etc. Also puts the title for the
     * aplication.
     *
     * @param sTitle The title string used by the application for naming the screen.
     */
    public Mcrew(String sTitle) {
        // not implemented right now
        this();
        setTitle(sTitle);
        //auxMCREWLabel.addPropertyChangeListener(auxPanelListener);
        //Setting the Icon Image in the title bar
        super.setIconImage(About.getWeruIconImage());
    }

    /**
     * Single argument constructor that initializes the object that holds the data, adds pop-up
     * menu, loads tooltips file, adds help to the application, etc. Also puts the title for the
     * aplication.
     *
     * @param title The title string used by the application for naming the screen.
     * @param fileName The .MAN or .XML file from which the the data needs to be pulled in the
     * application.
     * @param cd
     * @param projDir Path that holds all the projects.
     */
    public Mcrew(String title, String fileName, String projDir, usda.weru.util.ConfigData cd) {
        // create an instance of mcrew
        this(title);

        //Awful hack to prevent the null source error from a stray MouseEvent while starting.
        /*try {
         Thread.sleep(100);
         }
         catch (InterruptedException ex) {
         }*/
        //Set the projectDir value to projDir. If MCREW is called with NO management file
        //[i.e. fileName==null] this will serve as the current directory path for the file choosers - by Neha
        projectDir = projDir;
        //fileName = mcrewConfigFile;
        //System.out.println("Mcrew called from WEPS with filename: "+ fileName);
        //change the file Name displayed
        changeRotFileName(fileName);

        TFile filedir = new TFile(fileName);
        absFileName = filedir.getAbsolutePath();
        //System.out.println("Mcrew:Mcrew():absFilename:"+absFileName);
        /* ConfigData holds all static data such as data from
         * dataconfig.xml and all Meta data
         */
        //ConfigData.initialize("weps_mcrew_cfg");
        // Changed by Neha - The Mcrew Config file is not hard-coded.
        // Instead we can set it in the Configuration screen.
        ConfigData.initialize(cd);
        //If the mcrew_cfg directory is not found, then return to weps.
        if (ConfigData.getReturnFlag() == true) {
            LOGGER.warn("Mcrew Data Config File Not Found.");
            JOptionPane.showMessageDialog(null, "Mcrew Data Config File Not Found." + "\nPlease load the mcrew_cfg Directory",
                    "Warning", JOptionPane.WARNING_MESSAGE);
            c_labelState = true;
            return;
        }
        // here we create the table
        table = new Table(this);
        table.setVisible(false);
        table.setLocation(0, 0);

        Dimension mdem = getSize();
        table.setSize(mdem.width - 20, mdem.height - 70);
        JP_main.add(table);
        this.setMinimumSize(new Dimension(table.getWidth(), table.getHeight()));

        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                setVisible(true);
            }

        });

        c_guiViews = new ArrayList<String>();
        c_cmis = new HashMap<String, JCheckBoxMenuItem>();
        c_tbs = new HashMap<String, JToggleButton>();

        //Setup the views defined for the table.
        for (final ConfigData.TableView view : ConfigData.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);
                c_cmis.put(view.getName(), cmi);
            }

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

                tb = new JToggleButton(new ImageIcon(Resources.getImage(view.getToolbarImage())));
                JTB_view.add(tb);
                c_tbs.put(view.getName(), tb);
            }

            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) {
                        handleViewToggle(view.getName(), cmi2.isSelected());
                    }
                });
            }

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

        }
        
        addHelp();
        //Init to the default
        table.toggleTableView("default", true);
        table.setVisible(true);

        calibIcon = ConfigData.getInitCalibColumnState();
        //here we create the instance of notes.
        notes = new NotesMan("Management File Notes", data, this);

        if ((fileName == null) || (fileName.length() == 0)) {
            return;
        }
        de.schlichtherle.truezip.file.TFile selectedFile = new TFile(fileName);
        if (selectedFile.exists()) {
            try {
                String fileDir = selectedFile.getCanonicalPath();
                projectDir = selectedFile.getParent();
                //System.out.println("Mcrew:Mcrew() " + " project Dir = " + projectDir);
                openFile(fileDir); // call open file method here
                table.checkData();
                //dataChanged = true;
            } catch (IOException e) {
                System.err.println("Error in opening file " + fileName);
            }
        }
        if ((projectDir == null) || (projectDir.length() == 0)) {
            /* Disable Open copy of Template and Save as Template menu options	 */
            JMI_openCT.setEnabled(false);
            //SaveAsTJMI.setEnabled(false);
        }
    }
    private List<String> c_guiViews;
    private Map<String, JCheckBoxMenuItem> c_cmis;
    private Map<String, JToggleButton> c_tbs;

    private void handleViewToggle(String name, boolean state) {
        JCheckBoxMenuItem cmi = c_cmis.get(name);
        JToggleButton tb = c_tbs.get(name);

        table.toggleTableView(name, state);

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

        if (tb != null) {
            tb.setSelected(state);
        }
        this.setMinimumSize(new Dimension(table.getWidth(), table.getHeight()));
    }

    /**
     *
     * @return
     */
    public boolean getLabelState() {
        return c_labelState;
    }

    /**
     * In case running a standalone version of the application, this becomes the starting point of
     * the application.
     *
     * @param args A command line array of arguments such as fille name, screen title, etc.
     */
    public static void main(String[] args) {
        System.setProperty("line.separator", "\n"); // make file line separator unix compatible
        // create an instance of mcrew
        Mcrew mp = new Mcrew();

        mp.standaloneFlg = true;

        mp.data = new ManageData();

        //ConfigData holds all static data such as data from
        //mcrewconfig.xmland all Meta data
        ConfigData.initialize();

        // here we create the table
        mp.table = new Table(mp.data);
        mp.table.setLocation(0, 0);

        Dimension mdem = mp.getSize();
        mp.table.setSize(mdem.width - 20, mdem.height - 70);
        mp.JP_main.add(mp.table);
        mp.setVisible(true);

        /* Disable Open copy of Template and Save as Template menu options when running standalone */
        mp.JMI_openCT.setEnabled(false);
        //mp.SaveAsTJMI.setEnabled(false);
        //When running stand-alone,the return arrow should not be displayed
        mp.JB_close.setVisible(false);
    }
    private javax.swing.JMenuItem popCutJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem popCopyJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem popPasteJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem popDeleteJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem popUndoDeleteJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem popInsertJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem popInsertOperationJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem popInsertFileJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem popInsertFileDateAdjustedJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem popAddRotationDateAdjustedJMI = new javax.swing.JMenuItem();

    private javax.swing.JMenuItem popDrillDownScreenJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem popAdjustDateJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem popSetDateJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem setDateJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem calendarDateJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem dateChangeDateJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem dateIncrementYearJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem dateDecrementYearJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem dateIncrementMonthJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem dateDecrementMonthJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem dateIncrementWeekJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem dateDecrementWeekJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem dateIncrementDayJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem dateDecrementDayJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem operationScreenJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem operationNotesJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem addChangeOperationJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem cropScreenJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem addChangeCropJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem cropNotesJMI = new javax.swing.JMenuItem();
    // Menu items for popup for "Tillage direction" cells
    private javax.swing.JMenuItem setDirectionJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem adjustDirectionJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem setTozeroJMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem setTo45JMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem setTo90JMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem incrementBy15JMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem decrementBy15JMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem incrementBy45JMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem decrementBy45JMI = new javax.swing.JMenuItem();
    private javax.swing.JMenuItem changeBy90JMI = new javax.swing.JMenuItem();

    /**
     *
     * @param cursor
     */
    @Override
    public void setCursor(Cursor cursor) {
        super.setCursor(cursor);
        Table temp = table;
        if (temp != null) {
            temp.setCursor(cursor);
        }
    }

    /**
     *
     * @param wait
     */
    public void setWaiting(boolean wait) {
        if (wait) {
            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        } else {
            setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        }
    }

    private void addPopupMenu() {
        MenuElement[] menuElements;

        popup = new JPopupMenu();
        datePopup = new JPopupMenu();
        // operationPopup = new JPopupMenu();
        // cropPopup = new JPopupMenu();
        operationCellPopup = new JPopupMenu();
        cropCellPopup = new JPopupMenu();
        tillageCellPopup = new JPopupMenu();

        popupVec = new Vector<MenuElement>();
        datePopupVec = new Vector<MenuElement>();
        //operationPopupVec = new Vector();
        //cropPopupVec = new Vector();
        operationCellPopupVec = new Vector<MenuElement>();
        cropCellPopupVec = new Vector<MenuElement>();
        tillageCellPopupVec = new Vector<MenuElement>();

        SymAction lSymAction = new SymAction();

        popSetDateJMI.setText("Set Date");
        popSetDateJMI.setActionCommand("Set Date");
        popSetDateJMI.addActionListener(lSymAction);
        popup.add(popSetDateJMI);

        popAdjustDateJMI.setText("Adjust Date");
        popAdjustDateJMI.setActionCommand("Adjust Date");
        popAdjustDateJMI.addActionListener(lSymAction);
        popup.add(popAdjustDateJMI);

        popInsertJMI.setText("Insert Blank Row");
        popInsertJMI.setActionCommand("Insert Blank Row");
        popInsertJMI.addActionListener(lSymAction);
        popup.add(popInsertJMI);

        popInsertOperationJMI.setText("Insert Operation");
        popInsertOperationJMI.setActionCommand("Insert Operation");
        popInsertOperationJMI.addActionListener(lSymAction);
        popup.add(popInsertOperationJMI);

        popAddRotationDateAdjustedJMI.setText("Insert Rotation");
        popAddRotationDateAdjustedJMI.setActionCommand("Add Rotation");
        popAddRotationDateAdjustedJMI.addActionListener(lSymAction);
        popup.add(popAddRotationDateAdjustedJMI);

        popInsertFileDateAdjustedJMI.setText("Insert Management");
        popInsertFileDateAdjustedJMI.setActionCommand("Insert File");
        popInsertFileDateAdjustedJMI.addActionListener(lSymAction);
        popup.add(popInsertFileDateAdjustedJMI);

        //only show if not in NRCS mode
        if (!usda.weru.util.ConfigData.getDefault().isCompatibilityNRCS()) {
            popInsertFileJMI.setText("Insert Management (Unadjusted)");
            popInsertFileJMI.setActionCommand("Insert File (Unadjusted)");
            popInsertFileJMI.addActionListener(lSymAction);

            popup.add(popInsertFileJMI);
        }

        // Now follws multiple row operations
        popCutJMI.setText("Cut Row(s)");
        popCutJMI.setActionCommand("Cut ");
        popCutJMI.addActionListener(lSymAction);
        popup.add(popCutJMI);

        popCopyJMI.setText("Copy Row(s)");
        popCopyJMI.setActionCommand("Copy");
        popCopyJMI.addActionListener(lSymAction);
        popup.add(popCopyJMI);

        popPasteJMI.setText("Paste Row(s)");
        popPasteJMI.setActionCommand("Paste");
        popPasteJMI.addActionListener(lSymAction);
        popup.add(popPasteJMI);

        popDeleteJMI.setText("Delete Row(s)");
        popDeleteJMI.setActionCommand("Delete");
        popDeleteJMI.addActionListener(lSymAction);
        popup.add(popDeleteJMI);

        popUndoDeleteJMI.setText("Undo Delete Row(s)");
        popUndoDeleteJMI.setActionCommand("Undo Ddelete");
        popUndoDeleteJMI.addActionListener(lSymAction);
        popup.add(popUndoDeleteJMI);
        setUndoDeleteStatus(false);

        menuElements = popup.getSubElements();
        popupVec.addAll(Arrays.asList(menuElements));

        /* date popup menu optipns */
        calendarDateJMI.setText("Calendar Date");
        calendarDateJMI.setActionCommand("Calender Date");
        calendarDateJMI.addActionListener(lSymAction);
        datePopup.add(calendarDateJMI);

        setDateJMI.setText("Set Date");
        setDateJMI.setActionCommand("Set Date");
        setDateJMI.addActionListener(lSymAction);
        datePopup.add(setDateJMI);

        dateChangeDateJMI.setText("Adjust Date");
        dateChangeDateJMI.setActionCommand("Change Date");
        dateChangeDateJMI.addActionListener(lSymAction);
        datePopup.add(dateChangeDateJMI);

        dateIncrementYearJMI.setText("Increment Year");
        dateIncrementYearJMI.setActionCommand("Increment Year");
        dateIncrementYearJMI.addActionListener(lSymAction);
        datePopup.add(dateIncrementYearJMI);

        dateDecrementYearJMI.setText("Decrement Year");
        dateDecrementYearJMI.setActionCommand("Decrement Year");
        dateDecrementYearJMI.addActionListener(lSymAction);
        datePopup.add(dateDecrementYearJMI);

        dateIncrementMonthJMI.setText("Increment Month");
        dateIncrementMonthJMI.setActionCommand("Increment Month");
        dateIncrementMonthJMI.addActionListener(lSymAction);
        datePopup.add(dateIncrementMonthJMI);

        dateDecrementMonthJMI.setText("Decrement Month");
        dateDecrementMonthJMI.setActionCommand("Decrement Month");
        dateDecrementMonthJMI.addActionListener(lSymAction);
        datePopup.add(dateDecrementMonthJMI);

        dateIncrementWeekJMI.setText("Increment by week");
        dateIncrementWeekJMI.setActionCommand("Increment by week");
        dateIncrementWeekJMI.addActionListener(lSymAction);
        datePopup.add(dateIncrementWeekJMI);

        dateDecrementWeekJMI.setText("Decrement by week");
        dateDecrementWeekJMI.setActionCommand("Decrement by week");
        dateDecrementWeekJMI.addActionListener(lSymAction);
        datePopup.add(dateDecrementWeekJMI);

        dateIncrementDayJMI.setText("Increment Day");
        dateIncrementDayJMI.setActionCommand("Increment Day");
        dateIncrementDayJMI.addActionListener(lSymAction);
        datePopup.add(dateIncrementDayJMI);

        dateDecrementDayJMI.setText("Decrement Day");
        dateDecrementDayJMI.setActionCommand("Decrement Day");
        dateDecrementDayJMI.addActionListener(lSymAction);
        datePopup.add(dateDecrementDayJMI);

        menuElements = datePopup.getSubElements();
        datePopupVec.addAll(Arrays.asList(menuElements));

        /* operation and crop cell popup menu items */
        addChangeOperationJMI.setText("Change/Select Operation");
        addChangeOperationJMI.setActionCommand("Add/Change Operation");
        addChangeOperationJMI.addActionListener(lSymAction);
        operationCellPopup.add(addChangeOperationJMI);

        operationScreenJMI.setText("Operation Drill-down Screen");
        operationScreenJMI.setActionCommand("Operation Drill-down Screen");
        operationScreenJMI.addActionListener(lSymAction);
        operationCellPopup.add(operationScreenJMI);
        
        operationNotesJMI.setText("View Operation Notes");
        operationNotesJMI.setActionCommand("View Operation Notes");
        operationNotesJMI.addActionListener(lSymAction);
        operationCellPopup.add(operationNotesJMI);

        menuElements = operationCellPopup.getSubElements();
        operationCellPopupVec.addAll(Arrays.asList(menuElements));

        addChangeCropJMI.setText("Change/Select Crop");
        addChangeCropJMI.setActionCommand("Add/Change Crop");
        addChangeCropJMI.addActionListener(lSymAction);
        cropCellPopup.add(addChangeCropJMI);

        cropScreenJMI.setText("Crop Drill-down Screen");
        cropScreenJMI.setActionCommand("Crop Drill-down Screen");
        cropScreenJMI.addActionListener(lSymAction);
        cropCellPopup.add(cropScreenJMI);
        
        cropNotesJMI.setText("View Crop/Residue Notes");
        cropNotesJMI.setActionCommand("View Crop/Residue Notes");
        cropNotesJMI.addActionListener(lSymAction);
        cropCellPopup.add(cropNotesJMI);

        menuElements = cropCellPopup.getSubElements();
        cropCellPopupVec.addAll(Arrays.asList(menuElements));

        //datePopup.setText("Date functions");
        //popup.add(datePopup);
        /* Tillage Direction popup menu items - neha */
        setDirectionJMI.setText("Set Direction");
        setDirectionJMI.setActionCommand("Set Direction");
        setDirectionJMI.addActionListener(lSymAction);
        tillageCellPopup.add(setDirectionJMI);

        adjustDirectionJMI.setText("Adjust Direction");
        adjustDirectionJMI.setActionCommand("Adjust Direction");
        adjustDirectionJMI.addActionListener(lSymAction);
        tillageCellPopup.add(adjustDirectionJMI);

        setTozeroJMI.setText("Set to 0 deg");
        setTozeroJMI.setActionCommand("Set to 0 deg");
        setTozeroJMI.addActionListener(lSymAction);
        tillageCellPopup.add(setTozeroJMI);

        setTo45JMI.setText("Set to 45 deg");
        setTo45JMI.setActionCommand("Set to 45 deg");
        setTo45JMI.addActionListener(lSymAction);
        tillageCellPopup.add(setTo45JMI);

        setTo90JMI.setText("Set to 90 deg");
        setTo90JMI.setActionCommand("Set to 90 deg");
        setTo90JMI.addActionListener(lSymAction);
        tillageCellPopup.add(setTo90JMI);

        incrementBy15JMI.setText("Increment 15 deg");
        incrementBy15JMI.setActionCommand("Increment 15 deg");
        incrementBy15JMI.addActionListener(lSymAction);
        tillageCellPopup.add(incrementBy15JMI);

        decrementBy15JMI.setText("Decrement 15 deg");
        decrementBy15JMI.setActionCommand("Decrement 15 deg");
        decrementBy15JMI.addActionListener(lSymAction);
        tillageCellPopup.add(decrementBy15JMI);

        incrementBy45JMI.setText("Increment 45 deg");
        incrementBy45JMI.setActionCommand("Increment 45 deg");
        incrementBy45JMI.addActionListener(lSymAction);
        tillageCellPopup.add(incrementBy45JMI);

        decrementBy45JMI.setText("Decrement 45 deg");
        decrementBy45JMI.setActionCommand("Decrement 45 deg");
        decrementBy45JMI.addActionListener(lSymAction);
        tillageCellPopup.add(decrementBy45JMI);

        changeBy90JMI.setText("Change by 90 deg");
        changeBy90JMI.setActionCommand("Change by 90 deg");
        changeBy90JMI.addActionListener(lSymAction);
        tillageCellPopup.add(changeBy90JMI);

        menuElements = tillageCellPopup.getSubElements();
        tillageCellPopupVec.addAll(Arrays.asList(menuElements));

        popupListener = new PopupListener();
        this.addMouseListener(popupListener);
    }

    /**
     * This method sets the rotaion year in the frame from the management data Changes the Rotation
     * File Name displayed and adjusts the scroll bar accordingly
     *
     * @param fileName The new filename to be used.
     */
    public void changeRotFileName(String fileName) {
        filePathName = fileName;
        updateRotFileName();
        changes.firePropertyChange(RunFileData.ManageFile, null, new TFile(fileName).getPath());
    }

    /**
     *
     */
    public void updateRotFileName() {
        String text = "";
        if (dataChanged) {
            text = filePathName + "  (Modified)";
            JL_rotation2.setForeground(Color.BLUE);
        } else {
            text = filePathName;
            JL_rotation2.setForeground(Color.BLACK);
        }
        JL_rotation2.setText(text);
    }

    /**
     *
     * @param changed
     */
    public void setDataChanged(boolean changed) {
        dataChanged = changed;

        //Cheating, but we only allow one mcrew open at a time.
        if (openMcrewWindows.isEmpty()) {
            return;
        }
        Mcrew m = openMcrewWindows.firstElement();
        if (m != null) {
            m.updateRotFileName();
        }
    }

    /**
     * This method sends the new rotation year to the data
     *
     * @param yrs The new year to be set.
     */
    public void changeRotYears(String yrs) {
        //local cache to try and work around rare threading issues
        ManageData temp = data;
        if (temp == null) {
            return;
        }
        try {
            int old = temp.getRotationYears();
            int years = new Integer(yrs);
            if (years != old) {
                temp.setRotationYears(years);
                setDataChanged(true);
            }
        } catch (NumberFormatException e) {
            LOGGER.error("Mcrew:changeRotYears()->" + "Please enter a number for RotationYears");
            JTF_rotYears.setText(Integer.toString(temp.getRotationYears()));
        } catch (NullPointerException npe) {
            LOGGER.debug("Null Data Object", npe);
        }

    }

    /**
     * This function calls other functions for checking all conditions on data before saving the
     * file. Checks for correct rotation years, sorted data and no empty rows
     *
     * @return Returns true if evrything passed OK else false.
     */
    public boolean checkAllConditions() {
        checked = true;
        Vector<String> msgs = new Vector<String>();
        if (checkIfAllDatesPresent() == -1) {
            return false;
        }
        if (data.checkIfSorted(msgs) == ManageData.CHECK_FAILED) {
            String[] errorMsg = {"The data is not sorted according to the dates.", "",
                "Do you want to auto sort them before saving? Click 'No' to go back and change manually"};

            int option = JOptionPane.showConfirmDialog(this, errorMsg, "Sort data", JOptionPane.YES_NO_OPTION);

            switch (option) {
                case JOptionPane.YES_OPTION:
                    //sort rows
                    data.sortData();
                    break;
                case JOptionPane.NO_OPTION:
                    return false; // user resees no/cancel
            }
        }

        if (checkAndDeleteEmptyRows() == -1) {
            // user pressed cancel
            return false;
        }
        if (checkAndSetRotYears() == -1) {
            // user pressed cancel
            return false;
        }
        if (checkParameterConsistency() == -1) {
            return false;
        }
        return true;
    }

    /**
     * This method makes sure if rows exist in a table then their date cells are populated.
     *
     * @return True, if date is populated for every row in a table else false.
     */
    public int checkIfAllDatesPresent() {
        Vector<Integer> noDateRows = data.checkIfAllDatesPresent();

        if (noDateRows == null) {
            return 1;
        }
        String noDateRowStr = null;
        String[] errorMsg = {"There are following rows with no dates in them.", "", "Please go back and enter the dates."};

        for (Integer noDateRow : noDateRows) {
            if (noDateRowStr == null) {
                noDateRowStr = noDateRow.toString();
            } else {
                noDateRowStr += ", " + noDateRow.toString();
            }
        }

        errorMsg[1] = noDateRowStr;

        JOptionPane.showMessageDialog(this, errorMsg);

        return -1;
    }

    /**
     * Check if there are any empty rows in the table and prompt user to delete them
     *
     * @return True if empty rows are found, else false
     */
    public int checkAndDeleteEmptyRows() {
        Vector<Integer> emptyRows = data.checkEmptyRows();

        if (emptyRows == null) {
            return 1;
        }
        String emptyRowStr = null;
        String[] errorMsg = {"There are some empty rows in the table as given below.", "",
            "Do you want to delete the delete them before saving? Click 'No' to go back and change manually"};

        for (Integer emptyRow : emptyRows) {
            if (emptyRowStr == null) {
                emptyRowStr = emptyRow.toString();
            } else {
                emptyRowStr += ", " + emptyRow.toString();
            }
        }

        errorMsg[1] = emptyRowStr;

        int option = JOptionPane.showConfirmDialog(this, errorMsg, "Delete Empty Rows ?", JOptionPane.YES_NO_OPTION);

        switch (option) {
            case JOptionPane.YES_OPTION:
                //delete rows
                data.deleteRows(emptyRows);
                setUndoDeleteStatus(true);
                break;
            case JOptionPane.NO_OPTION:
                return -1; // user resees no/cance
        }

        return 1;
    }

    /**
     * Check if rotation years match the dates in the data and set it to a correct value if user
     * enters one.
     *
     * @return Returns the integer value telling the length of the rotation if it is equal to or
     * greater than the rotation year specified for the last operation else -1. This is a check to
     * input correct values for rotation years.
     */
    public int checkAndSetRotYears() {
        int correctYears = data.checkRotationYears(); // returns the correct year value
        if (correctYears == -1) {
            return -1;
        }
        int rotYears = Integer.parseInt(JTF_rotYears.getText());

        if (rotYears >= correctYears) {
            return rotYears;

            //System.out.println("Mcrew:checkRotYears->"+ "RotYears= " + rotYears + ", Correct Yrs= " + correctYears);
        }
        do {
            RotationLengthDialog dialog = new RotationLengthDialog(Integer.toString(correctYears));
            dialog.setSize(300, 250);
            JScrollPane sp = new JScrollPane(dialog, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            sp.setBorder(null);
            sp.setPreferredSize(new Dimension(365, 170));
            int ipValue = JOptionPane.showOptionDialog(this, sp, "Rotation Years", JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE, null, null, null);
            String newValue = dialog.getValue();

            if (ipValue == JOptionPane.CANCEL_OPTION) {
                return -1; //user pressed Cancel option
            } else {
                try {
                    rotYears = Integer.parseInt(newValue);
                } catch (NumberFormatException e) {
                    LOGGER.error("Non numeric value entered for rotation years: " + newValue, e);
                }
            }
        } while (rotYears < correctYears);

        String rotYearsStr = Integer.toString(rotYears);
        JTF_rotYears.setText(rotYearsStr);
        changeRotYears(rotYearsStr); // make changes in the data object
        return rotYears;
    }

    /**
     * Checks if all the operations and their actions have values for all the parameters listed in
     * "operation_defn.xml"
     *
     * @return Returns 0 if there are no invalid operations in the vector else 1
     */
    public int checkParameterConsistency() {
        Vector<String> msgs = new Vector<String>();
        if (data.checkParameterConsistency(msgs) == ManageData.CHECK_PASSED) {
            return ManageData.CHECK_PASSED;
        }
        WepsMessageLog log = new WepsMessageLog();
        for (String msg : msgs) {
            log.logMessage(WepsMessage.MessageSeverity.ERROR, msg);
        }
        WepsMessageDialog.showMessageList(this, "Management File Errors", "Errors were detected with the management file.", ".",
                log.getMessages());

        return ManageData.CHECK_FAILED;
    }

    @Override
    public void RotYearsJT_focusLost(java.awt.event.FocusEvent event) {
        ////System.out.println("RotYearsJT focuslost" + RotYearsJT.getText());
        changeRotYears(JTF_rotYears.getText());
    }

    @Override
    public void RotYearsJT_actionPerformed(java.awt.event.ActionEvent event) {
        ////System.out.println("RotYearsJT actionperformed - "+ RotYearsJT.getText());
        changeRotYears(JTF_rotYears.getText());
    }

    /**
     * This method is called when the new management option is selected
     *
     * @param event
     */
    @Override
    @SuppressWarnings("fallthrough")
    public void NewJMI_actionPerformed(java.awt.event.ActionEvent event) {
        //System.out.println("Mcrew: NewJMI : Proceeding to create new file");
        // create function dataChanged
        if (dataChanged) {
            switch(data.getSave())
            {
                case NOSAVE:
                    JOptionPane.showMessageDialog(null, "Unable to save:\nSome data out of limits.",
                    "Management File", JOptionPane.INFORMATION_MESSAGE);
                    break;
                case WARNSAVE:
                    JOptionPane.showMessageDialog(null, "Warning:\nSome data out of recommended limits.",
                    "Management File", JOptionPane.INFORMATION_MESSAGE);
                    /*FallThrough*/
                default:
                    int option = JOptionPane.showConfirmDialog(this, "Save current Management File ? ");
                    switch (option) {
                        case JOptionPane.CANCEL_OPTION:
                            return;
                        case JOptionPane.YES_OPTION:
                            if ((fileName == null) || (fileName.length() == 0) || (fileName.equals(sUntitledFileName))) {
                                SaveAsJMI_actionPerformed(event);
                            } else {
                                SaveJMI_actionPerformed(event);
                            }
                            break;
                        case JOptionPane.NO_OPTION:
                            break;
                    }
            }
        }
        data.setWepsManFileNotes("");
        fileName = sUntitledFileName;
        //RotationJT.setText(fileName);
        changeRotFileName(fileName);
        data.clear();
        notes.JTA_Notes.setText("");
        JTF_rotYears.setText(Integer.toString(data.getRotationYears()));
        setDataChanged(false);

        invalidate();
        repaint();
    }

    /**
     * This method is called when the open management option is selected
     *
     * @param event
     */
    @Override
    @SuppressWarnings("fallthrough")
    public void OpenJMI_actionPerformed(java.awt.event.ActionEvent event) {
        //System.out.println("Mcrew: OpenJMI: Opening file");
        if (dataChanged) {
            switch(data.getSave())
            {
                case NOSAVE:
                    JOptionPane.showMessageDialog(null, "Unable to save:\nSome data out of limits.",
                    "Management File", JOptionPane.INFORMATION_MESSAGE);
                    break;
                case WARNSAVE:
                    JOptionPane.showMessageDialog(null, "Warning:\nSome data out of recommended limits.",
                    "Management File", JOptionPane.INFORMATION_MESSAGE);
                    /*FallThrough*/
                default:
                int option = JOptionPane.showConfirmDialog(this, "Save current Management File ? ");
                switch (option) {
                    case JOptionPane.CANCEL_OPTION:
                        return;
                    case JOptionPane.YES_OPTION:
                        if ((fileName == null) || (fileName.length() == 0) || (fileName.equals(sUntitledFileName))) {
                            //if (RotationJT.getText().equals("Untitled"))
                            SaveAsJMI_actionPerformed(event);
                        } else {
                            SaveJMI_actionPerformed(event);
                        }
                        break;
                    case JOptionPane.NO_OPTION:
                        break;
                }
            }
        }
        /*  new filechooser
         FileChooser fc=new FileChooser(this, true);
         fc.setCurrentFolder(new File(ConfigData.getDirectoryName(XMLConstants.smanagement_template)));
         fc.setFileChooserStyle(FileChooser.STYLE_OPEN);
         fc.setFilterTypes("usda.weru.util.filechooser.filetype.AllFileType",
         "usda.weru.util.filechooser.filetype.ManagementFileType");
         fc.setVisible(true);
         */
        WepsFileChooser mfc = WepsFileChooser.create(WepsFileChooser.Action.Select, new TFile(savePath), false, true, null,
                WepsFileTypes.Management, WepsFileTypes.Rotation);
        //set the tooltip of "home" button to "Home" instead of "Desktop"
        mfc.homeToolTip(mfc);
        //remove the NewFolder button
        mfc.disableNewFolder(mfc);
        if ((savePath == null) || (savePath.length() == 0)) // if already a file is saved then open new file in that dir
        {
            mfc.setCurrentDirectory(new TFile(ConfigData.getDirectoryName(XMLConstants.smanagement_template)));
        }//new de.schlichtherle.truezip.file.File(ConfigData.INITIAL_DIR));
        else {
            mfc.setCurrentDirectory(new TFile(savePath));
        }
        if (!(mfc.showDialog(this) == WepsFileChooser.APPROVE_OPTION)) {
            return;
        }

        //	RotationJT.setText(mfc.getSelectedFile().getName()); // here set the title
        TFile selectedFile = new TFile(mfc.getSelectedFile());
        if (selectedFile == null) {
            return;
        }
        try {
            String filePath = selectedFile.getCanonicalPath();
            //System.out.println("File opened:path = " +filePath);
            //savePath = fileDir;
            openFile(filePath); // call open file method here
        } catch (IOException e) {
            System.err.println("Error in opening file " + e);
        }
    }

    /**
     * This function opens an existing management file and sets the rotation text box
     *
     * @param fullPathName The path where this file reisdes in the system or on the network.
     */
    public void openFile(String fullPathName) throws IllegalStateException {
        setWaiting(true);
        try {
            //System.out.println("Mcrew: openFile: Opening the file " + fullPathName);
            if (fullPathName.equals("")) {
                System.err.println("File not selected error");
                return;
            }

            //data.readDataFile(fullPathName);
            /* Read data on a new ManageData object and assign it to 'data'only on success
             'data' is the ManageData object associated with the 'table'[Table object],
             'table' in associated with this Mcrew object. */
            ManageData newData = new ManageData();
            int dataReadValue = newData.readDataFile(fullPathName);
            //System.out.println("Mcrew:openfile" + "  datareadvalue = " +dataReadValue);
            switch (dataReadValue) {
                case ManageData.kCorruptedFile:
                    JOptionPane.showMessageDialog(this, "Unable to read management file " + fullPathName
                            + "\nThe file appears to be corrupted.", "Corrupted File", JOptionPane.ERROR_MESSAGE);
                    return;
                case ManageData.kWrong_Version:
                    String[] errorMsg = new String[2];
                    errorMsg[0] = "Management file " + fullPathName + "\nis of version " + newData.version
                            + ", whereas the current version is " + ManageData.VERSION_CURRENT + ".";

                    errorMsg[1] = "Do you want to continue reading ?";

                    int reply = JOptionPane.showConfirmDialog(this, errorMsg, "Version", JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE);
                    if (reply == JOptionPane.NO_OPTION) {
                        return;
                    }
                    break;
                case ManageData.kFile_NotFound:
                    System.err.println("Mcrew:openFile() " + "Cannot find the file. Strange!!");
                    return;
                case ManageData.kUnknown_Error:
                    System.err.println("Mcrew:openFile() " + "Unknown error reading data file");
                    return;
                case ManageData.kSuccess:
                    //System.out.println("Data read succesfully");
                    break;
                default:
                    break;
            }

            //Issue: 543, there is a chance of threading race condition.  So we wait to make sure the data is not null.
            while (data == null) {
                Thread.yield();
            }
            data.readDataFile(fullPathName);
            table.checkData();

            TFile file = new TFile(fullPathName);
            fileName = file.getName();
            savePath = file.getParent();

            //Set the Text Field to the absolute path of current opened file.
            try {
                filePathName = file.getCanonicalPath();
                changeRotFileName(filePathName);
                //RotationJT.setText(filePathName);
            } catch (IOException e) {
                LOGGER.error("Unable to read file: " + file.getAbsolutePath(), e);
            }

            JTF_rotYears.setText(Integer.toString(data.getRotationYears()));
        } finally {
            setWaiting(false);
        }

        setDataChanged(false);
        checkAllConditions();
        refreshMcrewTableData();
    }

    /**
     * This method lets you open an updated file when a file data is modified and saved and the new
     * data needs to be displayed.
     *
     * @param fullPathName The system or network path where this file resides.
     */
    public void openRefreshedFile(String fullPathName) {
        setWaiting(true);
        try {
            data.readDataFile(fullPathName);
            table.checkData();
            TFile file = new TFile(fullPathName);
            fileName = file.getName();
            savePath = file.getParent();

            //Set the Text Field to the absolute path of current opened file.
            try {
                filePathName = file.getCanonicalPath();
                changeRotFileName(filePathName);
            } catch (IOException e) {
                LOGGER.error("Error reading file: " + file.getAbsolutePath(), e);
            }

            JTF_rotYears.setText(Integer.toString(data.getRotationYears()));
            //System.out.println("Mcrew:openFile->" + "Rotation years: " + data.getRotationYears());
        } finally {
            setWaiting(false);
        }
        setDataChanged(false);
        checkAllConditions();

    }

    /**
     * This method is called when the open copy of template option is selected
     *
     * @param event
     */
    @Override
    public void OpenCTJMI_actionPerformed(java.awt.event.ActionEvent event) {
        setWaiting(true);
        try {
            //System.out.println("Mcrew: OpenCT: Opening template");
            if (dataChanged) {
                int option = JOptionPane.showConfirmDialog(this, "Save current Management File ? ");
                switch (option) {
                    case JOptionPane.CANCEL_OPTION:
                        return;
                    case JOptionPane.YES_OPTION:
                        if ((fileName == null) || (fileName.length() == 0) || (fileName.equals(sUntitledFileName))) {
                            //if (RotationJT.getText().equals("Untitled"))
                            SaveAsJMI_actionPerformed(event);
                        } else {
                            SaveJMI_actionPerformed(event);
                        }
                        break;
                    case JOptionPane.NO_OPTION:
                        break;
                }
            }

            TFile dirXML = new TFile(ConfigData.getDirectoryName(XMLConstants.smanagement_template));
            String dirXMLPath = dirXML.getAbsolutePath();
            WepsFileChooser mfc = new WepsFileChooser(WepsFileChooser.Filetype.MANAGE, dirXMLPath, WepsFileChooser.OPEN);
            mfc.setCurrentDirectory(dirXML);
            //set the tooltip of "home" button to "Home" instead of "Desktop"
            mfc.homeToolTip(mfc);
            //remove the NewFolder button
            mfc.disableNewFolder(mfc);

            if (!(mfc.showDialog(this) == WepsFileChooser.APPROVE_OPTION)) {
                return;
            }
            //	RotationJT.setText(mfc.getSelectedFile().getName()); // here set the title
            TFile selectedFile = new TFile(mfc.getSelectedFile());

            try {
                String fileDir = selectedFile.getCanonicalPath();
                //System.out.println("fileDir = " + fileDir);
                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;
                }
                //savePath = fileDir;
                openFile(copyToFilePath); // call open file method here
                TFile file = new TFile(fileDir);
                saveTemplatePath = file.getParent();
                //dataChanged = true;
            } catch (IOException e) {
                System.err.println("Error in opening file " + e);
            }
        } finally {
            setWaiting(false);
        }
    }

    /**
     * This method is called when the save management option is selected
     *
     * @param event
     */
    @Override
    @SuppressWarnings("fallthrough")
    public void SaveJMI_actionPerformed(java.awt.event.ActionEvent event) {
        //System.out.println("Mcrew: Save_JMI action Saving file");
        switch(data.getSave())
        {
            case NOSAVE:
                JOptionPane.showMessageDialog(null, "Unable to save:\nSome data out of limits.",
                "Management File", JOptionPane.INFORMATION_MESSAGE);
                return;
            case WARNSAVE:
                JOptionPane.showMessageDialog(null, "Warning:\nSome data out of recommended limits.",
                "Management File", JOptionPane.INFORMATION_MESSAGE);
                /*FallThrough*/
            default:
        }
        if ((fileName == null) || (fileName.length() == 0) || (fileName.equals(sUntitledFileName))) {
            ////System.out.println("Calling save as with fileName " + fileName);
            SaveAsJMI_actionPerformed(event);
            return;
        }

        //if file is xml and xml is not allowed, prompt to save as .man
        if (!usda.weru.util.ConfigData.getDefault().isFormatXMLAllowed() && fileName.toLowerCase().endsWith(".xml")) {
            SaveAsJMI_actionPerformed(event);
            return;

        }

        if (checkAllConditions() == false) {
            saveSuccess = false;
            return; // user pressed cancel on some option, Don't save
        }

        //If the use doesnt opens a file or opens a template of a file
        // and without making any changes saves the file, then the "absFileName"
        // should reflect this saved file.
        absFileName = filePathName;

        if (dataChanged == false) {
            return;
        }
        if ((savePath == null) || (savePath.length() == 0)) {
            savePath = ConfigData.getDirectoryName(XMLConstants.smanagement_template);

            ////System.out.println("Data changed " + dataChanged);
        }
        String fullPathFileName = savePath + TFile.separator + fileName;
        //System.out.println("MCREW : SaveJMI_aP : Saving file " + fullPathFileName);
        //Get the parent location of this file, see if its writable,if not
        //display the warning message and return.-by Neha
        TFile mcrewFile = new TFile(fullPathFileName);
        TFile parentFile = new TFile(mcrewFile.getParentFile());
        //System.out.println("SaveAsJMI_actionPerformed:parent file"+mcrewFile.getParent()+" can we write into this location:"+
        //parentFile.canWrite());
        if (parentFile.canWrite() == false) {
            JOptionPane.showMessageDialog(this, "The File location Specified is not writable\n " + fullPathFileName, "Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        data.writeDataFile(savePath + TFile.separator + fileName);
        //update the abs file path name to this path of the saved file
        absFileName = fullPathFileName;

        setDataChanged(false);
        saveSuccess = true;

        if (refreshMcrewScreen.equals("true")) {
            openRefreshedFile(absFileName);
            refreshMcrewScreen = "false";
        }

        //System.out.println("Returning after saving file");
    }

    /**
     * This method is called when the save as option is selected
     *
     * @param event
     */
    @Override
    @SuppressWarnings("fallthrough")
    public void SaveAsJMI_actionPerformed(java.awt.event.ActionEvent event) {
        switch(data.getSave())
        {
            case NOSAVE:
                JOptionPane.showMessageDialog(null, "Unable to save:\nSome data out of limits.",
                "Management File", JOptionPane.INFORMATION_MESSAGE);
                return;
            case WARNSAVE:
                JOptionPane.showMessageDialog(null, "Warning:\nSome data out of recommended limits.",
                "Management File", JOptionPane.INFORMATION_MESSAGE);
                /*FallThrough*/
            default:
        }
        RandomAccessFile in;
        long endPos;

        //System.out.println("");
        if (checkAllConditions() == false) {
            saveSuccess = false;
            return; // user pressed cancel on some option, Don't save
        }

        WepsFileChooser mfc;
        TFile tempFile;
        //  //System.out.println("savePath:"+savePath+"  projectDir:"+projectDir);
        if ((savePath == null) || (savePath.length() == 0)) {
            fileName = "untitled.man";
            //The file chooser dialog will open in the current WEPS directory.
            mfc = new WepsFileChooser(WepsFileChooser.Filetype.MANAGE, projectDir, WepsFileChooser.SAVE);
            mfc.setCurrentDirectory(new TFile(projectDir)); //new de.schlichtherle.truezip.file.File(ConfigData.INITIAL_DIR));
            tempFile = new TFile(projectDir, fileName);
        } else if (!usda.weru.util.ConfigData.getDefault().isFormatXMLAllowed()) {
            //xml not allowed!
            mfc = new WepsFileChooser(WepsFileChooser.Filetype.MANAGE, savePath, WepsFileChooser.SAVE);
            String tempFileName = Util.purgeExtensions(fileName, WepsFileTypes.Management.getExtension());

            tempFile = new TFile(savePath, tempFileName);
            mfc.setCurrentDirectory(new TFile(savePath));
        } else {
            mfc = new WepsFileChooser(WepsFileChooser.Filetype.MANAGE, savePath, WepsFileChooser.SAVE);
            tempFile = new TFile(savePath, fileName);
            mfc.setCurrentDirectory(new TFile(savePath));
        }

        //set the tooltip of "home" button to "Home" instead of "Desktop"
        mfc.homeToolTip(mfc);
        mfc.setSelectedFile(tempFile);
        //                mfc.setText(tempFile.getName());
        mfc.setText(tempFile.getName());
        mfc.setDialogTitle("Save a Management File");

        if (mfc.showDialog(this) != WepsFileChooser.APPROVE_OPTION) {
            //            fileName = "";
            return;
        }
        TFile currentFile = new TFile(mfc.getSelectedFile());
        /* try{
         in = new RandomAccessFile(currentFile, "r");
         endPos = in.length(); // determine file length
         if( !( endPos > 0 ) ){
         JOptionPane.showMessageDialog(this, "CANNOT SAVE : Check for either empty rows or the file itself.",
         " Cannot Save file ",
         JOptionPane.INFORMATION_MESSAGE);
         return;
         }
         }catch(IOException e) {
         System.err.println(e.getMessage());
         }*/

        String newFileName = currentFile.getPath();
        //System.out.println("M_SA_aP: " + newFileName);
        TFile testFile = currentFile;
        TFile parentDir = new TFile(testFile.getParentFile());
        String name = testFile.getName();
        while (parentDir != null && !parentDir.exists()) {
            name = parentDir.getName() + TFile.separator + name;
            parentDir = new TFile(parentDir.getParentFile());
        }

        char[] invalidChars = {'\\', '/', '<', '>', '|', '?', '*', '&', '"', ':', '~', '`', '\''};
        //A single quote cannot be given as a character, so given as a separate string
        for (int i = 0; i < name.length(); i++) {
            for (int j = 0; j < invalidChars.length; j++) {
                if (name.charAt(i) == invalidChars[j]) {
                    JOptionPane.showMessageDialog(this, "INVALID CHARACTER : "
                            + invalidChars[j] + " \n\\ / < > | ? * & \" ~ ` ' ",
                            " Cannot Save file ", JOptionPane.INFORMATION_MESSAGE);
                    SaveAsJMI_actionPerformed(event);
                    return;
                }
            }
        }
        if (!mfc.getSelectedFile().getParentFile().exists()) {

            JOptionPane.showMessageDialog(this, "WRONG PATH : " + newFileName + " doesn't exist.", " Cannot Save file ",
                    JOptionPane.INFORMATION_MESSAGE);
            SaveAsJMI_actionPerformed(event);
            return;
        }

        // strip suffix that filechooser seems to want to add
        if (newFileName.toUpperCase().endsWith(".MAN")) {
            newFileName = newFileName.substring(0, newFileName.lastIndexOf('.'));
            //System.out.println("MCREW : SaveAsJMI : New MAN_Filename is : " + newFileName );
        } else if (newFileName.toUpperCase().endsWith(".XML")) {
            newFileName = newFileName.substring(0, newFileName.lastIndexOf('.'));
        }

        String savedFile = null; //save the name of the file along with .man or .xml extension.

        // create .xml file if filter specified if
        int result = -1;
        if (mfc.accept(new TFile("x.xml"))) {
            result = data.writeDataFile(newFileName + ".xml");
            savedFile = newFileName + ".xml";
        }

        //MUST DO THE MAN SECOND!! Make sure we use it in the run data.
        // create .man file if filter specified if
        if (mfc.accept(new TFile("x.man"))) {
            result = data.writeDataFile(newFileName + ".man");
            savedFile = newFileName + ".man";
        }

        if (result != 1) {
            JOptionPane.showMessageDialog(this, "The File location Specified is not writable\n " + newFileName, "Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        fileName = new TFile(savedFile).getName();
        saveSuccess = true;

        try {
            data.setWepsManFileNotes("");
            TFile fileDir = new TFile(savedFile);
            absFileName = fileDir.getCanonicalPath();
        } catch (IOException e) {
            System.err.println("Error in opening file " + e);
        }
        String message = null;
        //If Mcrew is not stand alone, append the message that mcrew will be closed
        changeRotFileName(savedFile);
        setDataChanged(false);
    }

    /**
     * This method is called when the save as template option is selected
     *
     * @param event
     */
    @Override
    public void SaveAsTJMI_actionPerformed(java.awt.event.ActionEvent event) {

        //System.out.println("Mcrew: SaveAsTJMI"+ "Save as Template file");
        if (checkAllConditions() == false) {
            return; // user pressed cancel on some option, Don't save
        }
        //if( (fileName == null) || (fileName.equals(sUntitledFileName)) )//(fileName.length() == 0) )

        String tempSaveAsPath = ConfigData.getDirectoryName(usda.weru.util.ConfigData.ManTempSaveAs);
        String tempPath = ConfigData.getDirectoryName(XMLConstants.smanagement_template);
        TFile dirXML = null;
        if (tempSaveAsPath != null && tempSaveAsPath.length() > 0 && ConfigData.getHasManTempSaveAsDir()) {
            dirXML = new TFile(tempSaveAsPath);
        } else {
            dirXML = new TFile(tempPath);
        }
        String dirXMLPath = dirXML.getAbsolutePath();

        TFile tempFile;
        tempFile = new TFile(dirXMLPath, fileName != null ? fileName : "Untitled");

        WepsFileChooser mfc = new WepsFileChooser(WepsFileChooser.Filetype.MANAGE, dirXMLPath, WepsFileChooser.SAVE);

        mfc.setCurrentDirectory(dirXML); //new de.schlichtherle.truezip.file.File(ConfigData.INITIAL_DIR));
        //set the tooltip of "home" button to "Home" instead of "Desktop"
        mfc.homeToolTip(mfc);
        mfc.setPersitSelectedFile(true);
        mfc.setSelectedFile(tempFile);
        mfc.setText(tempFile.getName());
        mfc.setDialogTitle("Save a Template Management File");
        if (mfc.showDialog(this) != WepsFileChooser.APPROVE_OPTION) {
            return;
        }
        TFile testFile = new TFile(mfc.getSelectedFile());
        TFile parentDir = new TFile(testFile.getParentFile());
        String name = testFile.getName();
        while (parentDir != null && !parentDir.exists()) {
            name = parentDir.getName() + TFile.separator + name;
            parentDir = new TFile(parentDir.getParentFile());
        }

        char[] invalidChars = {'\\', '/', '<', '>', '|', '?', '*', '&', '"', ':', '~', '`', '\''};
        //A single quote cannot be given as a character, so given as a separate string
        for (int i = 0; i < name.length(); i++) {
            for (int j = 0; j < invalidChars.length; j++) {
                if (name.charAt(i) == invalidChars[j]) {
                    JOptionPane.showMessageDialog(this, "INVALID CHARACTER : " + invalidChars[j] + " \n\\ / < > | ? * & \" ~ ` '",
                            " Cannot Save file ", JOptionPane.INFORMATION_MESSAGE);
                    SaveAsTJMI_actionPerformed(event);
                    return;
                }
            }
        }

        TFile selectedFile = new TFile(mfc.getSelectedFile());
        if (!selectedFile.getParentFile().exists()) {

            JOptionPane.showMessageDialog(this, "WRONG PATH : " + selectedFile.getPath()
                    + " doesn't exist.", " Cannot Save file ",
                    JOptionPane.INFORMATION_MESSAGE);
            SaveAsTJMI_actionPerformed(event);
            return;
        }

        String newFileName = selectedFile.getPath();

        // strip suffix that filechooser seems to want to add
        if (newFileName.toUpperCase().endsWith(".MAN")) {
            newFileName = newFileName.substring(0, newFileName.lastIndexOf('.'));
            //System.out.println("MCREW : SaveAsJMI : New MAN_Filename is : " + newFileName );
        } else if (newFileName.toUpperCase().endsWith(".XML")) {
            newFileName = newFileName.substring(0, newFileName.lastIndexOf('.'));
        }

        String savedFile = null; //save the name of the file along with .man or .xml extension.

        // create .xml file if filter specified if
        int result = -1;
        if (mfc.accept(new TFile("x.xml"))) {
            result = data.writeDataFile(newFileName + ".xml");
            savedFile = newFileName + ".xml";
        }

        //MUST DO THE MAN SECOND!! Make sure we use it in the run data.
        // create .man file if filter specified if
        if (mfc.accept(new TFile("x.man"))) {
            result = data.writeDataFile(newFileName + ".man");
            savedFile = newFileName + ".man";
        }

        if (result != 1) {
            JOptionPane.showMessageDialog(this, "The File location Specified is not writable\n " + newFileName, "Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        //setDataChanged(false);
        JOptionPane.showMessageDialog(this, savedFile, "Management file(s) template created", JOptionPane.INFORMATION_MESSAGE);

        //Comment out this line if you dont want to set the name of this file
        // to the rotation text field.
        //    RotationJT.setText(savedFilePath); // set the rotation file text area to last file saved
    }

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

    /**
     * This method is called when the exit option is selected
     *
     * @param event
     */
    @Override
    public void ExitJMI_actionPerformed(java.awt.event.ActionEvent event) {
        table.commitEdit();
        changeRotYears(JTF_rotYears.getText());
        //System.out.println("MCrew: ExitJMIactin: Exiting Mcrew");
        //This boolean is used to determine if the window should be closed or not.

        int option = -1;
        if (new TFile(absFileName).isDirectory()) {
            absFileName = "";
            fileName = "";
            filePathName = "";
        }
        if (dataChanged) {
            option = JOptionPane.showConfirmDialog(this, "Save current Management File ? ");
            //System.out.println("MCREW : ExitJMI_actionPerformed -- OPTION is : " + option );
            switch (option) {
                case JOptionPane.CANCEL_OPTION:
                    this.setVisible(true);
                    return;
                case JOptionPane.YES_OPTION:
                    if (!checkAllConditions()) {
                        return;
                    }
                    ////System.out.println("fileName:"+fileName+"  sUntitledFileName:"+sUntitledFileName);
                    if ((fileName == null) || (fileName.length() == 0) || (fileName.equals(sUntitledFileName))) {
                        SaveAsJMI_actionPerformed(event);
                    } else {
                        SaveJMI_actionPerformed(event);
                    }
                    break;
                case JOptionPane.NO_OPTION:
                    break;
            }
        }

        /* If the user selected Yes or No, then the Mcrew window should be closed.
         ** If the user selected Yes, and the data could not be saved due to empty file
         ** etc,. then the Mcrew window should not be closed.- by Neha.
         */
        boolean closeWindow = true;
        if (option == JOptionPane.YES_OPTION && saveSuccess == false) {
            closeWindow = false;
        }

        if (closeWindow == true) {
            openMcrewWindows.remove(this);
            cleanup();
            // Beep
            changes.firePropertyChange(WindowClosing, null, "true");
            this.setVisible(false);
            // hide the Frame
            table.setKillFlag(true);
            this.dispose();
            if (standaloneFlg) {
                System.exit(0);
            }
        } //end of if
    }

    /**
     *
     */
    public void cleanup() {
        try {
            ManageData tempData = data;
            if (tempData != null) {
                tempData.clear();
                data = null;
            }

            ConfigData.cleanup();

            Table tempTable = table;
            if (tempTable != null) {
                tempTable.cleanup();
            }
        } catch (Exception e) {
            LOGGER.warn("Unable to clean up mcrew data structures.", e);
        }

    }

    /**
     * This method is called when the cut option is selected ConfigData/ void
     * CutJMI_actionPerformed(java.awt.event.ActionEvent event) { // //System.out.println("Mcrew:
     * Cut Action: Cut row"); table.cutRows(); }
     *
     * /**
     * This method is called when the copy option is selected
     *
     * @param event
     */
    @Override
    public void CopyJMI_actionPerformed(java.awt.event.ActionEvent event) {
        setUndoDeleteStatus(false);
        ////System.out.println("Mcrew: CopyJMI action");
        table.copyRows();
    }

    @Override
    public void CutJMI_actionPerformed(java.awt.event.ActionEvent event) {
        setWaiting(true);
        try {
            setUndoDeleteStatus(false);
            table.cutRows();
            table.checkData();
        } finally {
            setWaiting(false);
        }
    }

    @Override
    public void PasteJMI_actionPerformed(java.awt.event.ActionEvent event) {
        setWaiting(true);
        try {
            setUndoDeleteStatus(false);
            table.pasteRows();
        } finally {
            setWaiting(false);
        }
    }

    @Override
    public void DeleteJMI_actionPerformed(java.awt.event.ActionEvent event) {
        setWaiting(true);
        try {
            table.deleteRows();
            table.checkData();
            setUndoDeleteStatus(true);
        } finally {
            setWaiting(false);
        }
    }

    /**
     *
     * @param evt
     */
    @Override
    public void UndoDeleteJMI_ActionPerformed(java.awt.event.ActionEvent evt) {
        setWaiting(true);
        try {
            table.undoDeleteRows();
            table.checkData();
            setUndoDeleteStatus(false);
        } finally {
            setWaiting(false);
        }
    }

    /**
     *
     * @param enabled
     */
    public void setUndoDeleteStatus(boolean enabled) {
//        enabled = data != null && data.deletedRows != null && data.deletedRows.size() > 0;
        JMI_undoDelete.setEnabled(enabled);
        popUndoDeleteJMI.setEnabled(enabled);
    }

    @Override
    public void SortJMI_actionPerformed(java.awt.event.ActionEvent event) {
        setWaiting(true);
        try {
            setUndoDeleteStatus(false);
            table.sortData();
            table.checkData();
        } finally {
            setWaiting(false);
        }
    }

    @Override
    public void InsertJMI_actionPerformed(java.awt.event.ActionEvent event) {
        setWaiting(true);
        try {
            setUndoDeleteStatus(false);
            table.insertRow();
        } finally {
            setWaiting(false);
        }

    }

    /**
     *
     * @param event
     */
    @Override
    public void InsertOperationJMI_actionPerformed(java.awt.event.ActionEvent event) {
        setUndoDeleteStatus(false);
        table.insertRow();
        boolean added = table.addColumnData(1);
        //Make sure a operation was added.
        if (!added) {
            table.deleteRows();
        }
    }

    /**
     *
     */
    public void setDeleted() {
        setUndoDeleteStatus(true);
    }

    @Override
    public void CycleFwdJMI_actionPerformed(java.awt.event.ActionEvent event) {
        setWaiting(true);
        try {
            long time = System.currentTimeMillis();
            while (checkAndSetRotYears() == -1) {
                if (System.currentTimeMillis() - time > 5000) {
                    return;
                }
            }
            int rotYears = Integer.parseInt(JTF_rotYears.getText());
            table.cycleForward(rotYears);
        } finally {
            setWaiting(false);
        }
    }

    @Override
    public void CycleBwdJMI_actionPerformed(java.awt.event.ActionEvent event) {
        setWaiting(true);
        try {
            long time = System.currentTimeMillis();
            while (checkAndSetRotYears() == -1) {
                if (System.currentTimeMillis() - time > 5000) {
                    return;
                }
            }
            int rotYears = new Integer(JTF_rotYears.getText());
            table.cycleBackward(rotYears);
        } finally {
            setWaiting(false);
        }
    }

    @Override
    public void NotesJMI_actionPerformed(java.awt.event.ActionEvent evt) {
        if (notes.notesPresent == false) {
            notes.JTA_Notes.setText(data.getWepsManFileNotes());
            notes.setVisible(true);
            //Position this frame relative to the position of Mcrew-by Neha
            notes.setLocationRelativeTo(this);
            notes.notesPresent = true;
        } else if (notes.isActive() == false) {
            notes.JTA_Notes.setText(data.getWepsManFileNotes());
            notes.toFront();
            notes.setVisible(true);
            notes.requestFocus();
        }
    }

    void InsertFileJMI_actionPerformed(java.awt.event.ActionEvent event) {
        //if( table.isOneRowSelected("insert file") ) return;
        setWaiting(true);
        try {
            ManageData dataToInsert = new ManageData();

            TFile dirXML = new TFile(ConfigData.getDirectoryName(XMLConstants.smanagement_template));
            WepsFileChooser mfc;

            mfc = WepsFileChooser.create(WepsFileChooser.Action.Select, dirXML, false, false, null, WepsFileTypes.Management,
                    WepsFileTypes.Rotation);
            mfc.setCurrentDirectory(dirXML); //new de.schlichtherle.truezip.file.File(ConfigData.INITIAL_DIR));

            mfc.setDialogTitle("Select a Management File");

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

            if (!(mfc.showDialog(null) == WepsFileChooser.APPROVE_OPTION)) {
                return;
            }
            TFile selectedFile = new TFile(mfc.getSelectedFile());

            try {
                String filePath = selectedFile.getCanonicalPath();
                //System.out.println("Mcrew:InsertFileJMI(): " + "Opening file " + filePath);
                dataToInsert.readDataFile(filePath);
                table.insertFile(dataToInsert, false, false);
                table.checkData();
                //savePath = delectedFile.getParent();
            } catch (IOException e) {
                System.err.println("Error in opening file " + e);
            }
            setDataChanged(true);
        } finally {
            setWaiting(false);
        }

    }

    void InsertFileDateAdjustedJMI_actionPerformed(java.awt.event.ActionEvent event) {
        setWaiting(true);
        try {
            if (data.getRows().isEmpty()) {
                InsertFileJMI_actionPerformed(event);
                return;
            }
            ManageData dataToInsert = new ManageData();

            TFile dirXML = new TFile(ConfigData.getDirectoryName(XMLConstants.smanagement_template));
            WepsFileChooser mfc;

            mfc = WepsFileChooser.create(WepsFileChooser.Action.Select, dirXML, false, false, null, WepsFileTypes.Management,
                    WepsFileTypes.Rotation);
            mfc.setCurrentDirectory(dirXML); //new de.schlichtherle.truezip.file.File(ConfigData.INITIAL_DIR));
            mfc.setDialogTitle("Select a Management File");

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

            if (!(mfc.showDialog(null) == WepsFileChooser.APPROVE_OPTION)) {
                return;
            }
            TFile selectedFile = new TFile(mfc.getSelectedFile());

            try {
                String filePath = selectedFile.getCanonicalPath();
                //System.out.println("Mcrew:InsertFileJMI(): " + "Opening file " + filePath);
                dataToInsert.readDataFile(filePath);
                table.insertFile(dataToInsert, true, false);
                table.checkData();
                //savePath = delectedFile.getParent();
            } catch (IOException e) {
                System.err.println("Error in opening file " + e);
            }

            setDataChanged(true);
        } finally {
            setWaiting(false);
        }
    }

    /**
     *
     * @param event
     */
    public void AddRotationDateAdjustedJMI_actionPerformed(java.awt.event.ActionEvent event) {
        setWaiting(true);
        try {

            ManageData dataToInsert = new ManageData();

            TFile dirXML = new TFile(ConfigData.getDirectoryName(XMLConstants.smanagement_template));
            WepsFileChooser mfc;

            mfc = WepsFileChooser.create(WepsFileChooser.Action.Select, dirXML, WepsFileTypes.Rotation);
            mfc.setCurrentDirectory(dirXML); //new de.schlichtherle.truezip.file.File(ConfigData.INITIAL_DIR));
            mfc.setDialogTitle("Select a Rotation File");

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

            if (!(mfc.showDialog(null) == WepsFileChooser.APPROVE_OPTION)) {
                return;
            }
            TFile selectedFile = new TFile(mfc.getSelectedFile());

            try {
                String filePath = selectedFile.getCanonicalPath();
                //System.out.println("Mcrew:InsertFileJMI(): " + "Opening file " + filePath);
                dataToInsert.readDataFile(filePath);
                table.insertFile(dataToInsert, true, true);
                table.checkData();
                //savePath = delectedFile.getParent();
            } catch (IOException e) {
                System.err.println("Error in opening file " + e);
            }

            setDataChanged(true);
        } finally {
            setWaiting(false);
        }
    }

    void DrillDownScreenJMI_actionPerformed(java.awt.event.ActionEvent event) {
        table.showDrillDownScreen();
    }

    void SetDateJMI_actionPerformed(java.awt.event.ActionEvent event) {
        table.setDates();
    }

    void ChangeDateJMI_actionPerformed(java.awt.event.ActionEvent event) {
        table.changeDates();
    }

    void CalendarDateJMI_actionPerformed(java.awt.event.ActionEvent event) {
        table.calendarDates();
    }

    void SetDirectionJMI_actionPerformed(java.awt.event.ActionEvent event) {
        table.setDirection();
    }

    void AdjustDirectionJMI_actionPerformed(java.awt.event.ActionEvent event) {
        table.adjustDirection();
    }

    void SetToZeroJMI_actionPerformed(java.awt.event.ActionEvent event) {
        table.setAbsoluteDirection(0);
    }

    void SetTo45JMI_actionPerformed(java.awt.event.ActionEvent event) {
        table.setAbsoluteDirection(45);
    }

    void SetTo90JMI_actionPerformed(java.awt.event.ActionEvent event) {
        table.setAbsoluteDirection(90);
    }

    void IncrementBy15JMI_actionPerformed(java.awt.event.ActionEvent event) {
        table.incrDecrDir(15);
    }

    void DecrementBy15JMI_actionPerformed(java.awt.event.ActionEvent event) {
        table.incrDecrDir(-15);
    }

    void IncrementBy45JMI_actionPerformed(java.awt.event.ActionEvent event) {
        table.incrDecrDir(45);
    }

    void DecrementBy45JMI_actionPerformed(java.awt.event.ActionEvent event) {
        table.incrDecrDir(-45);
    }

    void ChangeBy90JMI_actionPerformed(java.awt.event.ActionEvent event) {
        table.changeBy90();
    }

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

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

    @Override
    public void EmailJMI_actionPerformed(java.awt.event.ActionEvent event) {
        try {
            /**
             * projectsPath is the directory in which the projects are present projectDirectory is
             * the directory in which the current run is present. These both are needed for the File
             * Choosers in the Email
             *
             */
            //Email em = new Email("Send Email to WEPS Support", "", "weps-comments@weru.ksu.edu","MCrew", absFileName);
            Email.comment("MCREW", null, absFileName);
        } catch (java.lang.Exception e) {
        }
    }

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

    @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 = "";

            WepsFileChooser fileChooser = WepsFileChooser.create(WepsFileChooser.Action.Select, null, false, true, null,
                    WepsFileTypes.Management, WepsFileTypes.Rotation);
            fileChooser.setFileSelectionMode(WepsFileChooser.FILES_ONLY);
            fileChooser.setMultiSelectionEnabled(true);
            fileChooser.setAcceptAllFileFilterUsed(false);
            fileChooser.setApproveButtonText("Select Files");

            fileChooser.setDialogTitle("Select WEPS management files that are to be updated");

            String dir = ConfigData.getDirectoryName(XMLConstants.smanagement_template);
            TFile ddir = new TFile(dir);
            fileChooser.setCurrentDirectory(ddir);

            java.io.File[] sourceFiles = null;
            int returnVal = fileChooser.showOpenDialog(this);
            if (returnVal == WepsFileChooser.APPROVE_OPTION) {
                sourceFiles = fileChooser.getSelectedFiles();
            } else {
                return;
            }
            //Check if all the files selected are management files and put them in a vector
            boolean doUpdate = true;
            Vector<String> manFiles = new Vector<String>();
            for (int i = 0; sourceFiles != null && i < sourceFiles.length; i++) {
                try {
                    m_fileName = sourceFiles[i].getCanonicalPath();
                    doUpdate = WepsFileTypes.Management.accept(sourceFiles[i]) || WepsFileTypes.Rotation.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.addElement(m_fileName);
                } catch (HeadlessException | IOException e) {
                    System.out.println("Error: " + e);
                }
            }

            if (doUpdate == false) {
                return;
            }

            TFile fs = new TFile(ConfigData.getDirectoryName(XMLConstants.smanagement_skeleton));
            if ((!fs.exists()) || (!fs.isDirectory())) {
                JOptionPane.showMessageDialog(this, "Skeleton directory is not valid: \n\n"
                        + ConfigData.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.doUpdate(this, manFiles);
            TVFS.umount();
        } catch (FsSyncException ex) {
            java.util.logging.Logger.getLogger(Mcrew.class.getName()).log(Level.SEVERE, null, ex);
        }
    } //end of updateFilesJMI_actionPerformed

    //This function updates the WEPS Management files recursively.
    @Override
    public void UpdateWEPSJMI_actionPerformed(java.awt.event.ActionEvent event) {
        //  implement it;
        String dir;
        WepsFileChooser fileChooserMan = new WepsFileChooser(WepsFileChooser.Filetype.FILE, "", WepsFileChooser.SELECT);
        fileChooserMan.setFileSelectionMode(WepsFileChooser.DIRECTORIES_ONLY);
        fileChooserMan.setMultiSelectionEnabled(false);
        fileChooserMan.setDialogTitle("Select a directory where all WEPS management files will be updated");
        fileChooserMan.setAcceptAllFileFilterUsed(false);

        dir = ConfigData.getDirectoryName(XMLConstants.smanagement_template);
        TFile ddir = new TFile(dir);

        fileChooserMan.setApproveButtonText("Choose Directory");
        fileChooserMan.setCurrentDirectory(ddir);

        int returnVal = fileChooserMan.showOpenDialog(this);
        if (returnVal == WepsFileChooser.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);
            }
        } else {
            return;
        }
        if (JOptionPane.showConfirmDialog(this, "This will update all the WEPS management files in the management directory:\n"
                + dir + "\nwith current information from the operation and crop files.\n\nThis will also update all "
                + "WEPS management files in all subdirectores under \n" + dir
                + "\n\nDo you want to update the WEPS management files now?", "Update WEPS Management Files",
                JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
            return;
        }
        //set the cursor to wait cursor on the Mcrew screen
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        XMLManagementUpdater updater = new XMLManagementUpdater();
        updater.updateDirectory(this, dir, true);
        //set the cursor back to default on the Mcrew screen
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    }
    
    @Override
    public void BackConvertSingleJMI_actionPerformed(ActionEvent evt)
    {
        TFile sourceFile = null;
        TFile destinationDirectory = null;
        {
            WepsFileChooser fileChooser = new WepsFileChooser(WepsFileChooser.Filetype.FILE, "", WepsFileChooser.SELECT);
            fileChooser.setFileSelectionMode(WepsFileChooser.FILES_ONLY);
            fileChooser.setMultiSelectionEnabled(false);
            fileChooser.setApproveButtonText("Choose File");
            XMLSkelFilter filter = new XMLSkelFilter("man", "WEPS Management Files");
            fileChooser.setFileFilter(filter);
            fileChooser.setDialogTitle("Select a WEPS management file");

            TFile ddir = new TFile(savePath);
            fileChooser.setCurrentDirectory(ddir);

            int returnVal = fileChooser.showOpenDialog(this);

            if (returnVal == WepsFileChooser.APPROVE_OPTION) 
            {
                try { sourceFile = new TFile(fileChooser.getSelectedFile()); } 
                catch (Exception e) { System.err.println("Error: " + e); }
            } 
            else return;
        }
        {
            WepsFileChooser fileChooser = new WepsFileChooser(WepsFileChooser.Filetype.FILE, "", WepsFileChooser.SELECT);
            fileChooser.setFileSelectionMode(WepsFileChooser.DIRECTORIES_ONLY);
            fileChooser.setMultiSelectionEnabled(false);
            fileChooser.setDialogTitle("Select a destination directory.");
            fileChooser.setAcceptAllFileFilterUsed(false);
            fileChooser.setApproveButtonText("Choose Directory");
            
            TFile ddir = new TFile(savePath);
            fileChooser.setCurrentDirectory(ddir);

            int returnVal = fileChooser.showOpenDialog(this);

            if (returnVal == WepsFileChooser.APPROVE_OPTION) 
            {
                try { destinationDirectory = new TFile(fileChooser.getSelectedFile().getCanonicalPath() + TFile.separator); } 
                catch (Exception e) { System.err.println("Error: " + e); }
            } 
            else return;
        }
        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());
    }
            
    @Override
    public void BackConvertRecursiveJMI_actionPerformed(ActionEvent evt)
    {
        TFile sourceDirectory = null;
        TFile destinationDirectory = null;
        {
            WepsFileChooser fileChooser = new WepsFileChooser(WepsFileChooser.Filetype.FILE, "", WepsFileChooser.SELECT);
            fileChooser.setFileSelectionMode(WepsFileChooser.DIRECTORIES_ONLY);
            fileChooser.setMultiSelectionEnabled(false);
            fileChooser.setDialogTitle("Select a source directory.");
            fileChooser.setAcceptAllFileFilterUsed(false);
            fileChooser.setApproveButtonText("Choose Directory");
            
            TFile ddir = new TFile(savePath);
            fileChooser.setCurrentDirectory(ddir);

            int returnVal = fileChooser.showOpenDialog(this);

            if (returnVal == WepsFileChooser.APPROVE_OPTION) 
            {
                try { sourceDirectory = new TFile(fileChooser.getSelectedFile().getCanonicalPath() + TFile.separator); } 
                catch (Exception e) { System.err.println("Error: " + e); }
            } 
            else return;
        }
        {
            WepsFileChooser fileChooser = new WepsFileChooser(WepsFileChooser.Filetype.FILE, "", WepsFileChooser.SELECT);
            fileChooser.setFileSelectionMode(WepsFileChooser.DIRECTORIES_ONLY);
            fileChooser.setMultiSelectionEnabled(false);
            fileChooser.setDialogTitle("Select a destination directory.");
            fileChooser.setAcceptAllFileFilterUsed(false);
            fileChooser.setApproveButtonText("Choose Directory");
            
            TFile ddir = new TFile(savePath);
            fileChooser.setCurrentDirectory(ddir);

            int returnVal = fileChooser.showOpenDialog(this);

            if (returnVal == WepsFileChooser.APPROVE_OPTION) 
            {
                try { destinationDirectory = new TFile(fileChooser.getSelectedFile().getCanonicalPath() + TFile.separator); } 
                catch (Exception e) { System.err.println("Error: " + e); }
            } 
            else return;
        }
        if((sourceDirectory == null) || (destinationDirectory == null)) return;
        String extension = ".man";
        if(sourceDirectory.getAbsolutePath().equals(destinationDirectory.getAbsolutePath()))
        {
            extension = "Ver15.man";
        }
        convertDirectoryToArchive(sourceDirectory, destinationDirectory, extension);
    }
    
    public void convertDirectoryToArchive(TFile sourceDirectory, TFile destinationDirectory, String newExtension)
    {
        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());
            }
        }
    }

    // here we map the tool bar buttons to the menu items
    @Override
    public void OpenJB_actionPerformed(java.awt.event.ActionEvent event) {
        setUndoDeleteStatus(false);
        OpenJMI_actionPerformed(event);
    }

    @Override
    protected void NewJB_actionPerformed(java.awt.event.ActionEvent event) {
        setUndoDeleteStatus(false);
        NewJMI_actionPerformed(event);
    }

    @Override
    protected void SaveJB_actionPerformed(java.awt.event.ActionEvent event) {
        setUndoDeleteStatus(false);
        SaveJMI_actionPerformed(event);
    }

    @Override
    protected void CutJB_actionPerformed(java.awt.event.ActionEvent event) {
        setUndoDeleteStatus(false);
        CutJMI_actionPerformed(event);
    }

    @Override
    protected void CopyJB_actionPerformed(java.awt.event.ActionEvent event) {
        setUndoDeleteStatus(false);
        CopyJMI_actionPerformed(event);
    }

    //CancelButton_actionPerformed(java.awt.event.ActionEvent evt)
    @Override
    protected void PasteJB_actionPerformed(java.awt.event.ActionEvent event) {
        setUndoDeleteStatus(false);
        PasteJMI_actionPerformed(event);
    }

    @Override
    protected void SortJB_actionPerformed(java.awt.event.ActionEvent event) {
        setUndoDeleteStatus(false);
        SortJMI_actionPerformed(event);
    }

    @Override
    protected void HelpJB_actionPerformed(java.awt.event.ActionEvent event) {
        HelpJMI_actionPerformed(event);
    }

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

        NotesJMI_actionPerformed(evt);
    }

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

        ExitJMI_actionPerformed(evt);
    }

    @Override
    public void JBToggleCalib_itemStateChanged(java.awt.event.ItemEvent evt) {
    }

    @Override
    public void JBT_calib_actionPerformed(java.awt.event.ActionEvent evt) {
        ToggleCalibJMI_actionPerformed(evt);
    }

    /**
     * This method knows what to do when state change occurs for a particular object or item.
     *
     * @param e The state change that occured for a particular item.
     */
    @Override
    public void itemStateChanged(ItemEvent e) {
    }

    /**
     * The action to be taken based on the event that happens.
     *
     * @param e The event that is to be recognised for action to be performed.
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        //System.out.println("MCrew: actionPerformed: name = " + e);
    }

    @Override
    public void McrewB_componentResized(java.awt.event.ComponentEvent event) {
        validate();
        Dimension size = event.getComponent().getSize();

        if (size.getHeight() < MIN_HEIGHT) {
            size.height = MIN_HEIGHT;
        }
        if (size.getWidth() < MIN_WIDTH) {
            size.width = MIN_WIDTH;
        }

        this.setSize(size);
        size.height -= 60;
        size.width -= 30;
        JP_base.setSize(size);

        JP_toolBar.setSize(JP_base.getWidth() - (2 * sideOffSet), 32);
        JP_toolBar.setLocation(sideOffSet, componentOffSet);

        JSP_rotFile.setSize(JP_base.getWidth() - (2 * sideOffSet), 40);
        JSP_rotFile.setLocation(sideOffSet, JP_toolBar.getHeight() + (2 * componentOffSet));

        int otherCompHeight = JP_toolBar.getHeight() + JSP_rotFile.getHeight();

        JP_main.setSize(JP_base.getWidth() - (2 * sideOffSet), JP_base.getHeight()
                - (otherCompHeight + 3 * componentOffSet + sideOffSet));
        JP_main.setLocation(sideOffSet, otherCompHeight + (3 * componentOffSet));

        if (table != null) {

            table.setSize(JP_main.getWidth() - (2 * sideOffSet), JP_main.getHeight() - sideOffSet);
            table.setLocation(2, 2);
            //System.out.println("M_MBcR: Table Height : " + table.getHeight() + " & Width : " + table.getWidth());
        }

        validate();
        repaint();
    }

    //
    // Converts a WEPS management file into an XML skeleton file.
    //
    @Override
    public void ManToSkelJMI_actionPerformed(java.awt.event.ActionEvent event, boolean singleFileOnly) {
        try {
            // Step 1: Prompt for the source .man files to convert
            String m_fileName = "";
            String skelfile = "";
            String skelfileShort = "";
            String fileNameShort = "";
            Vector<String> createdFiles = new Vector<>();

            WepsFileChooser fileChooser = new WepsFileChooser(WepsFileChooser.Filetype.FILE, "", WepsFileChooser.SELECT);
            fileChooser.setFileSelectionMode(WepsFileChooser.FILES_ONLY);
            if (singleFileOnly == false) {
                fileChooser.setMultiSelectionEnabled(true);
                fileChooser.setAcceptAllFileFilterUsed(false);
                fileChooser.setApproveButtonText("Select Files");
            } else {
                fileChooser.setMultiSelectionEnabled(false);
                fileChooser.setApproveButtonText("Choose File");
            }

            XMLSkelFilter filter = new XMLSkelFilter("man", "WEPS Management Files");
            fileChooser.setFileFilter(filter);
            fileChooser.setDialogTitle("Select a WEPS management file");

            String dir = ConfigData.getDirectoryName(XMLConstants.smanagement_template);
            TFile ddir = new TFile(dir);
            fileChooser.setCurrentDirectory(ddir);

            java.io.File[] sourceFiles = null;

            int returnVal = fileChooser.showOpenDialog(this);

            if (returnVal == WepsFileChooser.APPROVE_OPTION) {
                try {
                    // depending on whether multiple selection is enabled java uses 2 different calls to get the
                    // selected file(s).
                    if (singleFileOnly == false) {
                        sourceFiles = fileChooser.getSelectedFiles();
                    } else {
                        sourceFiles = new TFile[1];
                        sourceFiles[0] = fileChooser.getSelectedFile();
                    }
                } catch (Exception e) {
                    System.err.println("Error: " + e);
                }
            } else {
                return;
            }
            boolean doConversion = true;
            for (java.io.File sourceFile : sourceFiles) {
                try {
                    m_fileName = sourceFile.getCanonicalPath();
                    doConversion = isManFile(m_fileName);
                    if (doConversion == false) {
                        JOptionPane.showMessageDialog(this, m_fileName
                                + "\n\nSelection is not a WEPS .man file.\n\nNo Files Converted.", "WEPS Information",
                                JOptionPane.ERROR_MESSAGE);
                    }
                } catch (IOException | HeadlessException e) {
                    System.err.println("Error: " + e);
                }
            }

            if (doConversion == false) {
                return;
            }

            WepsFileChooser fileChooserMan = new WepsFileChooser(WepsFileChooser.Filetype.FILE, "", WepsFileChooser.SELECT);
            if (singleFileOnly == false) {
                fileChooserMan.setFileSelectionMode(WepsFileChooser.DIRECTORIES_ONLY);
                fileChooserMan.setMultiSelectionEnabled(false);
                fileChooserMan.setDialogTitle("Select a destination directory where the NRCS XML files will be created");
                fileChooserMan.setAcceptAllFileFilterUsed(false);
                fileChooserMan.setApproveButtonText("Choose Directory");
            } else {
                fileChooserMan.setFileSelectionMode(WepsFileChooser.FILES_ONLY);
                fileChooserMan.setDialogTitle("Select a destination ");
                fileChooserMan.setApproveButtonText("Choose File");
                fileChooserMan.setApproveButtonToolTipText("Select a NRCS XML file to be created");
                fileChooserMan.setAcceptAllFileFilterUsed(true);
                XMLSkelFilter filterMan = new XMLSkelFilter("skel", "NRCS XML Management Files(*.skel)");
                fileChooserMan.setFileFilter(filterMan);
                String targetfile = sourceFiles[0].getName();

                targetfile = Util.purgeExtensions(targetfile, ".man", ".skel") + ".skel";

                TFile target = new TFile(targetfile);
                fileChooserMan.setSelectedFile(target);
            }

            dir = ConfigData.getDirectoryName(XMLConstants.smanagement_skeleton);
            ddir = new TFile(dir);

            String skeldir = "";
            fileChooserMan.setCurrentDirectory(ddir);

            returnVal = fileChooserMan.showOpenDialog(this);
            if (returnVal == WepsFileChooser.APPROVE_OPTION) {
                try {
                    if (singleFileOnly == false) {
                        skeldir = fileChooserMan.getSelectedFile().getCanonicalPath() + TFile.separator;
                        TFile testdir = new TFile(skeldir);
                        if ((!testdir.exists()) || testdir.isFile()) {
                            JOptionPane.showMessageDialog(this, skeldir
                                    + "\n\nSelection is not a directory.", "WEPS Information",
                                    JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                    } else {
                        skelfile = fileChooserMan.getSelectedFile().getCanonicalPath() + TFile.separator;
                        TFile testFile = new TFile(skelfile);
                        if (testFile.isDirectory()) {
                            JOptionPane.showMessageDialog(this, skelfile + "\n\nSelection is not a file.", "WEPS Information",
                                    JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                    }
                } catch (HeadlessException | IOException e) {
                    System.err.println("Error: " + e);
                }
            } else {
                return;
            }
            int total = 0;
            for (java.io.File sourceFile : sourceFiles) {
                if (singleFileOnly == false) {
                    skelfile = Util.purgeExtensions(skeldir + sourceFile.getName(), ".man", ".skel") + ".skel";
                } else {
                    TFile shortName = new TFile(skelfile);

                    int end = shortName.getName().lastIndexOf(".");
                    if (end == -1) {
                        skelfile = skelfile + ".skel";
                    }
                }
                try {
                    m_fileName = sourceFile.getCanonicalPath();
                    fileNameShort = sourceFile.getName();
                } catch (IOException e) {
                    System.err.println("Error: " + e);
                }
                if (doConversion) {
                    TFile f = new TFile(skelfile);
                    skelfileShort = f.getName();

                    //System.out.println("Checking: "+skelfile);
                    if (f.exists()) {
                        if (JOptionPane.showConfirmDialog(this, "Destination file already exists. \nDo you want to overwrite "
                                + skelfileShort + "?", "File Exists", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
                            doConversion = false;
                        }
                    }
                    if (doConversion) {
                        SkeletonUpdater skel = new SkeletonUpdater();

                        // This is what really does the conversion, read the management file and then write it out
                        // as a XML skel file
                        if (skel.readWEPSManBrief(m_fileName)) {
                            if (skel.writeSkeletonXMLFile(skelfile)) {
                                createdFiles.addElement(skelfile);
                                total++;
                            } else {
                                System.out.println("Could not write skelfile: " + skelfile + "\n");
                            }
                        } else {
                            System.out.println("Could not read: " + m_fileName + "\n");
                        }
                    } else {
                        System.out.println("Do conversion reset?\n");
                    }
                } else {
                    System.out.println("Do conversion=false\n");
                }
            }

            if (singleFileOnly == true) {
                JOptionPane.showMessageDialog(this, "WEPS NRCS XML file created:\n" + skelfile, "WEPS Information",
                        JOptionPane.INFORMATION_MESSAGE);
            } else {
                if (total >= 1) {
                    JTextArea info = new JTextArea(10, 35);
                    JScrollPane js = new JScrollPane(info);
                    for (int i = 0; i < total; i++) {
                        info.append(createdFiles.elementAt(i) + "\n");
                    }
                    JOptionPane.showMessageDialog(this, js, total + " WEPS NRCS XML Management Files Created",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            }
            TVFS.umount();
        } catch (FsSyncException ex) {
            java.util.logging.Logger.getLogger(Mcrew.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * Check if this really could be a WEPS Management file.
     */
    private boolean isManFile(String fileName) {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new TFileReader(new TFile(fileName)));
            String temp;

            temp = br.readLine();

            if (temp != null) {
                if (temp.toUpperCase().contains("VERSION:")) {
                    return true;
                }
            }
        } catch (IOException e) {
            System.err.println("isManFile: " + e);
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                LOGGER.error("Error closing management file stream.", e);
            }
        }

        return false;
    }
    private boolean checked = false;

    /**
     * If refreshmcrewscreen is true, we try to open the saved data .MAN/.XML to load the most
     * recent data onto the main MCREW screen table.
     */
    public void refreshMcrewTableData() {

        //System.out.println("Mcrew: refreshMcrewTableData : Saving file");
        if ((fileName == null) || (fileName.length() == 0) || (fileName.equals(sUntitledFileName))) {
            ////System.out.println("Calling save as with fileName " + fileName);
            //SaveAsJMI_actionPerformed(event);
            return;
        }
        if (!checked) {
            if (checkAllConditions() == false) {
                saveSuccess = false;
                return; // user pressed cancel on some option, Don't save
            }
        }

        //If the use doesnt opens a file or opens a tamplate of a file
        // and wothout making any changes saves the file, then the "absFileName"
        // should reflect this saved file.
        absFileName = filePathName;

        if (dataChanged == false) {
            return;
        }
        if ((savePath == null) || (savePath.length() == 0)) {
            savePath = ConfigData.getDirectoryName(XMLConstants.smanagement_template);

            ////System.out.println("Data changed " + dataChanged);
        }
        String fullPathFileName = savePath + TFile.separator + fileName;
        //System.out.println("MCREW : refreshMcrewTableData : Saving file " + fullPathFileName);
        //Get the parent location of this file, see if its writable,if not
        //display the warning message and return.-by Neha
        TFile mcrewFile = new TFile(fullPathFileName);
        TFile parentFile = new TFile(mcrewFile.getParentFile());
        //System.out.println("MCREW : refreshMcrewTableData : parent file"+mcrewFile.getParent()
        //+" can we write into this location:"+parentFile.canWrite());
        if (parentFile.canWrite() == false) {
            JOptionPane.showMessageDialog(this, "The File location Specified is not writable\n "
                    + fullPathFileName, "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        data.writeDataFile(savePath + TFile.separator + fileName);
        //update the abs file path name to this path of the saved file
        absFileName = fullPathFileName;

        setDataChanged(false);
        saveSuccess = true;

        if (refreshMcrewScreen.equals("true")) {
            openRefreshedFile(absFileName);
            refreshMcrewScreen = "false";
        }

        //System.out.println("Returning after saving file");
    }
    private PropertyChangeSupport changes = new PropertyChangeSupport(this);

    /**
     * Add a PropertyChangeListener to the listener list. The listener is registered for all
     * properties
     *
     * @param l PropertyChangeListener to be added
     */
    @Override
    public void addPropertyChangeListener(PropertyChangeListener l) {
        changes.addPropertyChangeListener(l);
    }

    /**
     * Remove a PropertyChangeListener from the listener list. This removes a PropertyChangeListener
     * that was registered for all properties.
     *
     * @param l The PropertyChangeListener to be removed
     */
    @Override
    public void removePropertyChangeListener(PropertyChangeListener l) {
        changes.removePropertyChangeListener(l);
    }

    // Filter for selection skeleton XML files
    private static class XMLSkelFilter extends javax.swing.filechooser.FileFilter {

        String fext;
        String fdescription;

        XMLSkelFilter(String exttext, String desc) {
            fext = exttext;
            fdescription = desc;
        }

        //Accept all directories and all XML/SKEL files.
        @Override
        public boolean accept(java.io.File f) {
            if (f.isDirectory()) {
                return true;
            }
            String ext = null;
            String s = f.getName();
            int i = s.lastIndexOf('.');

            if (i > 0 && i < s.length() - 1) {
                ext = s.substring(i + 1).toLowerCase();
            }
            String extension = ext;
            if (extension != null) {
                if (extension.equals(fext)) {
                    return true;
                } else {
                    return false;
                }
            }

            return false;
        }

        // The description of this filter
        @Override
        public String getDescription() {
            return fdescription;
        }
    }

    // Converts an NRCS skeleton XML file into a full WEPS management file.
    //This also gives the user the option of resolving unknown crops or operations.
    @Override
    public void SkelToManJMI_actionPerformed(java.awt.event.ActionEvent event, boolean singleFileOnly) {
        try {
            // Step 1: Prompt for the source .XML/SKEL file that will be converted
            String fromFileName = "";
            String toPath = "";
            String manfileShort = "";
            String fileNameShort = "";
            Vector<String> createdFiles = new Vector<>();

            WepsFileChooser fileChooser = new WepsFileChooser(WepsFileChooser.Filetype.FILE, "", WepsFileChooser.SELECT);
            fileChooser.setFileSelectionMode(WepsFileChooser.FILES_ONLY);
            if (singleFileOnly == false) {
                fileChooser.setMultiSelectionEnabled(true);
                fileChooser.setApproveButtonText("Select Files");
            } else {
                fileChooser.setMultiSelectionEnabled(false);
            }
            XMLSkelFilter filter = new XMLSkelFilter("skel", "NRCS XML Skeleton Management Files(*.skel)");
            fileChooser.setFileFilter(filter);
            fileChooser.setDialogTitle("Select an NRCS skeleton XML management file");

            String dir = ConfigData.getDirectoryName(XMLConstants.smanagement_skeleton);
            TFile ddir = new TFile(dir);
            fileChooser.setCurrentDirectory(ddir);

            int returnVal = fileChooser.showOpenDialog(this);
            java.io.File[] sourceFiles = null;

            if (returnVal == WepsFileChooser.APPROVE_OPTION) {
                try {
                    if (singleFileOnly == false) {
                        sourceFiles = fileChooser.getSelectedFiles();
                    } else {
                        sourceFiles = new TFile[1];
                        sourceFiles[0] = fileChooser.getSelectedFile();
                    }
                } catch (Exception e) {
                    System.err.println("Error: " + e);
                }
            } else {
                return;
            }
            WepsFileChooser fileChooserMan = new WepsFileChooser(WepsFileChooser.Filetype.FILE, "", WepsFileChooser.SELECT);
            fileChooserMan.setMultiSelectionEnabled(false);
            if (singleFileOnly == false) {
                // Step 2: Have user select the WEPS management directory where the files will be written
                fileChooserMan.setFileSelectionMode(WepsFileChooser.DIRECTORIES_ONLY);
                fileChooserMan.setDialogTitle("Select a destination WEPS management directory where the files will be created");
                fileChooserMan.setApproveButtonText("Choose Directory");
                fileChooserMan.setApproveButtonToolTipText("Select a destination WEPS management directory "
                        + "where the files will be created");
                fileChooserMan.setAcceptAllFileFilterUsed(false);
            } else {
                fileChooserMan.setDialogTitle("Select a destination WEPS management file that will be created");
                fileChooserMan.setApproveButtonText("Choose File");
                fileChooserMan.setApproveButtonToolTipText("Select a destination WEPS management file where to be created");
                fileChooserMan.setAcceptAllFileFilterUsed(true);
                XMLSkelFilter filterMan = new XMLSkelFilter("man", "WEPS Management Files(*.man)");
                fileChooserMan.setFileFilter(filterMan);
                String targetfile = sourceFiles[0].getName();

                if (targetfile.endsWith(".skel")) {
                    targetfile = Util.purgeExtensions(targetfile, ".man", ".skel") + ".man";
                } else {
                    targetfile = Util.purgeExtensions(targetfile, ".man", ".skel") + ".skel";
                }
                TFile target = new TFile(targetfile);
                fileChooserMan.setSelectedFile(target);
            }

            dir = ConfigData.getDirectoryName(XMLConstants.smanagement_template);
            ddir = new TFile(dir);

            String mandir = "";

            fileChooserMan.setCurrentDirectory(ddir);

            returnVal = fileChooserMan.showOpenDialog(this);
            if (returnVal == WepsFileChooser.APPROVE_OPTION) {
                try {
                    if (singleFileOnly == false) {
                        mandir = fileChooserMan.getSelectedFile().getCanonicalPath() + TFile.separator;
                        TFile testdir = new TFile(mandir);
                        if ((!testdir.exists()) || testdir.isFile()) {
                            JOptionPane.showMessageDialog(this, mandir + "\n\nSelection is not a directory.",
                                    "WEPS Information", JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                    } else {
                        toPath = fileChooserMan.getSelectedFile().getCanonicalPath() + TFile.separator;
                        TFile testFile = new TFile(toPath);
                        if (testFile.isDirectory()) {
                            JOptionPane.showMessageDialog(this, toPath + "\n\nSelection is not a file.",
                                    "WEPS Information", JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                    }
                } catch (HeadlessException | IOException e) {
                    System.err.println("Error: " + e);
                }
            } else {
                return;
            }
            SkelImportPanel skelimport = new SkelImportPanel(this, "Operation or crop not found",
                    true, ManageData.WriteFileMode.FROM_NRCS);

            String opDBDir = ConfigData.getDirectoryName(XMLConstants.soperation);
            String cropDBDir = ConfigData.getDirectoryName(XMLConstants.scrop);

            if (!skelimport.setDatabases(opDBDir, cropDBDir)) {
                //something went wrong, quit
                return;
            }

            //
            // Loop through each of the skeleton files and convert them to a full weps management file.
            //
            int total = 0;
            String newstr = "";
            boolean overwriteAll = false;
            boolean skipAll = false;
            Stack<ConversionTask<TFile>> stack = new Stack<ConversionTask<TFile>>();
            for (java.io.File from : sourceFiles) {
                if (singleFileOnly == false) {
                    //TODO: rot extension
                    toPath = mandir + Util.purgeExtensions(from.getName(), ".man", ".skel") + ".man";
                } else {
                    TFile shortName = new TFile(toPath);

                    int end = shortName.getName().lastIndexOf(".");
                    if (end == -1) {
                        toPath = toPath + ".man";
                    }
                }

                TFile to = new TFile(toPath);

                stack.push(new ConversionTask<TFile>(new TFile(from), new TFile(to)));
            }

            ConversionContext.enter(stack);
            try {
                int popped = 0;
                while (!stack.empty()) {

                    skelimport.setProgress(popped, popped + stack.size());

                    ConversionTask<TFile> task = stack.pop();
                    ConversionContext.getCurrent().task = task;
                    popped++;

                    TFile fromFile = task.getFrom();
                    TFile toFile = task.getTo();

                    manfileShort = toFile.getName();

                    try {
                        fromFileName = fromFile.getCanonicalPath();
                        fileNameShort = toFile.getName();
                    } catch (IOException e) {
                        System.err.println("Error: " + e);
                    }

                    boolean doconversion = true;
                    while (toFile.exists() && !overwriteAll && !skipAll) {
                        String[] options = {"Overwrite", "Overwrite All", "Rename", "Skip", "Skip All"};
                        int result = JOptionPane.showOptionDialog(this,
                                "Destination management file already exists.\n" + toFile.getName(),
                                "File Exists", 0, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                        if (result == 0) {
                            //overwrite the file.
                            doconversion = true;
                            break;
                        } else if (result == 1) {
                            //overwrite all
                            doconversion = true;
                            overwriteAll = true;
                            break;
                        } else if (result == 2) {
                            //select a new file name.
                            //show the proper file chooser based on if toFile is man or rot!
                            WepsFileChooser wfc;
                            if (WepsFileTypes.Management.accept(toFile)) {
                                wfc = WepsFileChooser.create(WepsFileChooser.Action.Create,
                                        new TFile(toFile.getParentFile()), WepsFileTypes.Management);
                            } else {
                                wfc = WepsFileChooser.create(WepsFileChooser.Action.Create,
                                        new TFile(toFile.getParentFile()), WepsFileTypes.Rotation);
                            }

                            wfc.setSelectedFile(toFile);
                            wfc.setPersitSelectedFile(false);
                            if (wfc.showDialog(this) == WepsFileChooser.APPROVE_OPTION) {
                                toPath = wfc.getSelectedFile().getPath();
                                toFile = new TFile(wfc.getSelectedFile());

                                //upate the current task
                                task.to = toFile;
                            }
                        } else if (result == 3) {
                            //skip
                            doconversion = false;
                            break;
                        } else if (result == 4) {
                            //skip all
                            skipAll = true;
                            doconversion = false;
                            break;
                        }
                    }

                    if (toFile.exists() && overwriteAll) {
                        doconversion = true;
                    }
                    if (toFile.exists() && skipAll) {
                        doconversion = false;
                    }
                    if (doconversion) {
                        if (skelimport.skel2man(fromFileName, toFile.getAbsolutePath())) {
                            total++;
                            createdFiles.addElement(toFile.getAbsolutePath());
                        }
                    }
                }
            } finally {
                ConversionContext.exit();
            }

            if (singleFileOnly == true) {
                JOptionPane.showMessageDialog(this, total + " WEPS management files written to:\n\n "
                        + toPath, "WEPS Information", JOptionPane.INFORMATION_MESSAGE);
            } else {
                if (total >= 1) {
                    JTextArea info = new JTextArea(10, 35);
                    info.setEditable(false);
                    JScrollPane js = new JScrollPane(info);
                    for (int i = 0; i < total; i++) {
                        info.append(createdFiles.elementAt(i) + "\n");
                    }
                    JOptionPane.showMessageDialog(this, js, total
                            + " WEPS Management Files Created", JOptionPane.INFORMATION_MESSAGE);
                }
            }
            logUnknownOperationsAndCrops(skelimport, null);
            TVFS.umount();
        } catch (FsSyncException ex) {
            java.util.logging.Logger.getLogger(Mcrew.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    //called when user requests conversion of WEPS Management files to NRCS XML format recursively.- added by Neha
    @Override
    public void ManToSkelRec_actionPerformed(java.awt.event.ActionEvent evt) {

        if (!convertRec(MAN2SKELREC)) {
            return;
        }
        //set the cursor to wait cursor on the Mcrew screen
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        XMLManagementUpdater updater = new XMLManagementUpdater();
        //Get all the man files in this directory
        List<String> manFiles = updater.onlyRecursion(sourceDirName, "man");

        LOGGER.trace("files to convert:");
        for (int i = 0; manFiles != null && i < manFiles.size(); i++) {
            LOGGER.trace(manFiles.get(i));
        }

        if (manFiles == null) {
            manFiles = Collections.emptyList();
        }
        targetDirName = targetDirName != null ? targetDirName : "";
        sourceDirName = sourceDirName != null ? sourceDirName : "";
        int returnCode = convertToManOrSkelRec(sourceDirName, targetDirName,
                manFiles, MAN2SKELREC, ManageData.WriteFileMode.NORMAL);
        if (returnCode == 0) {
            LOGGER.error("Error in the path of the management directory. Management directory MUST be in db/man");
        } else if (returnCode == 2) {
            LOGGER.debug("User pressed cancel all button");
        } else if (returnCode == 3) {
            LOGGER.error("Error in selecting the target directory");
        } else if (returnCode == 4) {
            LOGGER.error("Error in value of type variable");
        } else if (returnCode == 5) {
            LOGGER.error("Could not write Skeleton file");
        } else if (returnCode == 6) {
            LOGGER.error("Could not read the Management file");
        }

        //set the cursor back to default on the Mcrew screen
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    } //end of ManToSkelRec_actionPerformed

    //This method handles the WepsFileChooser stuff for the recursive conversion
    //of ManToSkel and SkelToMan - added by Neha
    boolean convertRec(int type) {
        String sourceDir;
        String dir;
        String targetDir = "";
        WepsFileChooser fileChooserSkel = new WepsFileChooser(WepsFileChooser.Filetype.FILE, "", WepsFileChooser.SELECT);
        fileChooserSkel.setFileSelectionMode(WepsFileChooser.DIRECTORIES_ONLY);
        fileChooserSkel.setMultiSelectionEnabled(false);

        fileChooserSkel.setAcceptAllFileFilterUsed(false);
        if (type == 0) {
            fileChooserSkel.setDialogTitle("Select a directory where all WEPS management "
                    + "files are to be converted to Skeleton Management files");
            sourceDir = ConfigData.getDirectoryName(XMLConstants.smanagement_template);
        } else if (type == 1) {
            fileChooserSkel.setDialogTitle("Select a directory where all Skeleton management "
                    + "files are to be converted to Weps Management files");
            sourceDir = ConfigData.getDirectoryName(XMLConstants.smanagement_skeleton);
        } else {
            return false;
        }
        TFile ddir = new TFile(sourceDir);

        fileChooserSkel.setApproveButtonText("Choose Directory");
        fileChooserSkel.setCurrentDirectory(ddir);

        int returnVal = fileChooserSkel.showOpenDialog(this);
        if (returnVal == WepsFileChooser.APPROVE_OPTION) {
            try {
                sourceDir = fileChooserSkel.getSelectedFile().getCanonicalPath() + TFile.separator;
                TFile testdir = new TFile(sourceDir);
                if ((!testdir.exists()) || testdir.isFile()) {
                    JOptionPane.showMessageDialog(this, sourceDir
                            + "\n\nSelection is not a directory.", "WEPS Information", JOptionPane.ERROR_MESSAGE);
                    return false;
                }
            } catch (HeadlessException | IOException e) {
                System.err.println("Error: " + e);
            }
        } else {
            return false;
        }

        // Step 2: Have user select the destination directory where the files will be written
        WepsFileChooser fileChooserMan = new WepsFileChooser(WepsFileChooser.Filetype.FILE, "", WepsFileChooser.SELECT);
        fileChooserMan.setMultiSelectionEnabled(false);
        fileChooserMan.setFileSelectionMode(WepsFileChooser.DIRECTORIES_ONLY);
        fileChooserMan.setApproveButtonText("Choose Directory");
        fileChooserMan.setAcceptAllFileFilterUsed(false);

        if (type == 0) {
            fileChooserMan.setDialogTitle("Select a destination directory where the Skeleton Management files will be created");
            fileChooserMan.setApproveButtonToolTipText("Select a destination directory where the "
                    + "Skeleton Management files will be created");
            dir = ConfigData.getDirectoryName(XMLConstants.smanagement_skeleton);
        } else if (type == 1) {
            fileChooserMan.setDialogTitle("Select a destination WEPS management directory where the files will be created");
            fileChooserMan.setApproveButtonToolTipText("Select a destination WEPS management "
                    + "directory where the files will be created");
            dir = ConfigData.getDirectoryName(XMLConstants.smanagement_template);
        } else {
            return false;
        }

        TFile mdir = new TFile(dir);
        fileChooserMan.setCurrentDirectory(mdir);

        returnVal = fileChooserMan.showOpenDialog(this);
        if (returnVal == WepsFileChooser.APPROVE_OPTION) {
            try {
                targetDir = fileChooserMan.getSelectedFile().getCanonicalPath() + TFile.separator;
                TFile testdir = new TFile(targetDir);
                if ((!testdir.exists()) || testdir.isFile()) {
                    JOptionPane.showMessageDialog(this, targetDir + "\n\nSelection is not a directory.",
                            "WEPS Information", JOptionPane.ERROR_MESSAGE);
                    return false;
                }
            } catch (HeadlessException | IOException e) {
                System.err.println("Error: " + e);
            }
        } else {
            return false;
        }
        sourceDirName = sourceDir;
        targetDirName = targetDir;
        //System.out.println("Mcrew:convertRec:sourceDirName:"+sourceDirName);
        //System.out.println("Mcrew:convertRec:targetDirName:"+targetDirName);
        return true;
    } //end of convertRec method

    //called when user has requested to convert NRCS XML Management files into WEPS format recursively.
    @Override
    public void SkelToManRec_actionPerformed(java.awt.event.ActionEvent evt) {
        if (!convertRec(SKEL2MANREC)) {
            return;
        }
        //set the cursor to wait cursor on the Mcrew screen
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        XMLManagementUpdater updater = new XMLManagementUpdater();
        //Get all the skel files in this directory
        List<String> skelFiles = updater.onlyRecursion(sourceDirName, "skel");
        LOGGER.trace("Files to convert:");
        for (int i = 0; skelFiles != null && i < skelFiles.size(); i++) {
            LOGGER.trace(skelFiles.get(i));
        }

        if (skelFiles == null) {
            skelFiles = Collections.emptyList();
        }

        targetDirName = targetDirName != null ? targetDirName : "";
        sourceDirName = sourceDirName != null ? sourceDirName : "";
        int returnCode = convertToManOrSkelRec(sourceDirName, targetDirName, skelFiles,
                SKEL2MANREC, ManageData.WriteFileMode.FROM_NRCS);
        if (returnCode == 0) {
            LOGGER.error("error in the path of the skeleton directory. skeleton dir MUST be in db/skel");
        } else if (returnCode == 2) {
            LOGGER.debug("User pressed cancel all button");
        } else if (returnCode == 3) {
            LOGGER.error("Error in selecting the target directory");
        } else if (returnCode == 4) {
            LOGGER.error("Error in value of type variable");
        }

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

        //JOptionPane.showMessageDialog(null,files+" NRCS XML skeleton Files converted to WEPS management files",
        //"WEPS Information",JOptionPane.INFORMATION_MESSAGE);
    }

    //This method takes the skeleton/Management files vector and converts them into management/ skeleton files - added by Neha
    int convertToManOrSkelRec(String sourceDir, String targetDir, List<String> srcFiles,
            int type, ManageData.WriteFileMode mode) {

        int total = 0;
        String newstr = "";
        String targetFile_newPath = null;

        List<String> onlyDirs = new Vector<String>();
        List<String> onlySourceFiles = new Vector<String>();
        List<String> onlyTargetFiles = new Vector<String>();
        List<TFile> createdFiles = new Vector<TFile>();

        SkelImportPanel skelimport = new SkelImportPanel(this, "Operation or crop not found", true, mode);
        String opDBDir = ConfigData.getDirectoryName(XMLConstants.soperation);
        String cropDBDir = ConfigData.getDirectoryName(XMLConstants.scrop);

        if (!skelimport.setDatabases(opDBDir, cropDBDir)) {
            //something went wrong
            return 0;
        }

        //System.out.println("sourceDir:"+sourceDir+"  targetDir:"+targetDir);
        //We need to get one directory level above that specified in the sourceDir
        //path so that the entire directory structure will be created - neha
        //get rid of the final '\' in the sourceDir path if present
        if (sourceDir.endsWith("\\")) {
            sourceDir = sourceDir.substring(0, sourceDir.length() - 1);
        }
        //Go one directory level above the given path and keep the '\' at the end of the path
        int finalIndex = Math.max(sourceDir.lastIndexOf("\\"), sourceDir.lastIndexOf("/"));
        sourceDir = sourceDir.substring(0, finalIndex + 1);
        for (String entry : srcFiles) {
            int pathEnd = sourceDir.length();

            int entryLength = entry.length();
            String entryNewPath = targetDir + entry.substring(pathEnd, entryLength);
            //System.out.println("MCrew:ConvertToManOrSkelRec:entryNewPath:"+entryNewPath);
            boolean skelOrmanFile = false;
            if (type == 0) {
                skelOrmanFile = entry.endsWith(".man");
            } else if (type == 1) {
                skelOrmanFile = entry.endsWith(".skel");
            } else {
                return 4;
            }
            if (skelOrmanFile == false) {
                onlyDirs.add(entryNewPath);
            } else {
                int end = 0;
                //Remove all *.man and *.skel extensions from the source file
                newstr = Util.purgeExtensions(entryNewPath, ".skel", ".man", ".rot");

                if (type == 0) {
                    targetFile_newPath = newstr + ".skel";
                    onlySourceFiles.add(entry); //source man files
                    onlyTargetFiles.add(targetFile_newPath); //destination skeleton files
                } else if (type == 1) {
                    targetFile_newPath = newstr + ".man";
                    onlyTargetFiles.add(targetFile_newPath); //destination man files
                    onlySourceFiles.add(entry); //source skeleton files
                } else {
                    return 4;
                }
            } //end of else
        }
        //do the conversion from source [skeleton or man] files to target [man or skeleton] files
        boolean overwriteAll = false;
        boolean skipAll = false;
        boolean doconversion = true;

        //prepare conversion stack
        Stack<ConversionTask<TFile>> stack = new Stack<ConversionTask<TFile>>();
        for (int i = 0; i < onlySourceFiles.size(); i++) {
            stack.push(new ConversionTask<TFile>(new TFile(onlySourceFiles.get(i)), new TFile(onlyTargetFiles.get(i))));
        }

        ConversionContext.enter(stack);
        try {
            int popped = 0;
            while (!stack.empty()) {
                skelimport.altPicked = true;

                skelimport.setProgress(popped, popped + stack.size());

                ConversionTask<TFile> task = stack.pop();
                ConversionContext.getCurrent().task = task;
                popped++;

                TFile fromFile = task.getFrom();
                TFile toFile = task.getTo();

                popped++;

                String toPath = toFile.getAbsolutePath();

                LOGGER.debug("Converting: " + (popped) + "/" + stack.size());

                while (toFile.exists() && !overwriteAll && !skipAll) {
                    String[] options = {"Overwrite", "Overwrite All Existing", "Rename", "Skip", "Skip All Existing"};
                    int result = JOptionPane.showOptionDialog(this,
                            "Destination management file already exists.\n" + toFile.getName(),
                            "File Exists", 0, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                    if (result == 0) {
                        //overwrite the file.
                        doconversion = true;
                        break;
                    } else if (result == 1) {
                        //overwrite all
                        doconversion = true;
                        overwriteAll = true;
                        break;
                    } else if (result == 2) {
                        //select a new file name.
                        WepsFileChooser wfc;
                        if (WepsFileTypes.Management.accept(toFile)) {
                            wfc = WepsFileChooser.create(WepsFileChooser.Action.Create,
                                    new TFile(toFile.getParentFile()), WepsFileTypes.Management);
                        } else if (WepsFileTypes.Rotation.accept(toFile)) {
                            wfc = WepsFileChooser.create(WepsFileChooser.Action.Create,
                                    new TFile(toFile.getParentFile()), WepsFileTypes.Rotation);
                        } else {
                            wfc = WepsFileChooser.create(WepsFileChooser.Action.Create,
                                    new TFile(toFile.getParentFile()), WepsFileTypes.Skeleton);
                        }

                        TFile file = new TFile(toPath);
                        file = Util.incrementFileName(file);
                        wfc.setSelectedFile(file);
                        wfc.setPersitSelectedFile(false);
                        if (wfc.showDialog(this) == WepsFileChooser.APPROVE_OPTION) {
                            toFile = new TFile(wfc.getSelectedFile());
                            toPath = toFile.getAbsolutePath();
                            //upate the current task
                            task.to = toFile;
                        }
                    } else if (result == 3) {
                        //skip
                        doconversion = false;
                        break;
                    } else if (result == 4) {
                        //skip all
                        skipAll = true;
                        doconversion = false;
                        break;
                    }
                }

                if (!toFile.exists()) {
                    doconversion = true;
                } else if (toFile.exists() && overwriteAll) {
                    doconversion = true;
                } else if (toFile.exists() && skipAll) {
                    doconversion = false;
                }
                if (doconversion) {
                    if (type == 0) {
                        SkeletonUpdater skel = new SkeletonUpdater();
                        // This is what really does the conversion, read the management file and
                        // then write it out as a XML skel file
                        if (skel.readWEPSManBrief(fromFile.getAbsolutePath())) {
                            if (skel.writeSkeletonXMLFile(toFile.getAbsolutePath())) {
                                createdFiles.add(toFile);
                                total++;
                            } else {
                                logUnknownOperationsAndCrops(skelimport, null);
                                return 5;
                            }
                        } else {
                            logUnknownOperationsAndCrops(skelimport, null);
                            return 6;
                        }
                    } else if (type == 1) {
                        if (skelimport.skel2man(fromFile.getAbsolutePath(), toFile.getAbsolutePath())) {
                            Logger.getLogger(Mcrew.class).debug("Converting file: " + fromFile);
                            total++;
                            createdFiles.add(toFile);
                        } else {
                            Logger.getLogger(Mcrew.class).error("Could not convert Skel file: " + fromFile);
                        }
                    } else {
                        logUnknownOperationsAndCrops(skelimport, null);
                        return 4;
                    }
                } //end of if(doconversion) loop
                if (skelimport.skipRemainingFlag) {
                    //User is skipping the remaining files.
                    Logger.getLogger(Mcrew.class).info("Skipping remaining files.");
                    break;
                } else if (skelimport.cancelAllFlag) {
                    //Delete all the created files.
                    for (TFile tempFile : createdFiles) {
                        try {
                            tempFile.rm();
                        } catch (IOException e) {
                            LOGGER.warn(String.format("Unable to delete file, \"%s\".  Will retry on application exit.",
                                    tempFile.getAbsolutePath()));
                            tempFile.deleteOnExit();

                        }
                    }
                    //All the files are deleted.  Now remove the directories if we can.
                    purgeDirectoryStructure(new TFile(targetDir), true);
                    return 2;
                }
            } //end of for loop on onlyTargetFiles vector
        } finally {
            ConversionContext.exit();
        }
        String text = "";
        if (total >= 1) {
            StringBuilder buffer = new StringBuilder();
            for (int i = 0; i < total; i++) {
                buffer.append(createdFiles.get(i).getAbsolutePath());
                buffer.append("\n");
            }
            text = buffer.toString();
        } else {
            text = "No files created.";
        }
        String logFile = new TFile(ConfigData.getConfigDir(), "RUSLE2_Translation.log").getAbsolutePath();
        if (type == 0) {
            WepsMessageDialog.showScrollableMessage(this, total + " Skeleton Files Created", text, logFile,
                    WepsMessageDialog.OK_OPTION | WepsMessageDialog.SAVE_OPTION, JOptionPane.INFORMATION_MESSAGE);
        } else if (type == 1) {
            WepsMessageDialog.showScrollableMessage(this, total + " WEPS Management Files Created", text, logFile,
                    WepsMessageDialog.OK_OPTION | WepsMessageDialog.SAVE_OPTION, JOptionPane.INFORMATION_MESSAGE);
        } else {
            return 4;
        }
        logUnknownOperationsAndCrops(skelimport, null);

        return 1;
    } //end of method convertToManRec

    private void purgeDirectoryStructure(TFile dir, boolean first) {
        if (!dir.isDirectory()) {
            return;
        }
        for (java.io.File child : dir.listFiles()) {
            purgeDirectoryStructure(new TFile(child), false);
        }
        if (!first && dir.listFiles().length == 0) {
            try {
                dir.rm();
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }

    private void logUnknownOperationsAndCrops(SkelImportPanel skelimport, String dir) {
        //Check if we had any unknown crops or operations
        if (skelimport.hadUnknownCrop() || skelimport.hadUnknownOperation()) {
            try {
                //write to the project directory.
                if (dir == null) {
                    //Use the project directory
                    dir = "mcrew_cfg";
                }
                TFile translationFile = new TFile(ConfigData.getSkelTranslationPath());
                TFile file = new TFile(translationFile.getParentFile(), ConfigData.sDefaultSKEL_LOG);
                //Set to true so we append to the log.
                TFileWriter fw = new TFileWriter(file, true);
                try (BufferedWriter out = new BufferedWriter(fw)) {
                    out.write("#SKEL Conversion: " + new Date().toString());
                    out.newLine();
                    out.write("[Unkown Operations]");
                    out.newLine();
                    String spacer = " ";
                    Enumeration<String> enumOperations = skelimport.getUnknownOperations().elements();
                    while (enumOperations.hasMoreElements()) {
                        out.write(spacer + enumOperations.nextElement());
                        out.newLine();
                    }

                    out.write("[Unkown Crops]");
                    out.newLine();
                    Enumeration<String> enumCrops = skelimport.getUnknownCrops().elements();
                    while (enumCrops.hasMoreElements()) {
                        out.write(spacer + enumCrops.nextElement());
                        out.newLine();
                    }
                    out.write("#End of SKEL Conversion");
                    out.newLine();
                    out.newLine();
                }
                System.out.println("Wrote SKEL log to " + file.getCanonicalFile());
            } catch (IOException e) {
                System.err.println("There was an error writing the skel ops/crop log.");
            }
        }
    }

    /*
     public Table getTable(){
     return table;
     }
     */
    /* This code is for the pop-up menu
     */
    class PopupListener extends MouseAdapter {

        @Override
        public void mousePressed(MouseEvent e) {
            ////System.out.println("Mcrew: mousepressed:");
            maybeShowPopup(e);
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            ////System.out.println("Mcrew: released:");
            maybeShowPopup(e);
        }

        private void maybeShowPopup(MouseEvent e) {
            if (e.isPopupTrigger()) {
                e.consume();
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        }
    }

    // SymAction is overridden here to allow the popup menu objects to
    // be included in the list
    class SymAction implements java.awt.event.ActionListener {

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

            Object object = event.getSource();

            if (object == popCutJMI) {
                CutJMI_actionPerformed(event);
            } else if (object == popCopyJMI) {
                CopyJMI_actionPerformed(event);
            } else if (object == popPasteJMI) {
                PasteJMI_actionPerformed(event);
            } else if (object == popDeleteJMI) {
                DeleteJMI_actionPerformed(event);
            } else if (object == popUndoDeleteJMI) {
                UndoDeleteJMI_ActionPerformed(event);
            } else if (object == popInsertJMI) {
                InsertJMI_actionPerformed(event);
            } else if (object == popInsertOperationJMI) {
                InsertOperationJMI_actionPerformed(event);
            } else if (object == popInsertFileJMI) {
                // added by Sada
                InsertFileJMI_actionPerformed(event);
            } else if (object == popInsertFileDateAdjustedJMI) {
                // added by Sada
                InsertFileDateAdjustedJMI_actionPerformed(event);
            } else if (object == popAddRotationDateAdjustedJMI) {
                AddRotationDateAdjustedJMI_actionPerformed(event);
            } else if (object == popDrillDownScreenJMI) {
                // added by Sada
                DrillDownScreenJMI_actionPerformed(event);
            } else if (object == popSetDateJMI) {
                SetDateJMI_actionPerformed(event);
            } else if (object == popAdjustDateJMI) {
                ChangeDateJMI_actionPerformed(event);
            } else if (object == setDateJMI) {
                SetDateJMI_actionPerformed(event);
            } else if (object == calendarDateJMI) {
                CalendarDateJMI_actionPerformed(event);
            } else if (object == dateChangeDateJMI) {
                ChangeDateJMI_actionPerformed(event);
            } else if (object == dateIncrementYearJMI) {
                table.changeDates(Calendar.YEAR, 1);
            } else if (object == dateDecrementYearJMI) {
                table.changeDates(Calendar.YEAR, -1);
            } else if (object == dateIncrementMonthJMI) {
                table.changeDates(Calendar.MONTH, 1);
            } else if (object == dateDecrementMonthJMI) {
                table.changeDates(Calendar.MONTH, -1);
            } else if (object == dateIncrementWeekJMI) {
                table.changeDates(Calendar.DATE, 7);
            } else if (object == dateDecrementWeekJMI) {
                table.changeDates(Calendar.DATE, -7);
            } else if (object == dateIncrementDayJMI) {
                table.changeDates(Calendar.DATE, 1);
            } else if (object == dateDecrementDayJMI) {
                table.changeDates(Calendar.DATE, -1);
            } else if ((object == operationScreenJMI) || (object == cropScreenJMI)) {
                DrillDownScreenJMI_actionPerformed(event);
            } else if (object == addChangeOperationJMI){
                table.addColumnData(1);
            } else if(object == operationNotesJMI) {
                table.showNotes(1);
            } else if(object == addChangeCropJMI) {
                table.addColumnData(2);
            } else if(object == cropNotesJMI) {
                table.showNotes(2);
            } else if (object == setDirectionJMI) {
                SetDirectionJMI_actionPerformed(event);
            } else if (object == adjustDirectionJMI) {
                AdjustDirectionJMI_actionPerformed(event);
            } else if (object == setTozeroJMI) {
                SetToZeroJMI_actionPerformed(event);
            } else if (object == setTo45JMI) {
                SetTo45JMI_actionPerformed(event);
            } else if (object == setTo90JMI) {
                SetTo90JMI_actionPerformed(event);
            } else if (object == incrementBy15JMI) {
                IncrementBy15JMI_actionPerformed(event);
            } else if (object == decrementBy15JMI) {
                DecrementBy15JMI_actionPerformed(event);
            } else if (object == incrementBy45JMI) {
                IncrementBy45JMI_actionPerformed(event);
            } else if (object == decrementBy45JMI) {
                DecrementBy45JMI_actionPerformed(event);
            } else if (object == changeBy90JMI) {
                ChangeBy90JMI_actionPerformed(event);
                //Start here
            }
        }
    }

    private void addHelp() {
        //If the mcrew helpset has already been loaded we can skip this.
        if (Help.hasHelpSet("MCREW") == false) {
            loadHelp();
        }

        addCSH(Help.getHelpSet());
    } //end of addhelp()

    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)) {
        }
    }

    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_file, "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(JTB_main, "mcrewButtonBar_html");
        CSH.setHelpIDString(JB_new, "mcrewNewButton_html");
        CSH.setHelpIDString(JB_open, "mcrewOpenButton_html");
        CSH.setHelpIDString(JB_save, "mcrewSaveButton_html");
        CSH.setHelpIDString(JB_cut, "mcrewCutButton_html");
        CSH.setHelpIDString(JB_copy, "mcrewCopyButton_html");
        CSH.setHelpIDString(JB_paste, "mcrewPasteButton_html");
        CSH.setHelpIDString(JB_sort, "mcrewSortButton_html");
        CSH.setHelpIDString(JB_cycleFwd, "mcrewRotateFowardButton_html");
        CSH.setHelpIDString(JB_cycleBwd, "mcrewRotateBackwardButton_html");
        CSH.setHelpIDString(aboutButton, "mcrewHelpButton_html");
        CSH.setHelpIDString(helpButton, "mcrewInfoButton_html");
        CSH.setHelpIDString(JB_notes, "mcrewPencilButton_html");
        CSH.setHelpIDString(JB_close, "mcrewCloseButton_html");
        CSH.setHelpIDString(JL_yrofRot, "MCREWYrRot_html");
        CSH.setHelpIDString(JTF_rotYears, "MCREWYrRot_html");
        CSH.setHelpIDString(JP_rotationFile, "MCREWRotName_html");
        CSH.setHelpIDString(JP_main, "mcrewTableview_html");
        if(c_tbs != null)
        {
            for(String item : c_tbs.keySet())
            {
                CSH.setHelpIDString(c_tbs.get(item), "mcrewYieldButton_html");
            }
        }
    } //end of addCSH

    @Override
    public void dataChanged(JCTableDataEvent e) {
        setDataChanged(true);

        //TODO: clean this up, it is really crude
        for (ConfigData.TableView view : ConfigData.getTableViews()) {
            if (view.isAuto()) {
                if (isViewRequired(view)) {
                    handleViewToggle(view.getName(), true);
                } else {
                    handleViewToggle(view.getName(), false);
                }
            }
        }
    }

    private boolean isViewRequired(ConfigData.TableView view) {
        for (RowInfo row : data.getRows()) {
            OperationObject operation = (OperationObject) row.getDataObject("operation");
            if (operation != null) {
                for (Action action : operation.getAllActions()) {
                    for (String tagname : view.getColumnNames()) {
                        if (action.getParameterNames().contains(tagname)) {
                            return true;
                        }
                    }

                }
            }
        }
        return false;
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void DefaultViewJMI_actionPerformed(java.awt.event.ActionEvent evt) {
        for (String name : c_guiViews) {
            JCheckBoxMenuItem cmi = c_cmis.get(name);
            JToggleButton tb = c_tbs.get(name);

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

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

            table.toggleTableView(name, false);
        }
        table.toggleTableView("default", true);
    }

    /**
     *
     * @param <E>
     */
    public static class ConversionTask<E> {

        private final E from;
        private E to;

        /**
         *
         * @param from
         * @param to
         */
        public ConversionTask(E from, E to) {
            this.from = from;
            this.to = to;
        }

        /**
         *
         * @return
         */
        public E getFrom() {
            return from;
        }

        /**
         *
         * @return
         */
        public E getTo() {
            return to;
        }
    }

    /**
     *
     */
    public static class ConversionContext extends Context {

        private static final long serialVersionUID = 1L;

        Stack<ConversionTask<TFile>> stack;
        ConversionTask<TFile> task;

        /**
         *
         */
        @Override
        protected void enterAction() {

        }

        /**
         *
         */
        @Override
        protected void exitAction() {

        }

        /**
         *
         * @param stack
         */
        public static void enter(Stack<ConversionTask<TFile>> stack) {
            if (stack == null) {
                throw new IllegalStateException();
            }
            Context.enter(ConversionContext.class);

            getCurrent().stack = stack;
        }

        /**
         *
         */
        public static void exit() {
            Context.exit(ConversionContext.class);
        }

        /**
         *
         * @return
         */
        public static ConversionContext getCurrent() {
            for (Context ctx = Context.getCurrent(); ctx != null; ctx = ctx.getOuter()) {
                if (ctx instanceof ConversionContext) {
                    return (ConversionContext) ctx;
                }
            }
            return null;
        }

        /**
         *
         * @return
         */
        public static Stack<ConversionTask<TFile>> getStack() {
            ConversionContext current = getCurrent();
            return current != null ? current.stack : null;
        }

        /**
         *
         * @return
         */
        public static ConversionTask<TFile> getTask() {
            ConversionContext current = getCurrent();
            return current != null ? current.task : null;
        }
    }
    
    /**
     * Returns the table currently displayed in MCREW.
     * @return 
     */
    public Table getTable() { return table; }
}
