package usda.weru.mcrew;

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.Cursor;
import java.awt.HeadlessException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Stack;
import java.util.Vector;
//import java.util.logging.Level;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javolution.context.Context;
//import org.apache.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; 
import org.openide.util.Exceptions;
import usda.weru.util.ConfigData;
import usda.weru.util.Util;
import usda.weru.util.WepsMessageDialog;
import usda.weru.util.wepsFileChooser2.WepsFileChooser2;
import usda.weru.util.wepsFileChooser2.WepsFileTypes2;

/**
 * This class was split off from the MCREW window to save lines and increase clarity.
 * @author jonathanhornbaker
 */
public class SkelManConverter 
{
    private MCREWWindow source;
    /**
     * 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 from 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;
    private boolean recursionSelected;
    private static final Logger LOGGER = LogManager.getLogger(TablePanel.class);
    /**
     * These constants allow convertRec() method to differentiate between the 3 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 3 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 constants allow convertRec() method to differentiate between the 3 types of
     * conversions. Here - WEPP json files to Skeleton files. Similar to the above
     */
    public static final int WEPPJSON2SKELREC = 2;
    /**
     * These constants allow convertRec() method to differentiate between the 3 types of
     * conversions. Here - WEPP json files to WEPS management files. Similar to the above
     */
    public static final int WEPPJSON2WEPSMAN = 3;
    
    
    public SkelManConverter(MCREWWindow wind)
    {
        source = wind;
    }
    
    /**
     * This converts WEPP management files is JSON format to WEPS XML format
     * @param event
     * @param singleFileOnly 
     */
    public void ManToNRCS_XML(java.awt.event.ActionEvent event, boolean singleFileOnly) {
        try {
            String selected_filename = "", selected_filename_short = "";            // This (if single file) is the name of that file
            String new_skel_file = "", new_skel_file_short = "";                    // These will be the Names of the constructed file
            Vector<String> createdFiles = new Vector<>();                           // vector to store list of created files
            
            WepsFileChooser2 fileChooser = new WepsFileChooser2();
            fileChooser.enableRecCheckbox(false);
            fileChooser.createBasicFileChooser(WepsFileChooser2.SelectionType.FILES_ONLY, 
                    new XMLSkelFilter("json", "(*.json)"), singleFileOnly, 
                    "Select file to be converted to NRCS XML format.","Select WEPP .json Managment file",  null);
            fileChooser.setFileSelectionMode(WepsFileChooser2.SelectionType.FILES_AND_DIRECTORIES);
//            fileChooser.setFileFilter(
            java.io.File[] sourceFiles = null;                                      // For file or list of files
            int returnVal = fileChooser.showDialog(source);                         // Denotes success of the file selection process
            
            if (returnVal == WepsFileChooser2.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;                                                             // Unapproved options should end this sequence
            }
            
            boolean doConversion = true;
            for (java.io.File sourceFile : sourceFiles) {
                try {
                    selected_filename = sourceFile.getCanonicalPath();
                    doConversion = isWEPPfile(selected_filename);
                    if (doConversion == false) {
                        break;
                    }
                } catch (IOException | HeadlessException e) {
                    System.err.println("Error: " + e);
                }
            }
            
            if (!doConversion) {                                                    // don't convert any files, show message and return
                return;
            }  
            
            String targetFile = "";
            if (singleFileOnly) { targetFile = sourceFiles[0].getName(); }          // Only need target file name if single file, else unused param
            WepsFileChooser2 fileChooser_2 = new WepsFileChooser2();
            fileChooser_2.createBasicFileChooser(WepsFileChooser2.SelectionType.DIRECTORIES_ONLY, 
                    null, false, 
                    "\"Select a destination directory where the NRCS XML files will be created\"" ,"Select a directory",  null);
            fileChooser_2.setFileSelectionMode(WepsFileChooser2.SelectionType.FILES_AND_DIRECTORIES);
//            fileChooser.setFileFilter(
            String skeldir = "";
            returnVal = fileChooser_2.showDialog(source);                           // int determines whether choice is acceptable or not
            
            if (returnVal != WepsFileChooser2.APPROVE_OPTION) {                     // Then return, we only care if approved
                return;
            } else {                                                                // Option approved, time to write new file to diretory/filename
                try {
                    if (singleFileOnly == false) {
                        skeldir = fileChooser_2.getSelectedFile().getCanonicalPath() + TFile.separator;                                 // Get path of selection
                        TFile testdir = new TFile(skeldir);                                                                             // try to open the path
                        if ((!testdir.exists()) || testdir.isFile()) {                                                                  // must exist and fit criteria
                            JOptionPane.showMessageDialog(source, skeldir                                                               // Throw error if doesn't fit, return
                                    + "\n\nSelection is not a directory.", "WEPS Information",
                                    JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                    } else {
                        new_skel_file = fileChooser_2.getSelectedFile().getCanonicalPath() + TFile.separator;
                        TFile testFile = new TFile(new_skel_file);
                        if (testFile.isDirectory()) {
                            JOptionPane.showMessageDialog(source, new_skel_file + "\n\nSelection is not a file.", "WEPS Information",
                                    JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                    }
                } catch (HeadlessException | IOException e) {
                    System.err.println("Error: " + e);
                }
            }
            
            int total = 0;
            for (java.io.File sourceFile : sourceFiles) {
                if (singleFileOnly == false) {                                      // remove any erroneous tags
                    new_skel_file = Util.purgeExtensions(skeldir + sourceFile.getName(), ".json", ".skel", ".mgt") + ".skel";
                } else {
                    TFile shortName = new TFile(new_skel_file);

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

                    if (f.exists()) {
                        if (JOptionPane.showConfirmDialog(source, "Destination file already exists. \nDo you want to overwrite "
                                + new_skel_file_short + "?", "File Exists", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
                            doConversion = false;
                        }
                    }
                    if (doConversion) {
                        // This is where conversion actually takes place. If returned false, file fails.
                        JSONUpdater json = new JSONUpdater(this.source);
                        if (json.write_to_XML(selected_filename, new_skel_file)) { 
                            createdFiles.addElement(new_skel_file);
                            total++;
                        } else {
                            System.out.println("Failed to write new '.skel' file: " + selected_filename + "\n");
                            JOptionPane.showMessageDialog(this.source, "Failed to convert to skel file:\n" +
                                    selected_filename, "Conversion Error", JOptionPane.ERROR_MESSAGE);
                        }
                    } else {
                        System.out.println("Do conversion reset?\n");
                    }
                } else {
                    System.out.println("Do conversion=false\n");
                }
            }
            
            if (singleFileOnly == true) {
                JOptionPane.showMessageDialog(source, "WEPS NRCS XML file created:\n" + new_skel_file, "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(source, js, total + " WEPS NRCS XML Management Files Created",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            }
            TVFS.umount();
            
        } catch (Exception ex) { // FsSyncException ex
            //java.util.logging.LogManager.getLogger(TablePanel.class.getName()).log(Level.SEVERE, null, ex);
            LOGGER.error("", ex);
        }
    }// end ManToNRCS_XML
    
    /**
     * This method converts selected .json WEPP CRLMOD management file(s) from a WepsFileChooser 
     * to WEPS .man management files, using temporary .skel files created in JSONUpdater.
     * @param event
     * @param singleFileOnly 
     */
    public void Man_WEPP_To_Man_WEPS(java.awt.event.ActionEvent event, boolean singleFileOnly) {
        try {
            String selected_filename = "", selected_filename_short = "";            // This (if single file) is the name of that file
            String new_skel_file = "", new_skel_file_short = "";                    // These will be the Names of the constructed file
            Vector<String> createdFiles = new Vector<>();                           // vector to store list of created files
            String mandir = "";
            String toPath = "";
            
            WepsFileChooser2 fileChooser = new WepsFileChooser2();
            fileChooser.enableRecCheckbox(false);
            fileChooser.createBasicFileChooser(WepsFileChooser2.SelectionType.FILES_ONLY, 
                    new XMLSkelFilter("json", "(*.json)"), singleFileOnly, 
                    "Select file to be converted to NRCS Mangement format.","Select WEPP .json Managment file",  null);
            fileChooser.setFileSelectionMode(WepsFileChooser2.SelectionType.FILES_AND_DIRECTORIES);
//            fileChooser.setFileFilter(
            java.io.File[] sourceFiles = null;                                      // For file or list of files
            int returnVal = fileChooser.showDialog(source);                         // Denotes success of the file selection process
            
            if (returnVal == WepsFileChooser2.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;                                                             // Unapproved options should end this sequence
            }
            
            boolean doConversion = true;
            for (java.io.File sourceFile : sourceFiles) {
                try {
                    selected_filename = sourceFile.getCanonicalPath();
                    doConversion = isWEPPfile(selected_filename);
                    if (doConversion == false) {
                        break;
                    }
                } catch (IOException | HeadlessException e) {
                    System.err.println("Error: " + e);
                }
            }
            
            if (!doConversion) {                                                    // don't convert any files, show message and return
                return;
            }  
            
            String targetFile = "";
            if (singleFileOnly) { targetFile = sourceFiles[0].getName(); }          // Only need target file name if single file, else unused param

            WepsFileChooser2 fileChooser_2 = new WepsFileChooser2();
            fileChooser_2.createBasicFileChooser(WepsFileChooser2.SelectionType.DIRECTORIES_ONLY, 
                    null, false, 
                    "Select a directory for new WEPS Management files" ,"Select a directory",  null);
            fileChooser_2.setFileSelectionMode(WepsFileChooser2.SelectionType.FILES_AND_DIRECTORIES);
//            fileChooser.setFileFilter(
            // XMLSkelFilter filterMan = new XMLSkelFilter("skel", "NRCS XML Management Files(*.skel)");
            String skeldir = "";
            returnVal = fileChooser_2.showDialog(source);                           // int determines whether choice is acceptable or not
            
            if (returnVal != WepsFileChooser2.APPROVE_OPTION) {                     // Then return, we only care if approved
                return;
            } else {                                                                // Option approved, time to write new file to diretory/filename
                try {
                    if (singleFileOnly == false) {
                        skeldir = fileChooser_2.getSelectedFile().getCanonicalPath() + TFile.separator; 
                        mandir = fileChooser_2.getSelectedFile().getCanonicalPath() + TFile.separator;// Get path of selection
                        TFile testdir = new TFile(skeldir);                                                                             // try to open the path
                        if ((!testdir.exists()) || testdir.isFile()) {                                                                  // must exist and fit criteria
                            JOptionPane.showMessageDialog(source, skeldir                                                               // Throw error if doesn't fit, return
                                    + "\n\nSelection is not a directory.", "WEPS Information",
                                    JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                    } else {
                        new_skel_file = fileChooser_2.getSelectedFile().getCanonicalPath() + TFile.separator;
                        toPath = fileChooser_2.getSelectedFile().getCanonicalPath() + TFile.separator;
                        TFile testFile = new TFile(new_skel_file);
                        if (testFile.isDirectory()) {
                            JOptionPane.showMessageDialog(source, new_skel_file + "\n\nSelection is not a file.", "WEPS Information",
                                    JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                    }
                } catch (HeadlessException | IOException e) {
                    System.err.println("Error: " + e);
                }
            }
            
            // stack for storing temporary skel files to translate
            Stack<ConversionTask<TFile>> stack = new Stack<ConversionTask<TFile>>();
            
            int total = 0;
            for (java.io.File sourceFile : sourceFiles) {
                if (singleFileOnly == false) {                                      // remove any erroneous tags
                    new_skel_file = Util.purgeExtensions(skeldir + sourceFile.getName(), ".json", ".skel", ".mgt") + ".man";
                } else {
                    TFile shortName = new TFile(new_skel_file);

                    int end = shortName.getName().lastIndexOf(".");
                    if (end == -1) {
                        new_skel_file = new_skel_file + ".man";
                    }
                }
                try {
                    selected_filename = sourceFile.getCanonicalPath();
                    selected_filename_short = sourceFile.getName();
                } catch (IOException e) {
                    System.err.println("Error: " + e);
                }
                if (doConversion) {
                    TFile f = new TFile(new_skel_file);
                    new_skel_file_short = f.getName();
                    /* // No need for this, takes place in the next step and this is a temp file.
                    if (f.exists()) {
                        if (JOptionPane.showConfirmDialog(source, "Destination file already exists. \nDo you want to overwrite "
                                + new_skel_file_short + "?", "File Exists", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
                            doConversion = false;
                        }
                    }
                    */
                    if (doConversion) {
                        // This is where conversion to temp .ske file actually takes place. If returned false, file fails.
                        JSONUpdater json = new JSONUpdater(this.source);
                        // temp file to make sure conversion was a success
                        java.io.File file = json.write_to_MAN(selected_filename);
                        
                        // if success, create conversion task with TFile
                        if (file != null) {
                            // This is the new file that will be written to 
                            TFile to = new TFile(new_skel_file);
                            // Put conversion task on the stack
                            stack.push(new ConversionTask<TFile>(new TFile(file), new TFile(to)));
                        } else {
                            System.out.println("Failed to write new '.skel' file: " + selected_filename + "\n");
                            JOptionPane.showMessageDialog(source, "Failed to convert file due to issues with formatting."+
                                     " This conversion is for WEPP CRLMOD Management files (.mgt or .json)\nFile: " + selected_filename, "Conversion Error",  JOptionPane.INFORMATION_MESSAGE);
                        }
                    } else {
                        System.out.println("Do conversion reset?\n");
                    }
                } else {
                    System.out.println("Do conversion=false\n");
                }
            }
            
            // variables need for stack conversion
            boolean overwriteAll = false;
            boolean skipAll = false;
            
            SkelImportPanel skelimport = new SkelImportPanel(source, "Operation or crop not found",
                    true, ManageData.WriteFileMode.FROM_NRCS);

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

            if (!skelimport.setDatabases(opDBDir, cropDBDir)) {
                //something went wrong, quit
                return;
            }
            
            String manfileShort = "";
            String fromFileName = "";
            String fileNameShort = "";
            
            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++;
                    
                    if (task.getTo().getAbsolutePath().endsWith(".rot")) {
                        continue;
                        /* THIS is the only thing preventing .rot files from being created.
                        I don't know how .rot is created. I don't know where the conversionTask
                        is placed on the stack. I don't know anything. On a single file, the stack
                        enters the above 'while (!stack.empty())' with a size of one. Somewhere
                        somehow, a new conversion stack is added with the '.rot' extention and
                        the while loop runs twice. I'm not even convinced it is converting it 
                        to a '.rot' file at all. Might just be a regular .man w/ '.rot' at the end.
                        Good luck -CKM */
                    }

                    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; // NOTE: there is a 'doConversion' variable above. Note the 'c/C'. Changing the wrong one might fail hard.
                    while (toFile.exists() && !overwriteAll && !skipAll) {
                        String[] options = {"Overwrite", "Overwrite All", "Rename", "Skip", "Skip All"};
                        int result = JOptionPane.showOptionDialog(source,
                                "Destination management file already exists.\n" + toFile.getPath(),
                                "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!
                            WepsFileChooser2 wfc;
                            if (WepsFileTypes2.Management.getFileFilter().accept(toFile)) {
                                wfc = WepsFileChooser2.create(WepsFileChooser2.Action.Create,
                                        new TFile(toFile.getParentFile()), WepsFileTypes2.Management);
                            } else {
                                wfc = WepsFileChooser2.create(WepsFileChooser2.Action.Create,
                                        new TFile(toFile.getParentFile()), WepsFileTypes2.Rotation);
                            }

                            wfc.setSelectedFile(toFile);
                            wfc.setPersistSelectedFile(false);
                            if (wfc.showDialog(source) == WepsFileChooser2.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(source, 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(source, js, total
                            + " WEPS Management Files Created", JOptionPane.INFORMATION_MESSAGE);
                }
            }
            logUnknownOperationsAndCrops(skelimport, null);
            TVFS.umount();
            
        } catch (Exception ex) { // FsSyncException ex
            //java.util.logging.LogManager.getLogger(TablePanel.class.getName()).log(Level.SEVERE, null, ex);
            LOGGER.error("", ex);
        }
    } 
    
    private WepsFileChooser2 setupManToSkelFC1(boolean singleFileOnly){
        WepsFileChooser2 fileChooser = new WepsFileChooser2();
            fileChooser.enableRecCheckbox(false);
            
            fileChooser.createBasicFileChooser(WepsFileChooser2.SelectionType.FILES_ONLY, 
                    null, singleFileOnly, 
                    "Select a WEPS mgt. file(s) to convert to NRCS XML skeleton format.","Select WEPS .man Managment file",  null);
//            fileChooser.createBasicFileChooser(WepsFileChooser2.SelectionType.FILES_ONLY, 
//                    new XMLSkelFilter("man", "WEPS Management Files (.man)"), singleFileOnly, 
//                    "Select a WEPS mgt. file(s) to convert to NRCS XML skeleton format.","Select WEPS .man Managment file",  null);
            fileChooser.enableFolderButtons();
            fileChooser.enableDbButton(false);
            fileChooser.enableCfgDefLocButton(false);
//            fileChooser.setDefaultDirectory(new TFile(fileChooser.getPath().));
            if (singleFileOnly == false) {
                fileChooser.setMultiSelectionEnabled(true);
                fileChooser.setAcceptAllFileFilterUsed(false);
            } else {
                fileChooser.setMultiSelectionEnabled(false);
            }
            
            String localdir = getDefLocMan(fileChooser);//this.source.getCD().getData(ConfigData.CurrentProj);//this.source.getCD().getData(ConfigData.LocalManDB);
            // Local Management templates
//            String dir = MCREWConfig.getDirectoryName(XMLConstants.smanagement_template);
//            TFile ddir = new TFile(dir);
            fileChooser.setCurrentDirectory(localdir);
            fileChooser.setFileFilter(WepsFileTypes2.Management.getFileFilter());
            fileChooser.setDefaultDirectory(new TFile(Util.parse(localdir)));
            fileChooser.setFileSelectionMode(WepsFileChooser2.SelectionType.FILES_AND_DIRECTORIES);
            return fileChooser;
    }
    
    private String getDefLocSkel(WepsFileChooser2 wfc){
        if(wfc.loctemp_button.isEnabled()){
            return MCREWConfig.getDirectoryName(XMLConstants.smanagement_skeleton);
        }
        return this.source.getCD().getData(ConfigData.CurrentProj);
    }
    
    private String getDefLocMan(WepsFileChooser2 wfc){
        if(wfc.loctemp_button.isEnabled()&& wfc.loctemp_button.isVisible()){
            return this.source.getCD().getData(ConfigData.LocalManDB);
        }
        if(wfc.sharetemp_button.isEnabled() && wfc.sharetemp_button.isVisible()){
            return this.source.getCD().getData(ConfigData.SharedManDB);
        }
        if(wfc.systemp_button.isEnabled() && wfc.systemp_button.isVisible()){
            return this.source.getCD().getData(ConfigData.sysManTemp);
        }
        if(wfc.crlmod_button.isEnabled() && wfc.crlmod_button.isVisible()){
            return this.source.getCD().getData(ConfigData.MCREW_OPEN_COPY_OF_CRLMOD_TEMPLATE_DEFAULT);
        }
        return this.source.getCD().getData(ConfigData.CurrentProj);
    }
    
    private WepsFileChooser2 setupManToSkelFC2(boolean singleFileOnly, java.io.File[] sourceFiles){
        WepsFileChooser2 fileChooserMan = new WepsFileChooser2(WepsFileTypes2.File, "", WepsFileChooser2.Action.Select);
            if (singleFileOnly == false) {
                fileChooserMan.setFileSelectionMode(WepsFileChooser2.SelectionType.DIRECTORIES_ONLY);
                fileChooserMan.setMultiSelectionEnabled(false);
                fileChooserMan.setDialogTitle("Select a destination directory where the NRCS XML files will be created");
                fileChooserMan.setAcceptAllFileFilterUsed(false);
                fileChooserMan.setAllowDirectorySelection(true);
                fileChooserMan.setMessage("Select XML skeleton format Mgt file folder");
                fileChooserMan.setFileFolderText(WepsFileChooser2.ApproveText.FOLDER);
//                fileChooserMan.setFileText("Filter Type");
            } else {
                fileChooserMan.setFileSelectionMode(WepsFileChooser2.SelectionType.FILES_ONLY);
                fileChooserMan.setDialogTitle("Select a destination ");
                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);
                fileChooserMan.setFileFilter(WepsFileTypes2.Skeleton.getFileFilter());
                
                String targetfile = sourceFiles[0].getName();

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

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

            String dir = getDefLocSkel(fileChooserMan);//MCREWConfig.getDirectoryName(XMLConstants.smanagement_skeleton);
            
            String skeldir = "";
            fileChooserMan.setCurrentDirectory(dir);
            fileChooserMan.setDefaultDirectory(new TFile(Util.parse(dir)));
            
            
            fileChooserMan.setFileFilter(WepsFileTypes2.Skeleton.getFileFilter());
//            fileChooserMan.setFileFilter(new XMLSkelFilter("skel", "NRCS XML Management Files(*.skel)"));
            
            fileChooserMan.enableDbButton(false);
            fileChooserMan.enableCfgDefLocButton(false);
//            fileChooser.setFileFilter(
            fileChooserMan.enableFolderButtonsSave();
            fileChooserMan.enableCRMLMODTButton(false);
            fileChooserMan.enableSharedTButton(false);
            fileChooserMan.enableSysTButton(false);
            fileChooserMan.enableLocalTButton(false);
            return fileChooserMan;
    }
    
    /**
     * Converts a WEPS management file into an XML skeleton file.
     * @param event
     * @param singleFileOnly 
     */
    public void ManToSkel(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<>();
            java.io.File[] sourceFiles = null;
            
            WepsFileChooser2 fileChooser = setupManToSkelFC1(singleFileOnly);
            int returnVal = fileChooser.showDialog(source);

            if (returnVal == WepsFileChooser2.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(source, 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;
            }

            WepsFileChooser2 fileChooserMan = setupManToSkelFC2(singleFileOnly,sourceFiles); // refactored
            
            returnVal = fileChooserMan.showDialog(source);
            String skeldir = "";
            if (returnVal == WepsFileChooser2.APPROVE_OPTION) {
                try {
                    if (singleFileOnly == false) {
                        skeldir = fileChooserMan.getSelectedFile().getCanonicalPath() + TFile.separator;
                        TFile testdir = new TFile(skeldir);
                        if ((!testdir.exists()) || testdir.isFile()) {
                            JOptionPane.showMessageDialog(source, 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(source, 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", ".mgt", ".man") + ".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(source, "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(total >= 1){
                singleFileOnly = false;
            }
            if (singleFileOnly == true) {
//                JOptionPane joptemp;
//                JP_scroll.setPreferredSize(new Dimension(750, 200));
                String logFile = new TFile(MCREWConfig.getConfigDir(), "RUSLE2_Translation.log").getAbsolutePath();
                WepsMessageDialog.showScrollableMessage(source, " WEPS NRCS XML file created:", skelfile, logFile,
                    WepsMessageDialog.OK_OPTION, JOptionPane.INFORMATION_MESSAGE);
//                JOptionPane.showMessageDialog(source, "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);
                    String skelFiles = "";
                    for (int i = 0; i < total; i++) {
                        info.append(createdFiles.elementAt(i) + "\n");
                        skelFiles += createdFiles.elementAt(i) + "\n";
                    }
//                    JOptionPane.showMessageDialog(source, js, total + " WEPS NRCS XML Management Files Created",
//                            JOptionPane.INFORMATION_MESSAGE);
                    String logFile = new TFile(MCREWConfig.getConfigDir(), "RUSLE2_Translation.log").getAbsolutePath();
//                WepsMessageDialog.showScrollableMessage(source, "WEPS NRCS XML file created:\n" + skelfile, "WEPS Information", logFile);
                WepsMessageDialog.showScrollableMessage(source, total + " WEPS NRCS XML files created:", skelFiles, logFile,
                    WepsMessageDialog.OK_OPTION, JOptionPane.INFORMATION_MESSAGE);
                }
            }
            TVFS.umount();
        } catch (FsSyncException ex) {
            //java.util.logging.LogManager.getLogger(TablePanel.class.getName()).log(Level.SEVERE, null, ex);
            LOGGER.error("", ex);
        }

    }
    
    private WepsFileChooser2 setupSkelToManFC1(boolean singleFileOnly){
        WepsFileChooser2 fileChooser = new WepsFileChooser2();
        fileChooser.enableRecCheckbox(false);

        fileChooser.createBasicFileChooser(WepsFileChooser2.SelectionType.FILES_ONLY, null
                , singleFileOnly, 
                "Select NRCS skeleton file to convert to WEPS mgt file.","Select an NRCS skeleton XML management file",  null);
        fileChooser.enableFolderButtons();
//            new XMLSkelFilter("skel", "NRCS XML Skeleton Management Files(*.skel)")
        if (singleFileOnly == false) {
            fileChooser.setMultiSelectionEnabled(true);
            fileChooser.setAcceptAllFileFilterUsed(false);
        } else {
            fileChooser.setMultiSelectionEnabled(false);
        }

        String dir = MCREWConfig.getDirectoryName(XMLConstants.smanagement_skeleton);
        fileChooser.setCurrentDirectory(dir);
        fileChooser.setDefaultDirectory(new TFile(dir));
        fileChooser.setFileSelectionMode(WepsFileChooser2.SelectionType.FILES_AND_DIRECTORIES);
        fileChooser.enableDbButton(false);
        fileChooser.enableSysTButton(false);
        fileChooser.enableSharedTButton(false);
        fileChooser.enableCfgDefLocButton(false);
        fileChooser.enableCRMLMODTButton(false);
        fileChooser.enableLocalTButton(false);
        
        fileChooser.setFileFilter(WepsFileTypes2.Skeleton.getFileFilter());
//            fileChooser.setFileFilter(WepsFileTypes2.ManagementWeps.getFileFilter());
        return fileChooser;
    }
    
    
    private WepsFileChooser2 setupSkelToManFC2(java.io.File[] sourceFiles, boolean singleFileOnly){
        
        WepsFileChooser2 fileChooserMan = new WepsFileChooser2(WepsFileTypes2.File, "", WepsFileChooser2.Action.Select);
            fileChooserMan.setMultiSelectionEnabled(false);
            fileChooserMan.enableAllManButtons(this.source.getCD());
            if (singleFileOnly == false) {
                // Step 2: Have user select the WEPS management directory where the files will be written
                fileChooserMan.setFileSelectionMode(WepsFileChooser2.SelectionType.DIRECTORIES_ONLY);
                fileChooserMan.setDialogTitle("Select a destination WEPS management directory where the files will be created");
                fileChooserMan.setAcceptAllFileFilterUsed(false);
                fileChooserMan.setAllowDirectorySelection(true);
                fileChooserMan.setApproveButtonToolTipText("Select a destination WEPS management directory "
                        + "where the files will be created");
                fileChooserMan.setAcceptAllFileFilterUsed(false);
//                fileChooserMan.setText("Select a directory for files to be created");
                fileChooserMan.setText("Select location to place converted WEPS mgt files");
            } else {
                fileChooserMan.setDialogTitle("Select a destination WEPS management file that will be created");
                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);
            }
//            fileChooser.setFileSelectionMode(WepsFileChooser2.SelectionType.FILES_AND_DIRECTORIES);
//            fileChooser.setFileFilter(
            fileChooserMan.enableDbButton(false);
            fileChooserMan.enableCfgDefLocButton(false);

            // old, needs to be local management now
            //dir = MCREWConfig.getDirectoryName(XMLConstants.smanagement_template);
            String dir = this.getDefLocMan(fileChooserMan);// this.source.getCD().getData(ConfigData.LocalManDB);

            fileChooserMan.setCurrentDirectory(dir);
            fileChooserMan.setDefaultDirectory(new TFile(Util.parse(dir)));
            return fileChooserMan;         
    }

    /** 
     * 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.
     * @param event
     * @param singleFileOnly 
     */
    public void SkelToMan(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<>();
            
            WepsFileChooser2 fileChooser = setupSkelToManFC1(singleFileOnly);
            
            int returnVal = fileChooser.showDialog(source);
            java.io.File[] sourceFiles = null;

            if (returnVal == WepsFileChooser2.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;
            }
            WepsFileChooser2 fileChooserMan = setupSkelToManFC2(sourceFiles, singleFileOnly);
            String mandir = "";
            returnVal = fileChooserMan.showDialog(source);
            if (returnVal == WepsFileChooser2.APPROVE_OPTION) {
                try {
                    if (singleFileOnly == false) {
                        mandir = fileChooserMan.getSelectedFile().getCanonicalPath() + TFile.separator;
                        TFile testdir = new TFile(mandir);
                        if ((!testdir.exists()) || testdir.isFile()) {
                            JOptionPane.showMessageDialog(source, 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(source, 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(source, "Operation or crop not found",
                    true, ManageData.WriteFileMode.FROM_NRCS);

            String opDBDir = MCREWConfig.getDirectoryName(XMLConstants.soperation);
            String cropDBDir = MCREWConfig.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++;
                    
                    if (task.getTo().getAbsolutePath().endsWith(".rot")) {
                        continue;
                        /* THIS is the only thing preventing .rot files from being created.
                        I don't know how .rot is created. I don't know where the conversionTask
                        is placed on the stack. I don't know anything. On a single file, the stack
                        enters the above 'while (!stack.empty())' with a size of one. Somewhere
                        somehow, a new conversion stack is added with the '.rot' extention and
                        the while loop runs twice. I'm not even convinced it is converting it 
                        to a '.rot' file at all. Might just be a regular .man w/ '.rot' at the end.
                        Good luck -CKM */
                    }

                    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(source,
                                "Destination management file already exists.\n" + toFile.getPath(),
                                "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!
                            WepsFileChooser2 wfc;
                            if (WepsFileTypes2.Management.getFileFilter().accept(toFile)) {
                                wfc = WepsFileChooser2.create(WepsFileChooser2.Action.Create,
                                        new TFile(toFile.getParentFile()), WepsFileTypes2.Management);
                            } else {
                                wfc = WepsFileChooser2.create(WepsFileChooser2.Action.Create,
                                        new TFile(toFile.getParentFile()), WepsFileTypes2.Rotation);
                            }

                            wfc.setSelectedFile(toFile);
                            wfc.setPersistSelectedFile(false);
                            if (wfc.showDialog(source) == WepsFileChooser2.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(source, 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(source, js, total
                            + " WEPS Management Files Created", JOptionPane.INFORMATION_MESSAGE);
                }
            }
            logUnknownOperationsAndCrops(skelimport, null);
            TVFS.umount();
        } catch (FsSyncException ex) {
            //java.util.logging.LogManager.getLogger(TablePanel.class.getName()).log(Level.SEVERE, null, ex);
            LOGGER.error("", ex);
        }

    }

    /**
     * called when user requests conversion of WEPS Management files to NRCS XML format recursively.- added by Neha
     * @param evt 
     */
    public void ManToSkelRec(java.awt.event.ActionEvent evt) {
        if (!convertRec(MAN2SKELREC)) {
            return;
        }
        //set the cursor to wait cursor on the Mcrew screen
        source.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        XMLManagementUpdater updater = new XMLManagementUpdater();
        //Get all the man files in source directory
        List<String> manFiles;
        if(recursionSelected){
            manFiles = updater.onlyRecursion(sourceDirName, "man");
        }
        else{
            manFiles = updater.nonRecursion(sourceDirName, "man");
        }
//        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
        source.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    } //end of ManToSkelRec_actionPerformed
    
    
    /**
     * called when user requests conversion of WEPS Management files to NRCS XML format nonrecursively.
     * @param evt 
     */
    public void ManToSkelNonRec(java.awt.event.ActionEvent evt) {
        if (!convertRec(MAN2SKELREC)) {
            return;
        }
        //set the cursor to wait cursor on the Mcrew screen
        source.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        XMLManagementUpdater updater = new XMLManagementUpdater();
        //Get all the man files in source directory
        List<String> manFiles = updater.nonRecursion(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
        source.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    } //end of ManToSkelRec_actionPerformed
    
    
    /**
     * This method handles the WepsFileChooser2 stuff for the recursive conversion
     * of ManToSkel and SkelToMan - added by Neha // Modified to accept WEPP json to
     * skeleton files or management files - CKM
     * @param type
     * @return 
     */
    boolean convertRec(int type) {
        String sourceDir;
        String dir;
        String targetDir = "";
//        fileChooserSource - source
        WepsFileChooser2 fileChooserSource = new WepsFileChooser2(WepsFileTypes2.File, "", WepsFileChooser2.Action.Select);
        fileChooserSource.setFileSelectionMode(WepsFileChooser2.SelectionType.DIRECTORIES_ONLY);
        fileChooserSource.setMultiSelectionEnabled(false);
        fileChooserSource.setAllowDirectorySelection(true);
        fileChooserSource.setAcceptAllFileFilterUsed(false);
        fileChooserSource.enableDbButton(false);
        fileChooserSource.enableCfgDefLocButton(false);
        fileChooserSource.setMessage("Select a Directory");
        if (type == 0) {
            String localdir = getDefLocMan(fileChooserSource);//this.source.getCD().getData(ConfigData.CurrentProj);
            // Local Management templates
            
//            fileChooserSkel.setCurrentDirectory(localdir);
            fileChooserSource.setFileFolderText(WepsFileChooser2.ApproveText.FOLDER);
            
            
//            XMLSkelFilter filterMan = new XMLSkelFilter("man", "WEPS Management Files(*.man)");
            fileChooserSource.setFileFilter(WepsFileTypes2.Management.getFileFilter());
            fileChooserSource.setMessage("Select root folder with WEPS mgt files to be converted to XML skeleton");
            fileChooserSource.setDialogTitle("Select a directory where all WEPS management "
                    + "files are to be converted to Skeleton Management files");
            sourceDir = localdir;
//            sourceDir = MCREWConfig.getDirectoryName(XMLConstants.smanagement_template);
        } else if (type == 1) {
            fileChooserSource.setDialogTitle("Select a directory where all Skeleton management "
                    + "files are to be converted to Weps Management files");
            fileChooserSource.setFileFolderText(WepsFileChooser2.ApproveText.FOLDER);
            fileChooserSource.setFileFilter(WepsFileTypes2.Skeleton.getFileFilter());
            fileChooserSource.setMessage("Select folder containing NRCS skeleton files to convert to WEPS mgt files");
            sourceDir = MCREWConfig.getDirectoryName(XMLConstants.smanagement_skeleton);
            fileChooserSource.setDefaultDirectory(new TFile(Util.parse(sourceDir)));
        } else if (type == 2) {
            fileChooserSource.setDialogTitle("Select a directory where all WEPP .json management "
                    + "files are to be converted to Skeleton Management files");
            sourceDir = MCREWConfig.getDirectoryName(XMLConstants.smanagement_template);
        } else if (type == 3) {
            fileChooserSource.setDialogTitle("Select a directory where all WEPP .json management "
                    + "files are to be converted to WEPS Management files");
            sourceDir = MCREWConfig.getDirectoryName(XMLConstants.smanagement_template);
        } else {
            return false;
        }
        fileChooserSource.setFileSelectionMode(WepsFileChooser2.SelectionType.FILES_AND_DIRECTORIES);
//            fileChooser.setFileFilter(
        
        fileChooserSource.enableFolderButtons();
        fileChooserSource.enableRecCheckbox(true);
        fileChooserSource.setCurrentDirectory(sourceDir);
        if(type==0){
             sourceDir = getDefLocMan(fileChooserSource);
             fileChooserSource.setCurrentDirectory(sourceDir);
             fileChooserSource.setDefaultDirectory(new TFile(Util.parse(sourceDir)));
//             fileChooserSource.enableCRMLMODTButton(false);
//            fileChooserSkel.enableSharedTButton(false);
//            fileChooserSkel.enableSysTButton(false);
//            fileChooserSkel.enableLocalTButton(false);
            
        }
        if(type==1){
            fileChooserSource.setCurrentDirectory(sourceDir);
            fileChooserSource.setFileFilter(WepsFileTypes2.Skeleton.getFileFilter());
            fileChooserSource.enableDbButton(false);
            fileChooserSource.enableSysTButton(false);
            fileChooserSource.enableSharedTButton(false);
            fileChooserSource.enableCRMLMODTButton(false);
            fileChooserSource.enableLocalTButton(false);
        }
       
        int returnVal = fileChooserSource.showDialog(source);
        if (returnVal == WepsFileChooser2.APPROVE_OPTION) {
            try {
                sourceDir = fileChooserSource.getSelectedFile().getCanonicalPath() + TFile.separator;
                recursionSelected = fileChooserSource.isRecurive();
                TFile testdir = new TFile(sourceDir);
                if ((!testdir.exists()) || testdir.isFile()) {
                    JOptionPane.showMessageDialog(source, 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
        WepsFileChooser2 fileChooserDest = new WepsFileChooser2(WepsFileTypes2.File, "", WepsFileChooser2.Action.Select);
        fileChooserDest.setMultiSelectionEnabled(false);
        fileChooserDest.setFileSelectionMode(WepsFileChooser2.SelectionType.DIRECTORIES_ONLY);
        fileChooserDest.setAcceptAllFileFilterUsed(false);
        fileChooserDest.setAllowDirectorySelection(true);
        fileChooserDest.enableCRMLMODTButton(false);
        fileChooserDest.enableSharedTButton(false);
        fileChooserDest.enableSysTButton(false);
        fileChooserDest.enableLocalTButton(false);
        fileChooserDest.setMessage("Select a Directory");
        if (type == 0) {
            fileChooserDest.setDialogTitle("Select a destination directory where the Skeleton Management files will be created");
            fileChooserDest.setApproveButtonToolTipText("Select a destination directory where the "
                    + "Skeleton Management files will be created");
            fileChooserDest.setFileFilter(WepsFileTypes2.Skeleton.getFileFilter());
            dir = MCREWConfig.getDirectoryName(XMLConstants.smanagement_skeleton);
            fileChooserDest.setDefaultDirectory(new TFile(Util.parse(dir)));
            
        } else if (type == 1) {
            fileChooserDest.enableAllManButtons(this.source.getCD());
            String localdir = getDefLocMan(fileChooserDest);
            fileChooserDest.setDialogTitle("Select a destination WEPS management directory where the files will be created");
            fileChooserDest.setApproveButtonToolTipText("Select a destination WEPS management "
                    + "directory where the files will be created");
            fileChooserDest.setFileFilter(WepsFileTypes2.Skeleton.getFileFilter());
            dir = localdir;
//            dir = MCREWConfig.getDirectoryName(XMLConstants.smanagement_template);
            fileChooserDest.setDefaultDirectory(new TFile(Util.parse(dir)));
            fileChooserDest.setMessage("Select location to place converted WEPS mgt files");
            
        } else if (type == 2) {
            fileChooserDest.setDialogTitle("Select a destination directory where the Skeleton Management files will be created");
            fileChooserDest.setApproveButtonToolTipText("Select a destination WEPS management "
                    + "directory where the files will be created");
            dir = MCREWConfig.getDirectoryName(XMLConstants.smanagement_template);
        } else if (type == 3) {
            fileChooserDest.setDialogTitle("Select a destination directory where the WEPS Management files will be created");
            fileChooserDest.setApproveButtonToolTipText("Select a destination WEPS management "
                    + "directory where the files will be created");
            dir = MCREWConfig.getDirectoryName(XMLConstants.smanagement_template);
        } else {
            return false;
        }
        
        fileChooserDest.enableDbButton(false);
        fileChooserDest.enableCfgDefLocButton(false);
        fileChooserDest.setFileSelectionMode(WepsFileChooser2.SelectionType.DIRECTORIES_ONLY);//.FILES_AND_DIRECTORIES);
//            fileChooser.setFileFilter(
        fileChooserDest.setCurrentDirectory(dir);
        fileChooserDest.enableFolderButtonsSave();
        
        fileChooserDest.setFileFolderText(WepsFileChooser2.ApproveText.FOLDER);
        if(type == 0){
            fileChooserDest.disableAllManButtons();
        }
        returnVal = fileChooserDest.showDialog(source);
        if (returnVal == WepsFileChooser2.APPROVE_OPTION) {
            try {
                targetDir = fileChooserDest.getSelectedFile().getCanonicalPath() + TFile.separator;
                TFile testdir = new TFile(targetDir);
                if ((!testdir.exists()) || testdir.isFile()) {
                    JOptionPane.showMessageDialog(source, 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 the user requests conversion of WEPP json Management files to NRCS XML format recursively
     * @param evt 
     */
    public void WEPP_jsonToSkel(java.awt.event.ActionEvent evt) {
        // First, have FileChooser2 handle all the selection and set variables
        if (!convertRec(WEPPJSON2SKELREC)) {
            return;
        }
        
        //set the cursor to wait cursor on the Mcrew screen
        source.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        
        XMLManagementUpdater updater = new XMLManagementUpdater();
        //Get all the json files in source directory
        List<String> jsonFiles = updater.onlyRecursion(sourceDirName, "json"); // CADE todo
        
        if (jsonFiles == null) {
            jsonFiles = Collections.emptyList();
        }
        /* for debugging if needed, prints all files queued for conversion
        System.out.println("Number of WEPP JSON files to be converted: " + skelFiles.size());
        for (String filename : skelFiles) System.out.println("\tFILE: " + filename);
        */
        
        targetDirName = targetDirName != null ? targetDirName : "";
        sourceDirName = sourceDirName != null ? sourceDirName : "";
        /* sourceDirName, targetDirname should be set in convertRec() call above
        *  WEPPJSON2SKELREC used to determine which coversion occurs */
        int returnCode = convertToManOrSkelRec(sourceDirName, targetDirName, jsonFiles, 
                WEPPJSON2SKELREC, ManageData.WriteFileMode.FROM_NRCS);
        
        information_errorCatcher(returnCode); /// errors based on return value
        
        //set the cursor back to default on the Mcrew screen
        source.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    }
    
    /**
     * This method communicates with convertRec to use wepsFileChoosers to set class variables
     * then gets files selected into a list of all the .json files in a directory to be converted 
     * and passes that list, along with a static final int WEPPJSON2WEPSMAN (3) to convertToManOrSkelRec() 
     * which handles the remainder of the conversion process.
     * @param evt 
     */
    public void WEPP_jsonToWEPS_managment(java.awt.event.ActionEvent evt) {
        // First, have FileChooser2 handle all the selection and set variables
        if (!convertRec(WEPPJSON2WEPSMAN)) {
            return;
        }
        
        //set the cursor to wait cursor on the Mcrew screen
        source.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        
        XMLManagementUpdater updater = new XMLManagementUpdater();
        //Get all the skel files in source directory
        List<String> jsonFiles = updater.onlyRecursion(sourceDirName, "json"); //CADE todo
        
        if (jsonFiles == null) {
            jsonFiles = Collections.emptyList();
        }
        /* for debugging if needed, prints all files queued for conversion
        System.out.println("Number of WEPP JSON files to be converted: " + jsonFiles.size());
        for (String filename : skelFiles) System.out.println("\tFILE: " + filename);
        */
        
        
        targetDirName = targetDirName != null ? targetDirName : "";
        sourceDirName = sourceDirName != null ? sourceDirName : "";
        /* sourceDirName, targetDirname should be set in convertRec() call above
        *  WEPPJSON2SKELREC used to determine which coversion occurs */
        int returnCode = convertToManOrSkelRec(sourceDirName, targetDirName, jsonFiles, 
                WEPPJSON2WEPSMAN, ManageData.WriteFileMode.FROM_NRCS);
        
        information_errorCatcher(returnCode); /// errors based on return value
        
        //set the cursor back to default on the Mcrew screen
        source.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    }

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

        XMLManagementUpdater updater = new XMLManagementUpdater();
        //Get all the skel files in source directory
        List<String> skelFiles;// = updater.onlyRecursion(sourceDirName, "skel");
        if(recursionSelected){
            skelFiles = updater.onlyRecursion(sourceDirName, "skel");
        }
        else{
            skelFiles = updater.nonRecursion(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);
        information_errorCatcher(returnCode);

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

        //JOptionPane.showMessageDialog(null,files+" NRCS XML skeleton Files converted to WEPS management files",
        //"WEPS Information",JOptionPane.INFORMATION_MESSAGE);
    }
    
    /**
     * Lists errors that can occur in a conversion
     * @param returnCode 
     */
    private void information_errorCatcher(int returnCode) {
                switch (returnCode) {
            case 0:
                LOGGER.error("error in the path of the skeleton directory. skeleton dir MUST be in db/skel");
                break;
            case 2:
                LOGGER.debug("User pressed cancel all button");
                break;
            case 3:
                LOGGER.error("Error in selecting the target directory");
                break;
            case 4:
                LOGGER.error("Error in value of type variable");
                break;
            default:
                break;
        }
    }
    
    /**
     * This method takes the skeleton/Management files vector and converts them 
     * into management/ skeleton files - added by Neha. Modified to also translate 
     * WEPP json files to skeleton files and management files - CKM
     * @param sourceDir
     * @param targetDir
     * @param srcFiles
     * @param type
     * @param mode
     * @return 
     */
    int convertToManOrSkelRec(String sourceDir, String targetDir, List<String> srcFiles,
            int type, ManageData.WriteFileMode mode) {

        int total = 0;
        String newstr;
        String targetFile_newPath;

        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(source, "Operation or crop not found", true, mode);
        String opDBDir = MCREWConfig.getDirectoryName(XMLConstants.soperation);
        String cropDBDir = MCREWConfig.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; // used to verify that the file is of correct type
            if (type == 0) {
                skelOrmanFile = entry.endsWith(".man");
            } else if (type == 1) {
                skelOrmanFile = entry.endsWith(".skel");
            } else if (type == 2 || type == 3) {
                skelOrmanFile = (entry.endsWith(".json") || entry.endsWith(".mgt"));
            } 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", ".json", ".mgt");

                if (type == 0 || type == 2) {
                    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";
                    onlySourceFiles.add(entry); //source skel files
                    onlyTargetFiles.add(targetFile_newPath); //destination man files
                } else if (type == 3) {
                    targetFile_newPath = newstr + ".man";
                    onlySourceFiles.add(entry); //source json files must be added to be pushed on to stack
                    onlyTargetFiles.add(targetFile_newPath); //destination man 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++;
                
                if (task.getTo().getAbsolutePath().endsWith(".rot")) {
                    continue;
                    /* THIS is the only thing preventing .rot files from being created.
                    I don't know how .rot is created. I don't know where the conversionTask
                    is placed on the stack. I don't know anything. On a single file, the stack
                    enters the above 'while (!stack.empty())' with a size of one. Somewhere
                    somehow, a new conversion stack is added with the '.rot' extention and
                    the while loop runs twice. I'm not even convinced it is converting it 
                    to a '.rot' file at all. Might just be a regular .man w/ '.rot' at the end.
                    Good luck -CKM */
                }

                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(source,
                            "Destination management file already exists.\n" + toFile.getPath(),
                            "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.
                        WepsFileChooser2 wfc;
                        if (WepsFileTypes2.Management.getFileFilter().accept(toFile)) {
                            wfc = WepsFileChooser2.create(WepsFileChooser2.Action.Create,
                                    new TFile(toFile.getParentFile()), WepsFileTypes2.Management);
                        } else if (WepsFileTypes2.Rotation.getFileFilter().accept(toFile)) {
                            wfc = WepsFileChooser2.create(WepsFileChooser2.Action.Create,
                                    new TFile(toFile.getParentFile()), WepsFileTypes2.Rotation);
                        } else {
                            wfc = WepsFileChooser2.create(WepsFileChooser2.Action.Create,
                                    new TFile(toFile.getParentFile()), WepsFileTypes2.Skeleton);
                            wfc.setFileFilter(WepsFileTypes2.Skeleton.getFileFilter());
                        }

                        TFile file = new TFile(toPath);
                        file = Util.incrementFileName(file);
                        wfc.setSelectedFile(file);
                        wfc.setPersistSelectedFile(false);
                        wfc.setFileSelectionMode(WepsFileChooser2.SelectionType.FILES_AND_DIRECTORIES);
                        
                        if (wfc.showDialog(source) == WepsFileChooser2.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())) {
                            LogManager.getLogger(TablePanel.class).debug("Converting file: " + fromFile);
                            total++;
                            createdFiles.add(toFile);
                        } else {
                            LogManager.getLogger(TablePanel.class).error("Could not convert Skel file: " + fromFile);
                        }
                    } else if (type == 2) {
                        // Covert to from WEPP json to .skel
                        JSONUpdater jsonUpdater = new JSONUpdater(this.source);
                        if (jsonUpdater.write_to_XML(fromFile.getAbsolutePath(), toFile.getAbsolutePath())) {
                            LogManager.getLogger(TablePanel.class).debug("Converting file: " + fromFile);
                            total++;
                            createdFiles.add(toFile);
                        } else {
                            LogManager.getLogger(TablePanel.class).error("Could not convert Skel file: " + fromFile);
                        }
                    } else if (type == 3) {
                        /* Convert from WEPP json -> .skel tmp file -> WEPS management file */
                        JSONUpdater jsonUpdater = new JSONUpdater(this.source);
                        // Write to temp file
                        java.io.File tmpFile = jsonUpdater.write_to_MAN(fromFile.getAbsolutePath());
                        // Check that this file can be converted and isn't null
                        if (tmpFile == null) {
                            // We want to do nothing.. This means a file isn't valid format. A console message is put out elsewhere in the code. Let the loop continue
                             JOptionPane.showMessageDialog(source, "Failed to convert file due to issues with formatting."+
                                     " This conversion is for WEPP CRLMOD Management files (.json or .mgt)\nFile: " + fromFile.getName(), "Conversion Error",  JOptionPane.INFORMATION_MESSAGE);
                        } else {
                            // convert to man
                            TFile tmp_fromFile = new TFile(tmpFile);
                            if (skelimport.skel2man(tmp_fromFile.getAbsolutePath(), toFile.getAbsolutePath())) {
                                LogManager.getLogger(TablePanel.class).debug("Converting file: " + fromFile);
                                total++;
                                createdFiles.add(toFile);
                            } else {
                                LogManager.getLogger(TablePanel.class).error("Could not convert (.json or .mgt) file: " + fromFile.getAbsolutePath());
                            }
                        }
                        
                    } else {
                        logUnknownOperationsAndCrops(skelimport, null);
                        return 4;
                    }
                } //end of if(doconversion) loop
                if (skelimport.skipRemainingFlag) {
                    //User is skipping the remaining files.
                    LogManager.getLogger(TablePanel.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(MCREWConfig.getConfigDir(), "RUSLE2_Translation.log").getAbsolutePath();
        if (type == 0 || type == 2) {
            WepsMessageDialog.showScrollableMessage(source, total + " Skeleton Files Created", text, logFile,
                    WepsMessageDialog.OK_OPTION | WepsMessageDialog.SAVE_OPTION, JOptionPane.INFORMATION_MESSAGE);
        } else if (type == 1 || type == 3) {
            WepsMessageDialog.showScrollableMessage(source, 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    

    /**
     * 
     * @param dir
     * @param first 
     */
    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);
            }
        }
    }

    /**
     * 
     * @param skelimport
     * @param dir 
     */
    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(MCREWConfig.getSkelTranslationPath());
                TFile file = new TFile(translationFile.getParentFile(), MCREWConfig.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.");
            }
        }
    }
    
    
    /**
     * Check if source 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;
    }
    
    /**
     * Checks that file extension is from the current list of approved of file 
     * extensions
     * @param fileName
     * @return true if yes, pops up error message and list of files extensions if not.
     */
    private boolean isWEPPfile(String fileName) {
        // approved extensions
        final String[] file_extensions = new String[]{".json", ".mgt"};
        String error = "";
        
        for (String ext : file_extensions) {
            if (fileName.endsWith(ext))
                return true;
            // build error message
            error += ext;
            error += ", ";
        }
        
        // if we get here, it failed
        JOptionPane.showMessageDialog(source, "The file: \"" + fileName + "\" is not from on of the approved file types.\n" +
                "The approved files types are: [ " + error.substring(0, error.length() - 2) + " ].\n" +
                "This file will not be converted.", "File Conversion Error", JOptionPane.ERROR_MESSAGE);
        return false;
    }
    
    /**
     *
     * @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;
        }
    }
    
    
    // Filter for selection skeleton XML files
    static class XMLSkelFilter extends javax.swing.filechooser.FileFilter {

        String fext;
        String fdescription;

        /**
         * New file filter
         * @param exttext Do not use the "." to prefix the extension. It will not accept any files.
         * @param desc 
         */
        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 source filter
        @Override
        public String getDescription() {
            return fdescription;
        }
    }
}
