private static void UpdateManifest2014(string songDirectory, Platform platform)
        {
            // UPDATE MANIFEST (RS2014)
            if (platform.version == GameVersion.RS2014)
            {
                var xmlFiles = Directory.EnumerateFiles(songDirectory, "*.xml", SearchOption.AllDirectories);
                var jsonFiles = Directory.EnumerateFiles(songDirectory, "*.json", SearchOption.AllDirectories);
                foreach (var xml in xmlFiles)
                {
                    var xmlName = Path.GetFileNameWithoutExtension(xml);
                    if (xmlName.ToUpperInvariant().Contains("SHOWLIGHT"))
                        continue;
                    if (xmlName.ToUpperInvariant().Contains("VOCAL"))
                        continue;//TODO: Re-generate vocals manifest.

                    string json = jsonFiles.FirstOrDefault(name => Path.GetFileNameWithoutExtension(name) == xmlName);
                    if (!String.IsNullOrEmpty(json))
                    {
                        var xmlContent = Song2014.LoadFromFile(xml);
                        var manifest = new Manifest2014<Attributes2014>();
                        var attr = Manifest2014<Attributes2014>.LoadFromFile(json).Entries.First().Value.First().Value;

                        var manifestFunctions = new ManifestFunctions(platform.version);

                        attr.PhraseIterations = new List<Manifest.PhraseIteration>();
                        manifestFunctions.GeneratePhraseIterationsData(attr, xmlContent, platform.version);

                        attr.Phrases = new List<Manifest.Phrase>();
                        manifestFunctions.GeneratePhraseData(attr, xmlContent);

                        attr.Sections = new List<Manifest.Section>();
                        manifestFunctions.GenerateSectionData(attr, xmlContent);

                        attr.MaxPhraseDifficulty = manifestFunctions.GetMaxDifficulty(xmlContent);

                        var attributeDictionary = new Dictionary<string, Attributes2014> { { "Attributes", attr } };
                        manifest.Entries.Add(attr.PersistentID, attributeDictionary);
                        manifest.SaveToFile(json);
                    }
                }
            }
        }
Example #2
0
        /// <summary>
        /// Load a PSARC file into memory and
        /// convert to GuitarPro file(s)
        /// </summary>
        /// <param name="inputFilePath"></param>
        /// <param name="outputDir"></param>
        /// <param name="songListShort"></param>
        /// <param name="outputFormat"></param>
        /// <param name="allDif"></param>
        public void PsarcToGp5(string inputFilePath, string outputDir, IList <SongInfoShort> songListShort = null, string outputFormat = "gp5", bool allDif = false)
        {
            Console.WriteLine("Opening archive {0} ...", inputFilePath);
            Console.WriteLine();

            try
            {
                var browser     = new PsarcBrowser(inputFilePath);
                var songList    = browser.GetSongList();
                var toolkitInfo = browser.GetToolkitInfo();

                // collect all songs to convert
                var toConvert = new List <SongInfo>();
                // if nothing was specified, convert all songs
                if (songListShort == null || songListShort.Count == 0)
                {
                    toConvert = toConvert.Concat(songList).ToList();
                }
                else
                {
                    // convert only the user selected songs and arrangements
                    toConvert = SongInfoShortToSongInfo(songListShort, songList);
                }

                foreach (var song in toConvert)
                {
                    var score = new Score();
                    // get all default or user specified arrangements for the song
                    var arrangements = song.Arrangements;
                    Console.WriteLine("Converting song " + song.Identifier + "...");

                    foreach (var arr in arrangements)
                    {
                        var arrangement = (Song2014)browser.GetArrangement(song.Identifier, arr);
                        // get maximum difficulty for the arrangement
                        var mf     = new ManifestFunctions(GameVersion.RS2014);
                        int maxDif = mf.GetMaxDifficulty(arrangement);

                        if (allDif) // create separate file for each difficulty
                        {
                            for (int difLevel = 0; difLevel <= maxDif; difLevel++)
                            {
                                ExportArrangement(score, arrangement, difLevel, inputFilePath, toolkitInfo);
                                Console.WriteLine("Difficulty Level: {0}", difLevel);

                                var baseFileName = CleanFileName(
                                    String.Format("{0} - {1}", score.Artist, score.Title));
                                baseFileName += String.Format(" ({0})", arr);
                                baseFileName += String.Format(" (level {0:D2})", difLevel);

                                SaveScore(score, baseFileName, outputDir, outputFormat);
                                // remember to remove the track from the score again
                                score.Tracks.Clear();
                            }
                        }
                        else // combine maximum difficulty arrangements into one file
                        {
                            Console.WriteLine("Maximum Difficulty Level: {0}", maxDif);
                            ExportArrangement(score, arrangement, maxDif, inputFilePath, toolkitInfo);
                        }
                    }

                    if (!allDif) // only maximum difficulty
                    {
                        var baseFileName = CleanFileName(
                            String.Format("{0} - {1}", score.Artist, score.Title));
                        SaveScore(score, baseFileName, outputDir, outputFormat);
                    }
                }

                Console.WriteLine();
            }

            catch (IOException e)
            {
                Console.WriteLine("Error encountered:");
                Console.WriteLine(e.Message);
            }
        }
Example #3
0
        public static string DoLikeSongPack(string srcPath, string appId = "248750")
        {
            // create SongPack directory structure
            var dlcName              = Path.GetFileName(srcPath).ToLower();
            var songPackDir          = Path.Combine(Path.GetTempPath(), String.Format("{0}_songpack_p_Pc", dlcName));
            var audioWindowDir       = Path.Combine(songPackDir, "audio", "windows");
            var flatmodelsRsDir      = Path.Combine(songPackDir, "flatmodels", "rs");
            var gamexblocksNsongsDir = Path.Combine(songPackDir, "gamexblocks", "nsongs");
            var gfxassetsAlbumArtDir = Path.Combine(songPackDir, "gfxassets", "album_art");
            var manifestSongsDir     = Path.Combine(songPackDir, "manifests", String.Format("songs_dlc_{0}", dlcName));
            var songsArrDir          = Path.Combine(songPackDir, "songs", "arr");
            var binGenericDir        = Path.Combine(songPackDir, "songs", "bin", "generic");

            if (Directory.Exists(songPackDir))
            {
                DirectoryExtension.SafeDelete(songPackDir);
            }

            Directory.CreateDirectory(songPackDir);
            Directory.CreateDirectory(audioWindowDir);
            Directory.CreateDirectory(flatmodelsRsDir);
            Directory.CreateDirectory(gamexblocksNsongsDir);
            Directory.CreateDirectory(gfxassetsAlbumArtDir);
            Directory.CreateDirectory(manifestSongsDir);
            Directory.CreateDirectory(songsArrDir);
            Directory.CreateDirectory(binGenericDir);

            // populate SongPack temporary directory
            var audioWemFiles = Directory.EnumerateFiles(srcPath, "*.wem", SearchOption.AllDirectories).ToArray();

            foreach (var wem in audioWemFiles)
            {
                File.Copy(wem, Path.Combine(audioWindowDir, Path.GetFileName(wem)));
            }

            var audioBnkFiles = Directory.EnumerateFiles(srcPath, "*.bnk", SearchOption.AllDirectories).ToArray();

            foreach (var bnk in audioBnkFiles)
            {
                File.Copy(bnk, Path.Combine(audioWindowDir, Path.GetFileName(bnk)));
            }

            var xblockFiles = Directory.EnumerateFiles(srcPath, "*.xblock", SearchOption.AllDirectories).ToArray();

            foreach (var xblock in xblockFiles)
            {
                File.Copy(xblock, Path.Combine(gamexblocksNsongsDir, Path.GetFileName(xblock)));
            }

            var albumArtFiles = Directory.EnumerateFiles(srcPath, "*.dds", SearchOption.AllDirectories).ToArray();

            foreach (var albumArt in albumArtFiles)
            {
                File.Copy(albumArt, Path.Combine(gfxassetsAlbumArtDir, Path.GetFileName(albumArt)));
            }

            var jsonFiles = Directory.EnumerateFiles(srcPath, "*.json", SearchOption.AllDirectories).ToArray();

            foreach (var json in jsonFiles)
            {
                File.Copy(json, Path.Combine(manifestSongsDir, Path.GetFileName(json)));
            }

            var hsanFiles = Directory.EnumerateFiles(srcPath, "*.hsan", SearchOption.AllDirectories).ToArray();

            foreach (var hsan in hsanFiles)
            {
                File.Copy(hsan, Path.Combine(manifestSongsDir, Path.GetFileName(hsan)));
            }

            var sngFiles = Directory.EnumerateFiles(srcPath, "*.sng", SearchOption.AllDirectories).ToArray();

            foreach (var sng in sngFiles)
            {
                File.Copy(sng, Path.Combine(binGenericDir, Path.GetFileName(sng)));
            }

            // declare variables one time for use in DDC generation
            DDCSettings.Instance.LoadConfigXml();
            var phraseLen = DDCSettings.Instance.PhraseLen;
            // removeSus may be depricated in latest DDC but left here for comptiblity
            var removeSus = DDCSettings.Instance.RemoveSus;
            var rampPath  = DDCSettings.Instance.RampPath;
            var cfgPath   = DDCSettings.Instance.CfgPath;

            // generate SongPack comment
            var spComment = "(Remastered by SongPack Maker)";
            var addDD     = false;

            if (ConfigRepository.Instance().GetBoolean("ddc_autogen"))
            {
                addDD      = true;
                spComment += " " + "(DDC by SongPack Maker)";
            }

            var xmlFiles = Directory.EnumerateFiles(srcPath, "*.xml", SearchOption.AllDirectories).ToArray();

            foreach (var xml in xmlFiles)
            {
                // completely skip dlc.xml template files
                if (xml.EndsWith("_RS2014.dlc.xml"))
                {
                    continue;
                }

                var xmlSongPack = Path.Combine(songsArrDir, Path.GetFileName(xml));
                File.Copy(xml, xmlSongPack);

                // skip vocal and showlight xml files
                if (xml.EndsWith("_vocals.xml") || xml.EndsWith("_showlights.xml"))
                {
                    continue;
                }

                // add DDC to xml arrangement
                if (addDD)
                {
                    // check if arrangment has pre existing DD and do not overwrite
                    var songXml = Song2014.LoadFromFile(xml);
                    var mf      = new ManifestFunctions(GameVersion.RS2014);
                    if (mf.GetMaxDifficulty(songXml) == 0)
                    {
                        var consoleOutput = String.Empty;
                        // apply DD to xml arrangments... 0 = Ends normally with no error
                        var result = DDCreator.ApplyDD(xmlSongPack, phraseLen, removeSus, rampPath, cfgPath, out consoleOutput, true);
                        if (result == 1)
                        {
                            Debug.WriteLine(String.Format("Arrangement file '{0}' => {1}", Path.GetFileNameWithoutExtension(xml), "DDC ended with system error " + consoleOutput));
                        }
                        else if (result == 2)
                        {
                            Debug.WriteLine(String.Format("Arrangement file '{0}' => {1}", Path.GetFileNameWithoutExtension(xml), "DDC ended with application error " + consoleOutput));
                        }
                    }
                }
            }

            // generate new Aggregate Graph
            var aggGraphPack = new AggregateGraph2014();

            aggGraphPack.JsonDB        = new List <GraphItem>();
            aggGraphPack.HsonDB        = new List <GraphItem>(); // used for consoles ONLY
            aggGraphPack.HsanDB        = new GraphItem();
            aggGraphPack.MusicgameSong = new List <GraphItemLLID>();
            aggGraphPack.SongXml       = new List <GraphItemLLID>();
            aggGraphPack.ShowlightXml  = new List <GraphItemLLID>();
            aggGraphPack.ImageArt      = new List <GraphItemLLID>();
            aggGraphPack.Soundbank     = new List <GraphItemLLID>();
            aggGraphPack.GameXblock    = new List <GraphItem>();

            // fix aggregate graph entries, reusing existing Persistent ID
            var currentPlatform     = new Platform(GamePlatform.Pc, GameVersion.RS2014);
            var aggregateGraphFiles = Directory.EnumerateFiles(srcPath, "*.nt", SearchOption.AllDirectories).ToArray();

            foreach (var aggGraph in aggregateGraphFiles)
            {
                var agg = LoadFromFile(aggGraph);

                foreach (var json in agg.JsonDB)
                {
                    json.Canonical        = String.Format(CANONICAL_MANIFEST_PC, dlcName);
                    json.RelPathDirectory = json.Canonical;
                    json.Tag = new List <string>();
                    json.Tag.Add(TagValue.Database.GetDescription());
                    json.Tag.Add(TagValue.JsonDB.GetDescription());
                    json.UUID        = IdGenerator.Guid();
                    json.RelPathFile = String.Format("{0}.json", json.Name);
                }

                aggGraphPack.JsonDB.AddRange(agg.JsonDB);
                aggGraphPack.MusicgameSong.AddRange(agg.MusicgameSong);
                aggGraphPack.SongXml.AddRange(agg.SongXml);
                aggGraphPack.ShowlightXml.AddRange(agg.ShowlightXml);
                aggGraphPack.ImageArt.AddRange(agg.ImageArt);
                aggGraphPack.Soundbank.AddRange(agg.Soundbank);

                aggGraphPack.GameXblock.AddRange(agg.GameXblock);
            }

            // create a single hsanDB entry
            aggGraphPack.HsanDB.Name             = String.Format("songs_dlc_{0}", dlcName);
            aggGraphPack.HsanDB.Canonical        = String.Format(CANONICAL_MANIFEST_PC, dlcName);
            aggGraphPack.HsanDB.RelPathDirectory = aggGraphPack.HsanDB.Canonical;
            aggGraphPack.HsanDB.Tag = new List <string>();
            aggGraphPack.HsanDB.Tag.Add(TagValue.Database.GetDescription());
            aggGraphPack.HsanDB.Tag.Add(TagValue.HsanDB.GetDescription());
            aggGraphPack.HsanDB.UUID        = IdGenerator.Guid();
            aggGraphPack.HsanDB.RelPathFile = String.Format("{0}.hsan", aggGraphPack.HsanDB.Name);

            var aggregateGraphFileName = Path.Combine(songPackDir, String.Format("{0}_aggregategraph.nt", dlcName));

            using (var fs = new FileStream(aggregateGraphFileName, FileMode.Create))
                using (var ms = new MemoryStream())
                {
                    aggGraphPack.Serialize(ms);
                    ms.Flush();
                    ms.Seek(0, SeekOrigin.Begin);
                    ms.CopyTo(fs);
                }

            MergeHsanFiles(songPackDir, dlcName, manifestSongsDir);

            var appIdFile = Path.Combine(songPackDir, "appid.appid");

            File.WriteAllText(appIdFile, appId);

            var toolkitVersionFile = Path.Combine(songPackDir, "toolkit.version");

            using (var fs = new FileStream(toolkitVersionFile, FileMode.Create))
                using (var ms = new MemoryStream())
                {
                    DLCPackageCreator.GenerateToolkitVersion(ms, packageVersion: "SongPack Maker v1.2", packageComment: spComment);
                    ms.Flush();
                    ms.Seek(0, SeekOrigin.Begin);
                    ms.CopyTo(fs);
                }

            var rootFlatFile = Path.Combine(flatmodelsRsDir, "rsenumerable_root.flat");

            using (var fs = new FileStream(rootFlatFile, FileMode.Create))
                using (var ms = new MemoryStream(Resources.rsenumerable_root))
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    ms.CopyTo(fs);
                }

            var songFlatFile = Path.Combine(flatmodelsRsDir, "rsenumerable_song.flat");

            using (var fs = new FileStream(songFlatFile, FileMode.Create))
                using (var ms = new MemoryStream(Resources.rsenumerable_song))
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    ms.CopyTo(fs);
                }

            return(songPackDir);
        }
        public Attributes2014(string arrangementFileName, Arrangement arrangement, DLCPackageData info, Platform platform)
            : base(arrangementFileName, arrangement, info, platform)
        {
            #region VARIABLES

            var dlcName = info.Name.ToLower();

            var xblockUrn    = String.Format(URN_TEMPLATE_SHORT, TagValue.EmergentWorld.GetDescription(), dlcName);
            var showlightUrn = String.Format(URN_TEMPLATE, TagValue.Application.GetDescription(), TagValue.XML.GetDescription(), String.Format("{0}_showlights", dlcName));
            var songXmlUrn   = String.Format(URN_TEMPLATE, TagValue.Application.GetDescription(), TagValue.XML.GetDescription(), String.Format(AggregateGraph2014.AggregateGraph2014.NAME_ARRANGEMENT, dlcName, arrangementFileName));
            var songSngUrn   = String.Format(URN_TEMPLATE, TagValue.Application.GetDescription(), TagValue.MusicgameSong.GetDescription(), String.Format(AggregateGraph2014.AggregateGraph2014.NAME_ARRANGEMENT, dlcName, arrangementFileName));

            var manifestFunctions = new ManifestFunctions(platform.version);

            #endregion

            #region FILL ATTRIBUTES

            ArrangementSort = arrangement.ArrangementSort;
            BlockAsset      = xblockUrn;
            manifestFunctions.GenerateDynamicVisualDensity(this, song2014, arrangement, GameVersion.RS2014);//2.0 constant for vocs in RS2
            FullName           = String.Format(AggregateGraph2014.AggregateGraph2014.NAME_ARRANGEMENT, info.Name, arrangement.ArrangementName);
            MasterID_PS3       = (IsVocal) ? -1 : arrangement.MasterId;
            MasterID_XBox360   = (IsVocal) ? -1 : arrangement.MasterId;
            PreviewBankPath    = String.Format("song_{0}_preview.bnk", info.Name.ToLower());
            RelativeDifficulty = 0; //Always 0 in RS2014
            ShowlightsXML      = showlightUrn;
            SongAsset          = songSngUrn;
            SongBank           = String.Format("song_{0}.bnk", info.Name.ToLower());
            SongEvent          = String.Format("Play_{0}", info.Name);
            SongXml            = songXmlUrn;
            SongVolume         = info.Volume;
            PreviewVolume      = info.PreviewVolume ?? SongVolume;

            // Only for Vocal
            if (IsVocal)
            {
                InputEvent = "Play_Tone_Standard_Mic";
                return;
            }

            // Only for instruments
            ArrangementProperties            = song2014.ArrangementProperties;
            ArrangementProperties.BassPick   = (int)arrangement.PluckedType;
            ArrangementProperties.PathLead   = Convert.ToInt32(arrangement.RouteMask == DLCPackage.RouteMask.Lead);
            ArrangementProperties.PathRhythm = Convert.ToInt32(arrangement.RouteMask == DLCPackage.RouteMask.Rhythm);
            ArrangementProperties.PathBass   = Convert.ToInt32(arrangement.RouteMask == DLCPackage.RouteMask.Bass);
            ArrangementProperties.RouteMask  = (int)arrangement.RouteMask;
            // Automatically set as two finger style if pick is not used
            ArrangementProperties.TwoFingerPicking = ArrangementProperties.PathBass == 1 && ArrangementProperties.BassPick == 0 ? 1 : 0;

            // TODO: monitor this change
            // EOF now properly sets the bonus/represent elements
            ArrangementProperties.Represent = Convert.ToInt32(arrangement.Represent);
            ArrangementProperties.BonusArr  = Convert.ToInt32(arrangement.BonusArr);

            // Metronome
            ArrangementProperties.Metronome = (int)arrangement.Metronome;

            if (arrangement.ArrangementName == Sng.ArrangementName.Combo)
            { //Exclusive condition
                if (arrangement.RouteMask == DLCPackage.RouteMask.Lead)
                {
                    ArrangementType = (int)Sng.ArrangementName.Lead;
                }
                else if (arrangement.RouteMask == DLCPackage.RouteMask.Rhythm)
                {
                    ArrangementType = (int)Sng.ArrangementName.Rhythm;
                }
                else
                {
                    ArrangementType = (int)arrangement.ArrangementName;
                }
            }
            else
            {
                ArrangementType = (int)arrangement.ArrangementName;
            }

            LastConversionDateTime = song2014.LastConversionDateTime;
            MaxPhraseDifficulty    = manifestFunctions.GetMaxDifficulty(song2014);

            TargetScore      = 100000;
            PhraseIterations = new List <PhraseIteration>();
            manifestFunctions.GeneratePhraseIterationsData(this, song2014, platform.version);
            //Score_MaxNotes -- Generated on function above
            //Score_PNV      -- Generated on function above

            Phrases = new List <Phrase>();
            manifestFunctions.GeneratePhraseData(this, song2014);

            Sections = new List <Section>();
            manifestFunctions.GenerateSectionData(this, song2014);

            SongAverageTempo = song2014.AverageTempo;
            SongOffset       = -song2014.StartBeat; //arrangement.Sng2014.Metadata.StartTime * -1;

            //SongPartition  -- Generated in DLCPackageCreator after this constructor

            ChordTemplates = new List <ChordTemplate>();
            manifestFunctions.GenerateChordTemplateData(this, song2014);

            //Chords TODO: create me
            try
            {
                // Commented out to check if this is cause of repeating chord display in game
                manifestFunctions.GenerateChords(this, song2014);
            }
            catch (Exception ex)
            {
                Console.WriteLine("GenerateChords: " + ex.Message);
            }

            //Techniques TODO: improve me
            // not source of 100% bug
            try
            {
                manifestFunctions.GenerateTechniques(this, song2014);
            }
            catch (Exception ex)
            {
                Console.WriteLine("GenerateTechniques: " + ex.Message);
            }

            //Fix for Dead tones
            var it = info.TonesRS2014;
            Tones            = new List <Tone2014>();
            Tone_A           = GetToneName(arrangement.ToneA, it);
            Tone_B           = GetToneName(arrangement.ToneB, it);
            Tone_Base        = GetToneName(arrangement.ToneBase, it);
            Tone_C           = GetToneName(arrangement.ToneC, it);
            Tone_D           = GetToneName(arrangement.ToneD, it);
            Tone_Multiplayer = GetToneName(arrangement.ToneMultiplayer, it);

            #endregion
        }
Example #5
0
        private int ApplyPackageDD(string file, string remSUS, string rampPath, string cfgPath, out string consoleOutputPkg, bool keepLog = false)
        {
            int  singleResult  = -1;
            bool exitedByError = false;

            consoleOutputPkg = String.Empty;
            var tmpDir      = Path.GetTempPath();
            var platform    = file.GetPlatform();
            var unpackedDir = Packer.Unpack(file, tmpDir, false, true, false);

            var xmlFiles = Directory.GetFiles(unpackedDir, "*.xml", SearchOption.AllDirectories);

            foreach (var xml in xmlFiles)
            {
                if (Path.GetFileNameWithoutExtension(xml).ToUpperInvariant().Contains("VOCAL"))
                {
                    continue;
                }

                if (Path.GetFileNameWithoutExtension(xml).ToUpperInvariant().Contains("SHOWLIGHT"))
                {
                    continue;
                }

                singleResult = ApplyDD(xml, remSUS, rampPath, cfgPath, out consoleOutputPkg, true, keepLog);

                // UPDATE MANIFEST (RS2014) for update
                if (platform.version == RocksmithToolkitLib.GameVersion.RS2014)
                {
                    var json = Directory.GetFiles(unpackedDir, String.Format("*{0}.json", Path.GetFileNameWithoutExtension(xml)), SearchOption.AllDirectories);
                    if (json.Length > 0)
                    {
                        Attributes2014 attr = Manifest2014 <Attributes2014> .LoadFromFile(json[0]).Entries.ToArray()[0].Value.ToArray()[0].Value;

                        Song2014 xmlContent = Song2014.LoadFromFile(xml);

                        var manifestFunctions = new ManifestFunctions(platform.version);

                        attr.PhraseIterations = new List <PhraseIteration>();
                        manifestFunctions.GeneratePhraseIterationsData(attr, xmlContent, platform.version);

                        attr.Phrases = new List <Phrase>();
                        manifestFunctions.GeneratePhraseData(attr, xmlContent);

                        attr.Sections = new List <Section>();
                        manifestFunctions.GenerateSectionData(attr, xmlContent);

                        attr.MaxPhraseDifficulty = manifestFunctions.GetMaxDifficulty(xmlContent);

                        var manifest            = new Manifest2014 <Attributes2014>();
                        var attributeDictionary = new Dictionary <string, Attributes2014> {
                            { "Attributes", attr }
                        };
                        manifest.Entries.Add(attr.PersistentID, attributeDictionary);
                        manifest.SaveToFile(json[0]);
                    }
                }

                if (singleResult == 1)
                {
                    exitedByError = true;
                    break;
                }
                else if (singleResult == 2)
                {
                    consoleOutputPkg = String.Format("Arrangement file '{0}' => {1}", Path.GetFileNameWithoutExtension(xml), consoleOutputPkg);
                }
            }

            if (!exitedByError)
            {
                var logFiles = Directory.GetFiles(unpackedDir, "*.log", SearchOption.AllDirectories);
                var newName  = Path.Combine(Path.GetDirectoryName(file), String.Format("{0}_{1}{2}",
                                                                                       Path.GetFileNameWithoutExtension(file).StripPlatformEndName().GetValidName(false).Replace("_DD", "").Replace("_NDD", ""),
                                                                                       isNDD ? "NDD" :  "DD", platform.GetPathName()[2]));
                if (keepLog)
                {
                    string clogDir = Path.Combine(Path.GetDirectoryName(newName), "DDC_Log");
                    string plogDir = Path.Combine(clogDir, Path.GetFileNameWithoutExtension(newName).StripPlatformEndName().Replace("_DD", "").Replace("_NDD", ""));

                    if (!Directory.Exists(clogDir))
                    {
                        Directory.CreateDirectory(clogDir);
                    }
                    DirectoryExtension.SafeDelete(plogDir); Directory.CreateDirectory(plogDir);
                    foreach (var logFile in logFiles)
                    {
                        File.Move(logFile, Path.Combine(plogDir, Path.GetFileName(logFile)));
                    }
                }
                else
                {
                    foreach (var logFile in logFiles)
                    {
                        if (File.Exists(logFile))
                        {
                            File.Delete(logFile);
                        }
                    }
                }
                Packer.Pack(unpackedDir, newName, true, platform);
                DirectoryExtension.SafeDelete(unpackedDir);
            }
            return(singleResult);
        }
        public Attributes2014(string arrangementFileName, Arrangement arrangement, DLCPackageData info, Platform platform)
            : base(arrangementFileName, arrangement, info, platform)
        {
            #region VARIABLES

            var dlcName = info.Name.ToLower();

            var xblockUrn = String.Format(URN_TEMPLATE_SHORT, TagValue.EmergentWorld.GetDescription(), dlcName);
            var showlightUrn = String.Format(URN_TEMPLATE, TagValue.Application.GetDescription(), TagValue.XML.GetDescription(), String.Format("{0}_showlights", dlcName));
            var songXmlUrn = String.Format(URN_TEMPLATE, TagValue.Application.GetDescription(), TagValue.XML.GetDescription(), String.Format(AggregateGraph2014.AggregateGraph2014.NAME_ARRANGEMENT, dlcName, arrangementFileName));
            var songSngUrn = String.Format(URN_TEMPLATE, TagValue.Application.GetDescription(), TagValue.MusicgameSong.GetDescription(), String.Format(AggregateGraph2014.AggregateGraph2014.NAME_ARRANGEMENT, dlcName, arrangementFileName));

            var manifestFunctions = new ManifestFunctions(platform.version);

            #endregion

            #region FILL ATTRIBUTES

            ArrangementSort = arrangement.ArrangementSort;
            BlockAsset = xblockUrn;
            manifestFunctions.GenerateDynamicVisualDensity(this, SongContent, arrangement, GameVersion.RS2014);//2.0 constant for vocs in RS2
            FullName = String.Format(AggregateGraph2014.AggregateGraph2014.NAME_ARRANGEMENT, info.Name, arrangement.Name);
            MasterID_PS3 = (IsVocal) ? -1 : arrangement.MasterId;
            MasterID_XBox360 = (IsVocal) ? -1 : arrangement.MasterId;
            PreviewBankPath = String.Format("song_{0}_preview.bnk", info.Name.ToLower());
            RelativeDifficulty = 0; //Always 0 in RS2014
            ShowlightsXML = showlightUrn;
            SongAsset = songSngUrn;
            SongBank = String.Format("song_{0}.bnk", info.Name.ToLower());
            SongEvent = String.Format("Play_{0}", info.Name);
            SongXml = songXmlUrn;
            SongVolume = info.Volume;
            PreviewVolume = info.PreviewVolume ?? SongVolume;

            // Only for Vocal
            if (IsVocal)
                InputEvent = "Play_Tone_Standard_Mic";

            // Only for instruments
            if (!IsVocal)
            {
                ArrangementProperties = SongContent.ArrangementProperties;
                ArrangementProperties.BassPick = (int)arrangement.PluckedType;
                ArrangementProperties.PathLead = Convert.ToInt32(arrangement.RouteMask == DLCPackage.RouteMask.Lead);
                ArrangementProperties.PathRhythm = Convert.ToInt32(arrangement.RouteMask == DLCPackage.RouteMask.Rhythm);
                ArrangementProperties.PathBass = Convert.ToInt32(arrangement.RouteMask == DLCPackage.RouteMask.Bass);
                ArrangementProperties.RouteMask = (int)arrangement.RouteMask;

                // BONUS ARRANGEMENT
                ArrangementProperties.BonusArr = Convert.ToInt32(arrangement.BonusArr);

                // Metronome
                ArrangementProperties.Metronome = (int)arrangement.Metronome;

                if (arrangement.Name == Sng.ArrangementName.Combo)
                { //Exclusive condition
                    if (arrangement.RouteMask == DLCPackage.RouteMask.Lead)
                        ArrangementType = (int)Sng.ArrangementName.Lead;
                    else if (arrangement.RouteMask == DLCPackage.RouteMask.Rhythm)
                        ArrangementType = (int)Sng.ArrangementName.Rhythm;
                    else
                        ArrangementType = (int)arrangement.Name;
                }
                else
                    ArrangementType = (int)arrangement.Name;

                //Chords        -- //TODO: MISSING GENERATE

                ChordTemplates = new List<ChordTemplate>();
                manifestFunctions.GenerateChordTemplateData(this, SongContent);

                LastConversionDateTime = SongContent.LastConversionDateTime;
                MaxPhraseDifficulty = manifestFunctions.GetMaxDifficulty(SongContent);

                TargetScore = 100000;
                PhraseIterations = new List<PhraseIteration>();
                manifestFunctions.GeneratePhraseIterationsData(this, SongContent, platform.version);
                //Score_MaxNotes -- Generated on function above
                //Score_PNV      -- Generated on function above

                Phrases = new List<Phrase>();
                manifestFunctions.GeneratePhraseData(this, SongContent);

                Sections = new List<Section>();
                manifestFunctions.GenerateSectionData(this, SongContent);

                SongAverageTempo = SongContent.AverageTempo;
                SongOffset = arrangement.Sng2014.Metadata.StartTime * -1;

                //SongPartition  -- Generated in DLCPackageCreator after this constructor

                //Techniques TODO: improve me
                try
                {
                    manifestFunctions.GenerateTechniques(this, SongContent);
                }
                catch { }

                //Fix for Dead tones
                var it = info.TonesRS2014;
                Tones = new List<Tone2014>();
                Tone_A = GetToneName(arrangement.ToneA, it);
                Tone_B = GetToneName(arrangement.ToneB, it);
                Tone_Base = GetToneName(arrangement.ToneBase, it);
                Tone_C = GetToneName(arrangement.ToneC, it);
                Tone_D = GetToneName(arrangement.ToneD, it);
                Tone_Multiplayer = GetToneName(arrangement.ToneMultiplayer, it);
            }

            #endregion
        }
        public Attributes2014(string arrangementFileName, Arrangement arrangement, DLCPackageData info, Platform platform)
            : base(arrangementFileName, arrangement, info, platform)
        {
            #region VARIABLES

            var dlcName = info.Name.ToLower();

            var xblockUrn    = String.Format(URN_TEMPLATE_SHORT, TagValue.EmergentWorld.GetDescription(), dlcName);
            var showlightUrn = String.Format(URN_TEMPLATE, TagValue.Application.GetDescription(), TagValue.XML.GetDescription(), String.Format("{0}_showlights", dlcName));
            var songXmlUrn   = String.Format(URN_TEMPLATE, TagValue.Application.GetDescription(), TagValue.XML.GetDescription(), String.Format(AggregateGraph2014.AggregateGraph2014.NAME_ARRANGEMENT, dlcName, arrangementFileName));
            var songSngUrn   = String.Format(URN_TEMPLATE, TagValue.Application.GetDescription(), TagValue.MusicgameSong.GetDescription(), String.Format(AggregateGraph2014.AggregateGraph2014.NAME_ARRANGEMENT, dlcName, arrangementFileName));

            var manifestFunctions = new ManifestFunctions(platform.version);

            #endregion

            #region FILL ATTRIBUTES

            ArrangementSort = arrangement.ArrangementSort;
            BlockAsset      = xblockUrn;
            manifestFunctions.GenerateDynamicVisualDensity(this, SongContent, arrangement, GameVersion.RS2014);//2.0 constant for vocs in RS2
            FullName           = String.Format(AggregateGraph2014.AggregateGraph2014.NAME_ARRANGEMENT, info.Name, arrangement.Name);
            MasterID_PS3       = (IsVocal) ? -1 : arrangement.MasterId;
            MasterID_XBox360   = (IsVocal) ? -1 : arrangement.MasterId;
            PreviewBankPath    = String.Format("song_{0}_preview.bnk", info.Name.ToLower());
            RelativeDifficulty = 0; //Always 0 in RS2014
            ShowlightsXML      = showlightUrn;
            SongAsset          = songSngUrn;
            SongBank           = String.Format("song_{0}.bnk", info.Name.ToLower());
            SongEvent          = String.Format("Play_{0}", info.Name);
            SongXml            = songXmlUrn;
            SongVolume         = info.Volume;
            PreviewVolume      = info.PreviewVolume ?? SongVolume;

            // Only for Vocal
            if (IsVocal)
            {
                InputEvent = "Play_Tone_Standard_Mic";
            }

            // Only for instruments
            if (!IsVocal)
            {
                ArrangementProperties            = SongContent.ArrangementProperties;
                ArrangementProperties.BassPick   = (int)arrangement.PluckedType;
                ArrangementProperties.PathLead   = Convert.ToInt32(arrangement.RouteMask == DLCPackage.RouteMask.Lead);
                ArrangementProperties.PathRhythm = Convert.ToInt32(arrangement.RouteMask == DLCPackage.RouteMask.Rhythm);
                ArrangementProperties.PathBass   = Convert.ToInt32(arrangement.RouteMask == DLCPackage.RouteMask.Bass);
                ArrangementProperties.RouteMask  = (int)arrangement.RouteMask;

                // BONUS ARRANGEMENT
                ArrangementProperties.BonusArr = Convert.ToInt32(arrangement.BonusArr);

                // Metronome
                ArrangementProperties.Metronome = (int)arrangement.Metronome;

                if (arrangement.Name == Sng.ArrangementName.Combo)
                { //Exclusive condition
                    if (arrangement.RouteMask == DLCPackage.RouteMask.Lead)
                    {
                        ArrangementType = (int)Sng.ArrangementName.Lead;
                    }
                    else if (arrangement.RouteMask == DLCPackage.RouteMask.Rhythm)
                    {
                        ArrangementType = (int)Sng.ArrangementName.Rhythm;
                    }
                    else
                    {
                        ArrangementType = (int)arrangement.Name;
                    }
                }
                else
                {
                    ArrangementType = (int)arrangement.Name;
                }

                //Chords        -- //TODO: MISSING GENERATE

                ChordTemplates = new List <ChordTemplate>();
                manifestFunctions.GenerateChordTemplateData(this, SongContent);

                LastConversionDateTime = SongContent.LastConversionDateTime;
                MaxPhraseDifficulty    = manifestFunctions.GetMaxDifficulty(SongContent);

                TargetScore      = 100000;
                PhraseIterations = new List <PhraseIteration>();
                manifestFunctions.GeneratePhraseIterationsData(this, SongContent, platform.version);
                //Score_MaxNotes -- Generated on function above
                //Score_PNV      -- Generated on function above

                Phrases = new List <Phrase>();
                manifestFunctions.GeneratePhraseData(this, SongContent);

                Sections = new List <Section>();
                manifestFunctions.GenerateSectionData(this, SongContent);

                SongAverageTempo = SongContent.AverageTempo;
                SongOffset       = arrangement.Sng2014.Metadata.StartTime * -1;

                //SongPartition  -- Generated in DLCPackageCreator after this constructor

                //Techniques TODO: improove me
                try
                {
                    manifestFunctions.GenerateTechniques(this, SongContent);
                }
                catch { }

                //Fix for Dead tones
                var it = info.TonesRS2014;
                Tones            = new List <Tone2014>();
                Tone_A           = GetToneName(arrangement.ToneA, it);
                Tone_B           = GetToneName(arrangement.ToneB, it);
                Tone_Base        = GetToneName(arrangement.ToneBase, it);
                Tone_C           = GetToneName(arrangement.ToneC, it);
                Tone_D           = GetToneName(arrangement.ToneD, it);
                Tone_Multiplayer = GetToneName(arrangement.ToneMultiplayer, it);
            }

            #endregion
        }
        /// <summary>
        /// Load a PSARC file into memory and
        /// convert to GuitarPro file(s)
        /// </summary>
        /// <param name="inputFilePath"></param>
        /// <param name="outputDir"></param>
        /// <param name="songListShort"></param>
        /// <param name="outputFormat"></param>
        /// <param name="allDif"></param>
        public void PsarcToGp5(string inputFilePath, string outputDir, IList<SongInfoShort> songListShort = null, string outputFormat = "gp5", bool allDif = false)
        {
            Console.WriteLine("Opening archive {0} ...", inputFilePath);
            Console.WriteLine();

            try
            {
                var browser = new PsarcBrowser(inputFilePath);
                var songList = browser.GetSongList();
                var toolkitInfo = browser.GetToolkitInfo();

                // collect all songs to convert
                var toConvert = new List<SongInfo>();
                // if nothing was specified, convert all songs
                if (songListShort == null || songListShort.Count == 0)
                    toConvert = toConvert.Concat(songList).ToList();
                else
                    // convert only the user selected songs and arrangements
                    toConvert = SongInfoShortToSongInfo(songListShort, songList);

                foreach (var song in toConvert)
                {
                    var score = new Score();
                    // get all default or user specified arrangements for the song 
                    var arrangements = song.Arrangements;
                    Console.WriteLine("Converting song " + song.Identifier + "...");

                    foreach (var arr in arrangements)
                    {
                        var arrangement = (Song2014)browser.GetArrangement(song.Identifier, arr);
                        // get maximum difficulty for the arrangement
                        var mf = new ManifestFunctions(GameVersion.RS2014);
                        int maxDif = mf.GetMaxDifficulty(arrangement);

                        if (allDif) // create seperate file for each difficulty
                        {
                            for (int difLevel = 0; difLevel <= maxDif; difLevel++)
                            {
                                ExportArrangement(score, arrangement, difLevel, inputFilePath, toolkitInfo);
                                Console.WriteLine("Difficulty Level: {0}", difLevel);

                                var baseFileName = CleanFileName(
                                    String.Format("{0} - {1}", score.Artist, score.Title));
                                baseFileName += String.Format(" ({0})", arr);
                                baseFileName += String.Format(" (level {0:D2})", difLevel);

                                SaveScore(score, baseFileName, outputDir, outputFormat);
                                // remember to remove the track from the score again
                                score.Tracks.Clear();
                            }
                        }
                        else // combine maximum difficulty arrangements into one file
                        {
                            Console.WriteLine("Maximum Difficulty Level: {0}", maxDif);
                            ExportArrangement(score, arrangement, maxDif, inputFilePath, toolkitInfo);
                        }
                    }

                    if (!allDif) // only maximum difficulty
                    {
                        var baseFileName = CleanFileName(
                            String.Format("{0} - {1}", score.Artist, score.Title));
                        SaveScore(score, baseFileName, outputDir, outputFormat);
                    }
                }

                Console.WriteLine();
            }

            catch (IOException e)
            {
                Console.WriteLine("Error encountered:");
                Console.WriteLine(e.Message);
            }

        }
        public AttributesHeader2014(string arrangementFileName, Arrangement arrangement, DLCPackageData info, Platform platform)
        {
            if (arrangement.ArrangementType == ArrangementType.ShowLight)
            {
                return;
            }

            IsVocal  = arrangement.ArrangementType == ArrangementType.Vocal;
            song2014 = (IsVocal) ? null : Song2014.LoadFromFile(arrangement.SongXml.File);
            var dlcName = info.Name.ToLower();

            var albumUrn = String.Format(URN_TEMPLATE, TagValue.Image.GetDescription(), TagValue.DDS.GetDescription(), String.Format("album_{0}", dlcName));
            var jsonUrn  = String.Format(URN_TEMPLATE, TagValue.Database.GetDescription(), TagValue.JsonDB.GetDescription(), String.Format("{0}_{1}", dlcName, arrangementFileName));

            //FILL ATTRIBUTES
            this.AlbumArt              = albumUrn;
            JapaneseVocal             |= arrangement.ArrangementName == Sng.ArrangementName.JVocals;
            ArrangementName            = IsVocal ? Sng.ArrangementName.Vocals.ToString() : arrangement.ArrangementName.ToString(); //HACK: weird vocals stuff
            DLCKey                     = info.Name;                                                                                // in RS2 DLCKey = SongKey, in RS1 they are different
            SongKey                    = info.Name;
            LeaderboardChallengeRating = 0;
            ManifestUrn                = jsonUrn;
            MasterID_RDV               = arrangement.MasterId; // must be unique else in-game hang occures
            PersistentID               = arrangement.Id.ToString().Replace("-", "").ToUpper();
            Shipping                   = true;                 // false = hides the arrangement in-game

            // DLC property controls whether album artwork marker is shown in-game setlist, but
            // has side effect that 'Alternate Arrangements' are locked for newer player profiles
            DLC = true; // false = requires UPlay to unlock

            // TODO: monitor this change
            if (info.ToolkitInfo == null || info.ToolkitInfo.PackageAuthor == "Ubisoft")
            {
                SKU = "RS2"; // shows purple marker w/ "DLC" text overlay
            }
            else
            {
                SKU = ""; // hides album artwork marker in-game setlist
            }
            // this SKU and DLCKey combination shows black marker w/ "RS1" text overlay on album artwork in-game setlist
            // SKU = "RS1";
            // DLCKey = "RS1CompatibilityDisc";

            if (IsVocal)
            {
                return;
            }

            // added better AlbumNameSort feature
            AlbumName      = info.SongInfo.Album;
            AlbumNameSort  = info.SongInfo.AlbumSort;
            ArtistName     = info.SongInfo.Artist;
            CentOffset     = (!arrangement.TuningPitch.Equals(0)) ? TuningFrequency.Frequency2Cents(arrangement.TuningPitch) : 0.0;
            ArtistNameSort = info.SongInfo.ArtistSort;
            BassPick       = arrangement.ArrangementType == ArrangementType.Bass ? (int)arrangement.PluckedType : 0;
            CapoFret       = (arrangement.Sng2014.Metadata.CapoFretId == 0xFF) ? CapoFret = 0 : Convert.ToDecimal(arrangement.Sng2014.Metadata.CapoFretId);
            DNA_Chords     = arrangement.Sng2014.DNACount[(int)DNAId.Chord];
            DNA_Riffs      = arrangement.Sng2014.DNACount[(int)DNAId.Riff];
            DNA_Solo       = arrangement.Sng2014.DNACount[(int)DNAId.Solo];
            NotesEasy      = arrangement.Sng2014.NoteCount[0];
            NotesMedium    = arrangement.Sng2014.NoteCount[1];
            NotesHard      = arrangement.Sng2014.NoteCount[2];
            EasyMastery    = Math.Round((double)(NotesEasy / NotesHard), 9);
            MediumMastery  = Math.Round((double)(NotesMedium / NotesHard), 9);
            Metronome      = arrangement.Metronome == Sng.Metronome.None ? null : (int?)arrangement.Metronome;

            // TODO: monitor this change
            Representative = arrangement.ArrangementPropeties.Represent;

            RouteMask = (int)arrangement.RouteMask;

            ManifestFunctions.GetSongDifficulty(this, song2014);

            SongLength   = Math.Round(song2014.SongLength, 3, MidpointRounding.AwayFromZero);
            SongName     = info.SongInfo.SongDisplayName;
            SongNameSort = info.SongInfo.SongDisplayNameSort;
            SongYear     = info.SongInfo.SongYear;

            //Detect tuning
            var tuning = TuningDefinitionRepository.Instance.Detect(song2014.Tuning, platform.version, arrangement.ArrangementType == ArrangementType.Bass);

            Tuning = tuning.Tuning; //can we just use SongContent.Tuning

            // optional properties
            JapaneseSongName   = string.IsNullOrEmpty(info.SongInfo.JapaneseSongName) ? null : info.SongInfo.JapaneseSongName;
            JapaneseArtistName = string.IsNullOrEmpty(info.SongInfo.JapaneseArtistName) ? null : info.SongInfo.JapaneseArtistName;
        }
Example #10
0
        public AttributesHeader2014(string arrangementFileName, Arrangement arrangement, DLCPackageData info, Platform platform)
        {
            if (arrangement.ArrangementType == ArrangementType.ShowLight)
            {
                return;
            }

            IsVocal  = arrangement.ArrangementType == ArrangementType.Vocal;
            song2014 = (IsVocal) ? null : Song2014.LoadFromFile(arrangement.SongXml.File);
            var dlcName = info.Name.ToLower();

            var albumUrn = String.Format(URN_TEMPLATE, TagValue.Image.GetDescription(), TagValue.DDS.GetDescription(), String.Format("album_{0}", dlcName));
            var jsonUrn  = String.Format(URN_TEMPLATE, TagValue.Database.GetDescription(), TagValue.JsonDB.GetDescription(), String.Format("{0}_{1}", dlcName, arrangementFileName));

            //FILL ATTRIBUTES
            this.AlbumArt              = albumUrn;
            JapaneseVocal             |= arrangement.ArrangementName == Sng.ArrangementName.JVocals;
            ArrangementName            = IsVocal ? Sng.ArrangementName.Vocals.ToString() : arrangement.ArrangementName.ToString(); //HACK: weird vocals stuff
            DLC                        = true;
            DLCKey                     = info.Name;
            LeaderboardChallengeRating = 0;
            ManifestUrn                = jsonUrn;
            MasterID_RDV               = arrangement.MasterId;
            PersistentID               = arrangement.Id.ToString().Replace("-", "").ToUpper();
            Shipping                   = true;
            SKU                        = "RS2";
            SongKey                    = info.Name; // proof same same

            if (IsVocal)
            {
                return;
            }
            // added better AlbumNameSort feature
            AlbumName      = info.SongInfo.Album;
            AlbumNameSort  = info.SongInfo.AlbumSort;
            ArtistName     = info.SongInfo.Artist;
            CentOffset     = (!arrangement.TuningPitch.Equals(0)) ? TuningFrequency.Frequency2Cents(arrangement.TuningPitch) : 0.0;
            ArtistNameSort = info.SongInfo.ArtistSort;
            BassPick       = arrangement.ArrangementType == ArrangementType.Bass ? (int)arrangement.PluckedType : 0;
            CapoFret       = (arrangement.Sng2014.Metadata.CapoFretId == 0xFF) ? CapoFret = 0 : Convert.ToDecimal(arrangement.Sng2014.Metadata.CapoFretId);
            DNA_Chords     = arrangement.Sng2014.DNACount[(int)DNAId.Chord];
            DNA_Riffs      = arrangement.Sng2014.DNACount[(int)DNAId.Riff];
            DNA_Solo       = arrangement.Sng2014.DNACount[(int)DNAId.Solo];
            NotesEasy      = arrangement.Sng2014.NoteCount[0];
            NotesMedium    = arrangement.Sng2014.NoteCount[1];
            NotesHard      = arrangement.Sng2014.NoteCount[2];
            EasyMastery    = Math.Round((double)(NotesEasy / NotesHard), 9);
            MediumMastery  = Math.Round((double)(NotesMedium / NotesHard), 9);
            Metronome      = arrangement.Metronome == Sng.Metronome.None ? null : (int?)arrangement.Metronome;
            // TODO: check for bug here
            // if there is an equivalent bonus arrangement then Representative is set to "1" otherwise "0"
            Representative = Convert.ToInt32(!arrangement.BonusArr);
            RouteMask      = (int)arrangement.RouteMask;

            ManifestFunctions.GetSongDifficulty(this, song2014);

            SongLength         = Math.Round(song2014.SongLength, 3, MidpointRounding.AwayFromZero);
            SongName           = info.SongInfo.SongDisplayName;
            SongNameSort       = info.SongInfo.SongDisplayNameSort;
            JapaneseSongName   = string.IsNullOrEmpty(info.SongInfo.JapaneseSongName) ? null : info.SongInfo.JapaneseSongName;
            JapaneseArtistName = string.IsNullOrEmpty(info.SongInfo.JapaneseArtistName) ? null : info.SongInfo.JapaneseArtistName;
            SongYear           = info.SongInfo.SongYear;

            //Detect tuning
            var tuning = TuningDefinitionRepository.Instance.Detect(song2014.Tuning, platform.version, arrangement.ArrangementType == ArrangementType.Bass);

            Tuning = tuning.Tuning; //can we just use SongContent.Tuning
        }
        /// <summary>
        /// Load a XML arrangment into memory and
        /// convert to GuitarPro file
        /// </summary>
        /// <param name="inputFilePath"></param>
        /// <param name="outputDir"></param>
        /// <param name="outputFormat"></param>
        /// <param name="allDif"></param>
        public void XmlToGp5(string inputFilePath, string outputDir, string outputFormat = "gp5", bool allDif = false)
        {
            Console.WriteLine("Opening arrangement {0} ...", inputFilePath);
            Console.WriteLine();
            var score = new Score();
            var arrangement = Song2014.LoadFromFile(inputFilePath);
            var toolkitInfo = new ToolkitInfo();
            toolkitInfo.ToolkitVersion = String.Format("CST v{0}", ToolkitVersion.version);
            toolkitInfo.PackageAuthor = "XML To GP5 Converter";
            toolkitInfo.PackageVersion = arrangement.LastConversionDateTime;

            var comments = Song2014.ReadXmlComments(inputFilePath);
            foreach (var xComment in comments)
            {
                if (xComment.Value.Contains("CST"))
                {
                    toolkitInfo.ToolkitVersion = xComment.Value.Trim();
                    break;
                }
            }

            // get maximum difficulty for the arrangement
            var mf = new ManifestFunctions(GameVersion.RS2014);
            int maxDif = mf.GetMaxDifficulty(arrangement);

            if (allDif) // create separate file for each difficulty
            {
                for (int difLevel = 0; difLevel <= maxDif; difLevel++)
                {
                    ExportArrangement(score, arrangement, difLevel, inputFilePath, toolkitInfo);
                    Console.WriteLine("Difficulty Level: {0}", difLevel);

                    var baseFileName = CleanFileName(
                        String.Format("{0} - {1}", score.Artist, score.Title));
                    baseFileName += String.Format(" ({0})", arrangement.Arrangement);
                    baseFileName += String.Format(" (level {0:D2})", difLevel);

                    SaveScore(score, baseFileName, outputDir, outputFormat);
                    // remember to remove the track from the score again
                    score.Tracks.Clear();
                }
            }
            else // combine maximum difficulty arrangements into one file
            {
                Console.WriteLine("Maximum Difficulty Level: {0}", maxDif);
                ExportArrangement(score, arrangement, maxDif, inputFilePath, toolkitInfo);
            }

            if (!allDif) // only maximum difficulty
            {
                var baseFileName = CleanFileName(
                    String.Format("{0} - {1}", score.Artist, score.Title));
                SaveScore(score, baseFileName, outputDir, outputFormat);
            }
        }
        // Read a Folder (clean temp folder)
        // Decompress the PC DLCs
        // Read details and populate a DB (clean Import DB before, and only populate Main if not there already)
        public void btn_PopulateDB_Click(object sender, EventArgs e)
        {
            rtxt_StatisticsOnReadDLCs.Text = "Starting... " + "\n" + rtxt_StatisticsOnReadDLCs.Text;
            //Set_DEBUG(); //Default value when in dEV/Debug mode, if needed

            var Temp_Path_Import = txt_TempPath.Text;
            var old_Path_Import = txt_TempPath.Text + "\\0_old";
            var broken_Path_Import = txt_TempPath.Text + "\\0_broken";
            var dupli_Path_Import = txt_TempPath.Text + "\\0_duplicate";
            var dlcpacks = txt_TempPath.Text + "\\0_dlcpacks";
            var repacked_Path = txt_TempPath.Text + "\\0_repacked";
            string pathDLC = txt_RocksmithDLCPath.Text;
            CreateTempFolderStructure(Temp_Path_Import, old_Path_Import, broken_Path_Import, dupli_Path_Import, dlcpacks, pathDLC, repacked_Path);

            //Clean Temp Folder
            if (chbx_CleanTemp.Checked && !chbx_Additional_Manipulations.GetItemChecked(38)) //39.Use only unpacked songs already in the 0 / dlcpacks folder
            {
                ////clear content of dlcpacks folder
                //System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(Temp_Path_Import);
                //foreach (FileInfo file in downloadedMessageInfo.GetFiles())
                //{
                //    file.Delete();
                //}
                //foreach (DirectoryInfo dir in downloadedMessageInfo.GetDirectories())
                //{
                //    if (dir.Name != "0_dlcpacks" && dir.Name != "0_old" && dir.Name != "0_broken" && dir.Name != "0_duplicate" && dir.Name != "0_dlcpacks") dir.Delete(true);
                //}

                //clean app working folders 0 folder
                //{
                System.IO.DirectoryInfo downloadedMessageInfo2 = new DirectoryInfo(txt_TempPath.Text);
                foreach (FileInfo file in downloadedMessageInfo2.GetFiles())
                {
                    file.Delete();
                }
                foreach (DirectoryInfo dir in downloadedMessageInfo2.GetDirectories())
                {
                    if (dir.Name != "0_dlcpacks" && dir.Name != "0_old" && dir.Name != "0_broken" && dir.Name != "0_duplicate" && dir.Name != "0_dlcpacks" && dir.Name != "0_Repacked")
                        dir.Delete(true);
                }
                //}
            }

            //help code
            //using (var u = new UpdateForm())
            //{
            //    u.Init(onlineVersion);
            //    u.ShowDialog();
            //}

            //Clean ImportDB
            DataSet dss = new DataSet();
            var DB_Path = "";
            //MessageBox.Show("cleaninig");
            DB_Path = (chbx_DefaultDB.Checked == true ? MyAppWD : txt_DBFolder.Text) + "\\Files.accdb;";
            try
            {
                using (OleDbConnection cnn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DB_Path))
                {
                    OleDbDataAdapter daa = new OleDbDataAdapter("DELETE FROM Import;", cnn);
                    daa.Fill(dss, "Import");
                    daa.Dispose();
                    rtxt_StatisticsOnReadDLCs.Text = "Cleaning....Import table...." + DB_Path + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                    if (chbx_CleanDB.Checked)
                    {
                        OleDbDataAdapter dan = new OleDbDataAdapter("DELETE FROM Main;", cnn);
                        dan.Fill(dss, "Main");
                        OleDbDataAdapter dam = new OleDbDataAdapter("DELETE FROM Arrangements;", cnn);
                        dam.Fill(dss, "Arrangements");
                        OleDbDataAdapter dag = new OleDbDataAdapter("DELETE FROM Tones;", cnn);
                        dag.Fill(dss, "Tones");
                        dan.Dispose();
                        dam.Dispose();
                        dag.Dispose();
                    }

                }
            }
            catch (System.IO.FileNotFoundException ee)
            {
                // To inform the user and continue is
                // sufficient for this demonstration.
                // Your application may require different behavior.
                Console.WriteLine(ee.Message);
                rtxt_StatisticsOnReadDLCs.Text = "Error cleaning Cleaned" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                //continue;
            }
            rtxt_StatisticsOnReadDLCs.Text = DB_Path + " Cleaned" + "\n" + rtxt_StatisticsOnReadDLCs.Text;

            int i = 0;
            if (!chbx_Additional_Manipulations.GetItemChecked(38)) //39. Use only unpacked songs already in the 0/0_Import folder folder
            {
                //GetDirList and calcualte hash for the IMPORTED file
                //MessageBox.Show(pathDLC, MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                string[] filez;
                if (chbx_Additional_Manipulations.GetItemChecked(37)) //38. Import other formats but PC, as well(separately of course)
                    filez = System.IO.Directory.GetFiles(pathDLC, "*.psarc");
                else
                    filez = System.IO.Directory.GetFiles(pathDLC, "*_p.psarc");

                foreach (string s in filez)
                {
                    //try to get the details
                    // Create the FileInfo object only when needed to ensure
                    // the information is as current as possible.
                    System.IO.FileInfo fi = null;

                    try
                    {
                        fi = new System.IO.FileInfo(s);
                    }
                    catch (System.IO.FileNotFoundException ee)
                    {
                        // To inform the user and continue is
                        // sufficient for this demonstration.
                        // Your application may require different behavior.
                        Console.WriteLine(ee.Message);
                        rtxt_StatisticsOnReadDLCs.Text = "error at import" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                        continue;
                    }
                    //- To remove usage of ee and loading
                    Console.WriteLine("{0} : {1} : {2}", fi.Name, fi.Directory, loading);

                    //details end

                    //Generating the HASH code
                    var FileHash = "";
                    using (FileStream fs = File.OpenRead(s))
                    {
                        SHA1 sha = new SHA1Managed();
                        FileHash = BitConverter.ToString(sha.ComputeHash(fs));
                        fs.Close();
                    }

                    //Populate ImportDB
                    rtxt_StatisticsOnReadDLCs.Text = "File " + (i + 1) + " :" + s + "\n" + rtxt_StatisticsOnReadDLCs.Text; //+ "-------"  + fi.GetHashCode() + "-----------" + fi.Length + "-" + fi.CreationTime + "-" + fi.DirectoryName + "-" + fi.LastWriteTime + "-" + fi.Name;
                    DataSet dsz = new DataSet();
                    DB_Path = (chbx_DefaultDB.Checked == true ? MyAppWD : txt_DBFolder.Text) + "\\Files.accdb;";
                    using (OleDbConnection cnb = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DB_Path))
                    {
                        string updatecmd; //s.Substring(s.Length - pathDLC.Length)
                        updatecmd = "INSERT INTO Import (FullPath, Path, FileName, FileCreationDate, FileHash, FileSize, ImportDate) VALUES (\"" + s + "\",\"";
                        updatecmd += fi.DirectoryName + "\",\"" + fi.Name + "\",\"" + fi.CreationTime + "\",\"" + FileHash + "\",\"" + fi.Length + "\",\"";
                        updatecmd += System.DateTime.Today + "\");";
                        OleDbDataAdapter dab = new OleDbDataAdapter(updatecmd, cnb);
                        dab.Fill(dsz, "Import");
                        dab.Dispose();
                        //dsz.Tables["Files"].AcceptChanges();
                        //MessageBox.Show(da)
                    }

                    //pB_ReadDLCs.Increment(1);
                    i++;
                }

                //Delete duplicates(same £HASH) from ImportDB
                DataSet dz = new DataSet();
                DataSet drz = new DataSet();
                var del = 0;
                var no = 0;
                using (OleDbConnection cnb = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DB_Path))
                {
                    string updatecmd; //s.Substring(s.Length - pathDLC.Length)

                    updatecmd = "SELECT MAX(s.ID) FROM Import s LEFT JOIN Import as d on d.FileHash = s.FileHash WHERE d.ID is not null GROUP BY s.FileHash;";
                    OleDbDataAdapter dbf = new OleDbDataAdapter(updatecmd, cnb);
                    dbf.Fill(dz, "Import");
                    no = dz.Tables[0].Rows.Count;
                    dbf.Dispose();
                    rtxt_StatisticsOnReadDLCs.Text = updatecmd + "\n" + rtxt_StatisticsOnReadDLCs.Text;

                    updatecmd = @"SELECT * FROM Import
                                WHERE ID not IN (SELECT MAX(s.ID) FROM Import s LEFT JOIN Import as d on d.FileHash=s.FileHash WHERE d.ID is not null GROUP BY s.FileHash);";
                    OleDbDataAdapter dff = new OleDbDataAdapter(updatecmd, cnb);
                    dff.Fill(drz, "Import");
                    del = drz.Tables[0].Rows.Count;
                    dff.Dispose();

                    updatecmd = @"DELETE FROM Import
                                WHERE ID not IN (SELECT MAX(s.ID) FROM Import s LEFT JOIN Import as d on d.FileHash=s.FileHash WHERE d.ID is not null GROUP BY s.FileHash);";
                    OleDbDataAdapter db = new OleDbDataAdapter(updatecmd, cnb);
                    db.Fill(dz, "Import");
                    db.Dispose();

                    //dsz.Tables["Files"].AcceptChanges();
                    //MessageBox.Show(da)
                }
                rtxt_StatisticsOnReadDLCs.Text = no + "/" + i + " Import files Inserted (excl. " + del + " duplicates)" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
            }
            else
            {
                System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(txt_RocksmithDLCPath.Text);
                foreach (DirectoryInfo dir in downloadedMessageInfo.GetDirectories())
                {

                    //Populate ImportDB
                    rtxt_StatisticsOnReadDLCs.Text = "Folder " + (i + 1) + " :" + "s" + "\n" + rtxt_StatisticsOnReadDLCs.Text; //+ "-------"  + fi.GetHashCode() + "-----------" + fi.Length + "-" + fi.CreationTime + "-" + fi.DirectoryName + "-" + fi.LastWriteTime + "-" + fi.Name;
                    DataSet dsz = new DataSet();
                    DB_Path = (chbx_DefaultDB.Checked == true ? MyAppWD : txt_DBFolder.Text) + "\\Files.accdb;";
                    using (OleDbConnection cnb = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DB_Path))
                    {
                        string updatecmd; //s.Substring(s.Length - pathDLC.Length)
                        updatecmd = "INSERT INTO Import (FullPath, Path, FileName, FileCreationDate, FileHash, FileSize, ImportDate) VALUES (\"" + txt_RocksmithDLCPath.Text + "\\" + dir.Name + "\",\"";
                        updatecmd += txt_RocksmithDLCPath.Text + "\\" + dir.Name + "\",\"" + txt_RocksmithDLCPath.Text + "\\" + dir.Name + "\",\"" + DateTime.Now + "\",\"" + "0" + "\",\"" + "0" + "\",\"";
                        updatecmd += System.DateTime.Today + "\");";
                        OleDbDataAdapter dab = new OleDbDataAdapter(updatecmd, cnb);
                        dab.Fill(dsz, "Import");
                        dab.Dispose();
                        //dsz.Tables["Files"].AcceptChanges();
                        //MessageBox.Show(da)
                        // if (dir.Name != "dlcpacks" && dir.Name != "0_old" && dir.Name != "0_broken" && dir.Name != "0_duplicate") dir.Delete(true);
                    }
                }
            }

            //START WITH mAINdb UPDATE
            DataSet ds = new DataSet();
            DataSet dns = new DataSet();
            var m = 0;
            var errr = true;
            try
            {
                using (OleDbConnection cnn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DB_Path))
                {// 1. If hash already exists do not insert
                    var cmd = @"SELECT DISTINCT FullPath, Path, FileName, FileHash, FileSize, ImportDate, m.Import_Date
                            FROM Import as i
                            LEFT JOIN Main as m on m.File_Hash = i.FileHash OR m.Original_File_Hash = i.FileHash
                            WHERE m.ID is not NULL;";
                    OleDbDataAdapter dha = new OleDbDataAdapter(cmd, cnn);
                    dha.Fill(dns, "Import");
                    dha.Dispose();
                    var tft = "\n Ignoring "; ;
                    var noOfRec = dns.Tables[0].Rows.Count;
                    //rtxt_StatisticsOnReadDLCs.Text = noOfRec + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                    if (chbx_Additional_Manipulations.GetItemChecked(29) && noOfRec > 0) //31. When importing delete identical duplicates(same hash/filesize)
                        tft = "";
                    for (m = 0; m < noOfRec; m++)
                    {
                        var newf = dns.Tables[0].Rows[m].ItemArray[0].ToString().Replace(pathDLC, dupli_Path_Import);
                        rtxt_StatisticsOnReadDLCs.Text = newf + "\n" + dns.Tables[0].Rows[m].ItemArray[0].ToString() + "\n" + rtxt_StatisticsOnReadDLCs.Text;//dns.Tables[0].Rows[m].ItemArray[0].ToString()
                        if (chbx_Additional_Manipulations.GetItemChecked(29)) //&& !File.Exists(newf) //As the new file might have a different name e.g. (1) ....etc.
                        {
                            File.Copy(dns.Tables[0].Rows[m].ItemArray[0].ToString(), newf, true);
                            try
                            {
                                File.Delete(dns.Tables[0].Rows[m].ItemArray[0].ToString());
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                MessageBox.Show("Issues when moving to duplicate folder" + "-" + ex.Message + dns.Tables[0].Rows[m].ItemArray[0].ToString());
                            }
                            tft += "\n Deleting " + dns.Tables[0].Rows[m].ItemArray[0].ToString() + " as imported on " + dns.Tables[0].Rows[m].ItemArray[5].ToString();
                        }

                    }

                    rtxt_StatisticsOnReadDLCs.Text = tft + noOfRec + "/" + (noOfRec + m) + " already imported" + "\n" + rtxt_StatisticsOnReadDLCs.Text;

                    cmd = @"SELECT FullPath, Path, FileName, FileHash, FileSize, ImportDate
                                FROM Import as i
                                LEFT JOIN Main as m on m.File_Hash = i.FileHash OR m.Original_File_Hash = i.FileHash
                                WHERE m.ID is NULL;";
                    OleDbDataAdapter daa = new OleDbDataAdapter(cmd, cnn);
                    daa.Fill(ds, "Import");
                    daa.Dispose();
                    noOfRec = ds.Tables[0].Rows.Count;//ds.Tables[0].Rows[0].ItemArray[0].ToString();
                    rtxt_StatisticsOnReadDLCs.Text = noOfRec + "/" + (noOfRec + m) + " New Songs 2 Import into MainDB" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                    //OleDbDataAdapter dac = new OleDbDataAdapter("INSERT INTO Main (Import_Path, Original_FileName, Current_FileName, File_Hash, File_Size, Import_Date) SELECT Path, FileName,FileName, FileHash, FileSize, ImportDate FROM Import as i LEFT JOIN Main as m on m.File_Hash = i.FileHash OR m.Original_File_Hash = i.FileHash WHERE m.ID is NULL;", cnn);
                    //dac.Fill(ds, "Main");
                    //OleDbDataAdapter dac = new OleDbDataAdapter(updatecmd, cnb);

                    //OleDbDataAdapter dad = new OleDbDataAdapter("SELECT count(*) FROM Import as i LEFT JOIN Main as m on m.File_Hash = i.FileHash OR m.Original_File_Hash = i.FileHash WHERE m.ID is not NULL;", cnn);
                    //dad.Fill(ds, "Import");

                    if (noOfRec > 0)
                    {
                        //Move duplicates to the end

                        for (var k = 0; k <= noOfRec - 1; k++)
                        {
                            //for (j = 0; j <= noOfRec - 1; j++)
                            //{
                            if (1 == 0)
                            {
                                ds.Tables[0].Rows[i].ItemArray[0] = ds.Tables[0].Rows[i];
                                noOfRec++;
                            }
                            //}
                        }
                        //connection.Open();
                        //DataSet dds = new DataSet();
                        //OleDbDataAdapter daf = new OleDbDataAdapter("SELECT FullPath, Path, FileName, FileHash, FileSize, ImportDate FROM Import as i LEFT JOIN Main as m on m.File_Hash = i.FileHash OR m.Original_File_Hash = i.FileHash WHERE m.ID is NULL;", cnn);
                        //daf.Fill(dds, "Import");
                        //oledbAdapter.Dispose();
                        //connection.Close();
                        //dss.Tables["Import"].AcceptChanges();
                        pB_ReadDLCs.Value = 0;
                        pB_ReadDLCs.Maximum = 2 * (noOfRec - 1);
                        bool duplit = false;
                        string[,] dupliInfo = new string[0, 0];
                        int[] dupliSongs = new int[noOfRec];
                        for (var j = 0; j <= 1; j++)
                            for (i = 0; i <= noOfRec - 1; i++)
                            {
                                if (j == 1 && dupliSongs[i] == 0)
                                    ;
                                else
                                {
                                    duplit = false;
                                    //MessageBox.Show(pB_ReadDLCs.Maximum+" test " +i);
                                    //DataTable AccTable = aSet.Tables["Accounts"];
                                    var FullPath = ds.Tables[0].Rows[i].ItemArray[0].ToString();
                                    rtxt_StatisticsOnReadDLCs.Text = (i + 1) + "/" + noOfRec + " " + FullPath + "\n\n" + rtxt_StatisticsOnReadDLCs.Text;
                                    errr = false;
                                    if (!chbx_Additional_Manipulations.GetItemChecked(37))
                                        if (!FullPath.IsValidPSARC())
                                        {
                                            MessageBox.Show(String.Format("File '{0}' isn't valid. File extension was changed to '.invalid'", Path.GetFileName(FullPath)), MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                            var Pathh = broken_Path_Import + "\\" + ds.Tables[0].Rows[i].ItemArray[2].ToString();
                                            if (chbx_Additional_Manipulations.GetItemChecked(30))
                                            {
                                                File.Copy(FullPath.Replace(".psarc", ".invalid"), Pathh, true);//.GetPlatform() FullPath.Substring(FullPath.LastIndexOf("\\")+1, FullPath.Length));
                                                File.Delete(FullPath.Replace(".psarc", ".invalid"));
                                            }
                                            errr = true;
                                            rtxt_StatisticsOnReadDLCs.Text = "FAILED2 @Import cause of extension issue but copied in the broken folder" + "----" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                            continue;
                                        }

                                    var unpackedDir = "";
                                    //rtxt_StatisticsOnReadDLCs.Text = "1" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                    var packagePlatform = FullPath.GetPlatform();
                                    var Available_Duplicate = "No";
                                    var Available_Old = "No";
                                    if (!chbx_Additional_Manipulations.GetItemChecked(38)) //39. Use only unpacked songs already in the 0/dlcpacks folder
                                    {

                                        try
                                        {
                                            // UNPACK
                                            unpackedDir = Packer.Unpack(FullPath, Temp_Path_Import, true, true, false);
                                            //packagePlatform = FullPath.GetPlatform();
                                        }
                                        catch (Exception ex)
                                        {
                                            MessageBox.Show("Unpacking ..." + ex.Message, MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                            // MessageBox.Show("Error decompressing the file!(BACH OFFICIAL DLC CAUSE OF WEIRD CHAR IN FILENAME) " + "-" );
                                            rtxt_StatisticsOnReadDLCs.Text = ex.Message + "problem at unpacking" + FullPath + "---" + Temp_Path_Import + "...\n\n" + rtxt_StatisticsOnReadDLCs.Text;
                                            errr = false;
                                            //rtxt_StatisticsOnReadDLCs.Text = "predone" + "..." + rtxt_StatisticsOnReadDLCs.Text;
                                            try
                                            {
                                                var Pathh = broken_Path_Import + "\\" + ds.Tables[0].Rows[i].ItemArray[2].ToString();
                                                if (chbx_Additional_Manipulations.GetItemChecked(30))
                                                {
                                                    File.Copy(FullPath, Pathh, true);//.GetPlatform() FullPath.Substring(FullPath.LastIndexOf("\\")+1, FullPath.Length));
                                                    File.Delete(FullPath);
                                                }
                                                errr = true; //bcapi???
                                            }
                                            catch (System.IO.FileNotFoundException ee)
                                            {
                                                rtxt_StatisticsOnReadDLCs.Text = "FAILED2" + ee.Message + "----" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                Console.WriteLine(ee.Message);
                                            }
                                        }
                                    }
                                    else unpackedDir = FullPath;

                                    //Commenting Reorganize as they might have fixed the incompatib char issue
                                    // REORGANIZE
                                    //System.Threading.Thread.Sleep(1000);
                                    var platform = FullPath.GetPlatform();
                                    //rtxt_StatisticsOnReadDLCs.Text = unpackedDir + " reorg...\n" + rtxt_StatisticsOnReadDLCs.Text;
                                    if (chbx_Additional_Manipulations.GetItemChecked(36) && !errr) //37. Keep the Uncompressed Songs superorganized
                                    {
                                        try
                                        {
                                            var structured = ConfigRepository.Instance().GetBoolean("creator_structured");
                                            if (structured)
                                            {
                                                unpackedDir = DLCPackageData.DoLikeProject(unpackedDir);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            // System.Threading.Thread.Sleep(20000);
                                            //rtxt_StatisticsOnReadDLCs.Text = "1111 ...\n" + rtxt_StatisticsOnReadDLCs.Text;
                                            var jsonFiles = Directory.GetFiles(unpackedDir, "*.json", SearchOption.AllDirectories);
                                            foreach (var json in jsonFiles)
                                            {
                                                if (Path.GetFileNameWithoutExtension(json).ToUpperInvariant().Contains("VOCAL"))
                                                    continue;
                                                if (platform.version == RocksmithToolkitLib.GameVersion.RS2014)
                                                {
                                                    var jsons = Directory.GetFiles(unpackedDir, String.Format("*{0}.json", Path.GetFileNameWithoutExtension(json)), SearchOption.AllDirectories);
                                                    if (jsons.Length > 0)
                                                    {
                                                        string textfile = File.ReadAllText(json);
                                                        textfile = textfile.Replace("?", "");
                                                        textfile = textfile.Replace("/", "-");
                                                        textfile = textfile.Replace("\\\"", "'");
                                                        textfile = textfile.Replace("Sonata:", "Sonata");
                                                        File.WriteAllText(json, textfile);
                                                    }
                                                }
                                            }
                                            rtxt_StatisticsOnReadDLCs.Text = ex.Message + "problem at reorg" + unpackedDir + "---" + Temp_Path_Import + "...\n" + rtxt_StatisticsOnReadDLCs.Text;

                                            try
                                            {
                                                var structured = ConfigRepository.Instance().GetBoolean("creator_structured");
                                                if (structured)
                                                {
                                                    unpackedDir = DLCPackageData.DoLikeProject(unpackedDir);
                                                }

                                            }
                                            catch (System.IO.FileNotFoundException ee)
                                            {
                                                var Pathh = broken_Path_Import + "\\" + ds.Tables[0].Rows[i].ItemArray[2].ToString();
                                                if (chbx_Additional_Manipulations.GetItemChecked(30))
                                                {
                                                    File.Copy(FullPath, Pathh, true);//.GetPlatform() FullPath.Substring(FullPath.LastIndexOf("\\")+1, FullPath.Length));
                                                    File.Delete(FullPath);
                                                }
                                                errr = true;
                                                rtxt_StatisticsOnReadDLCs.Text = "FAILED2 @org but copied in the broken folder" + ee.Message + "----" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                Console.WriteLine(ee.Message);
                                            }
                                        }
                                    }

                                    // rtxt_StatisticsOnReadDLCs.Text = "2" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                    var DD = "No";
                                    var Bass_Has_DD = "No";
                                    var sect1on = "Yes";
                                    if (!errr)
                                    {
                                        //FIX for adding preview_preview_preview
                                        if (unpackedDir == "")
                                        {
                                            unpackedDir = "C:\\GitHub\\tmp\\0\\dlcpacks\\songs_Pc";
                                            rtxt_StatisticsOnReadDLCs.Text = "Issues at decompressing WEMs or FAILED2 empty path" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                        }
                                        // LOAD DATA
                                        //rtxt_StatisticsOnReadDLCs.Text = "2.5" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                        DLCPackageData info = null;
                                        try
                                        {
                                            info = DLCPackageData.LoadFromFolder(unpackedDir, packagePlatform);
                                        }
                                        catch (Exception ee)
                                        {
                                            MessageBox.Show(ee.Message, MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                            rtxt_StatisticsOnReadDLCs.Text = ee.Message + " Broken Song Not Imported" + "----" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                            Console.WriteLine(ee.Message);
                                            var Pathh = broken_Path_Import + "\\" + ds.Tables[0].Rows[i].ItemArray[2].ToString();
                                            if (chbx_Additional_Manipulations.GetItemChecked(30))
                                            {
                                                File.Copy(FullPath, Pathh, true);//.GetPlatform() FullPath.Substring(FullPath.LastIndexOf("\\")+1, FullPath.Length));
                                                File.Delete(FullPath);
                                            }
                                            rtxt_StatisticsOnReadDLCs.Text = "FAILED2 @Load but copied in the broken folder" + ee.Message + "----" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                            Console.WriteLine(ee.Message);
                                            continue;
                                        }
                                        //rtxt_StatisticsOnReadDLCs.Text = "3" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                        string ff = info.SongInfo.Artist, gg = info.SongInfo.ArtistSort, hhh = info.SongInfo.SongDisplayName, jj = info.SongInfo.SongDisplayNameSort, kk = info.SongInfo.Album;
                                        if (chbx_Additional_Manipulations.GetItemChecked(35)) //36.
                                        {
                                            //Remove weird/illegal characters
                                            info.SongInfo.Artist = info.SongInfo.Artist.Replace("\\", "");
                                            info.SongInfo.Artist = info.SongInfo.Artist.Replace("\"", "");
                                            info.SongInfo.Artist = info.SongInfo.Artist.Replace("/", "");
                                            info.SongInfo.Artist = info.SongInfo.Artist.Replace("?", "");
                                            info.SongInfo.Artist = info.SongInfo.Artist.Replace(":", "");
                                            info.SongInfo.Artist = info.SongInfo.Artist.Replace("\"", "'");
                                            info.SongInfo.ArtistSort = info.SongInfo.ArtistSort.Replace("\\", "");
                                            info.SongInfo.ArtistSort = info.SongInfo.ArtistSort.Replace("\"", "");
                                            info.SongInfo.ArtistSort = info.SongInfo.ArtistSort.Replace("/", "");
                                            info.SongInfo.ArtistSort = info.SongInfo.ArtistSort.Replace("?", "");
                                            info.SongInfo.ArtistSort = info.SongInfo.ArtistSort.Replace(":", "");
                                            info.SongInfo.ArtistSort = info.SongInfo.ArtistSort.Replace("\"", "'");
                                            info.SongInfo.SongDisplayName = info.SongInfo.SongDisplayName.Replace("\\", "");
                                            info.SongInfo.SongDisplayName = info.SongInfo.SongDisplayName.Replace("\"", "");
                                            info.SongInfo.SongDisplayName = info.SongInfo.SongDisplayName.Replace("/", "");
                                            info.SongInfo.SongDisplayName = info.SongInfo.SongDisplayName.Replace("?", "");
                                            info.SongInfo.SongDisplayName = info.SongInfo.SongDisplayName.Replace(":", "");
                                            info.SongInfo.SongDisplayName = info.SongInfo.SongDisplayName.Replace("\"", "'");
                                            info.SongInfo.SongDisplayNameSort = info.SongInfo.SongDisplayNameSort.Replace("\\", "");
                                            info.SongInfo.SongDisplayNameSort = info.SongInfo.SongDisplayNameSort.Replace("/", "");
                                            info.SongInfo.SongDisplayNameSort = info.SongInfo.SongDisplayNameSort.Replace("\"", "");
                                            info.SongInfo.SongDisplayNameSort = info.SongInfo.SongDisplayNameSort.Replace("?", "");
                                            info.SongInfo.SongDisplayNameSort = info.SongInfo.SongDisplayNameSort.Replace(":", "");
                                            info.SongInfo.SongDisplayNameSort = info.SongInfo.SongDisplayNameSort.Replace("\"", "'");
                                            info.SongInfo.Album = info.SongInfo.Album.Replace("\\", "");
                                            info.SongInfo.Album = info.SongInfo.Album.Replace("\"", "");
                                            info.SongInfo.Album = info.SongInfo.Album.Replace("/", "");
                                            info.SongInfo.Album = info.SongInfo.Album.Replace("?", "");
                                            info.SongInfo.Album = info.SongInfo.Album.Replace(":", "");

                                            //info.AlbumArtPath = info.SongInfo.Album.Replace("/", "");
                                            if (ff != info.SongInfo.Artist) rtxt_StatisticsOnReadDLCs.Text = "removing potentially illegal characters \\,\",/,?,: from Artist..." + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                            if (gg != info.SongInfo.ArtistSort) rtxt_StatisticsOnReadDLCs.Text = "removing potential illegally characters \\,\",/,?,: from ArtistSort..." + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                            if (hhh != info.SongInfo.SongDisplayName) rtxt_StatisticsOnReadDLCs.Text = "removing potentially illegal characters \\,\",/,?,: from Title..." + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                            if (jj != info.SongInfo.SongDisplayNameSort) rtxt_StatisticsOnReadDLCs.Text = "removing potentially illegal characters \\,\",/,?,: from TitleSort..." + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                            if (kk != info.SongInfo.Album) rtxt_StatisticsOnReadDLCs.Text = "removing potentially illegal characters \\,\",/,?,: from Album..." + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                        }
                                        //rtxt_StatisticsOnReadDLCs.Text = "4" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                        if (chbx_Additional_Manipulations.GetItemChecked(16)) //17.Import with Artist/ Title same as Artist / Title Sort
                                        {
                                            info.SongInfo.ArtistSort = info.SongInfo.Artist;
                                            info.SongInfo.SongDisplayNameSort = info.SongInfo.SongDisplayName;
                                        }
                                        //rtxt_StatisticsOnReadDLCs.Text = "5 :"+ info.SongInfo.SongDisplayNameSort +  "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                        if (chbx_Additional_Manipulations.GetItemChecked(22)) //23. Import with the The/Die only at the end of Title Sort
                                        {
                                            if (chbx_Additional_Manipulations.GetItemChecked(20))
                                            {
                                                if (info.SongInfo.SongDisplayNameSort.Length > 4) info.SongInfo.SongDisplayNameSort = (info.SongInfo.SongDisplayNameSort.Substring(0, 4) == "The " ? info.SongInfo.SongDisplayNameSort.Substring(4, info.SongInfo.SongDisplayNameSort.Length - 4) + ",The" : info.SongInfo.SongDisplayNameSort);
                                                if (info.SongInfo.SongDisplayNameSort.Length > 4) info.SongInfo.SongDisplayNameSort = (info.SongInfo.SongDisplayNameSort.Substring(0, 4) == "Die " ? info.SongInfo.SongDisplayNameSort.Substring(4, info.SongInfo.SongDisplayNameSort.Length - 4) + ",Die" : info.SongInfo.SongDisplayNameSort);
                                                if (info.SongInfo.SongDisplayNameSort.Length > 4) info.SongInfo.SongDisplayNameSort = (info.SongInfo.SongDisplayNameSort.Substring(0, 4) == "the " ? info.SongInfo.SongDisplayNameSort.Substring(4, info.SongInfo.SongDisplayNameSort.Length - 4) + ",The" : info.SongInfo.SongDisplayNameSort);
                                                if (info.SongInfo.SongDisplayNameSort.Length > 4) info.SongInfo.SongDisplayNameSort = (info.SongInfo.SongDisplayNameSort.Substring(0, 4) == "die " ? info.SongInfo.SongDisplayNameSort.Substring(4, info.SongInfo.SongDisplayNameSort.Length - 4) + ",Die" : info.SongInfo.SongDisplayNameSort);
                                                if (info.SongInfo.SongDisplayNameSort.Length > 4) info.SongInfo.SongDisplayNameSort = (info.SongInfo.SongDisplayNameSort.Substring(0, 4) == "THE " ? info.SongInfo.SongDisplayNameSort.Substring(4, info.SongInfo.SongDisplayNameSort.Length - 4) + ",The" : info.SongInfo.SongDisplayNameSort);
                                                if (info.SongInfo.SongDisplayNameSort.Length > 4) info.SongInfo.SongDisplayNameSort = (info.SongInfo.SongDisplayNameSort.Substring(0, 4) == "DIE " ? info.SongInfo.SongDisplayNameSort.Substring(4, info.SongInfo.SongDisplayNameSort.Length - 4) + ",Die" : info.SongInfo.SongDisplayNameSort);

                                            }
                                            if (info.SongInfo.ArtistSort.Length > 4) info.SongInfo.ArtistSort = (info.SongInfo.ArtistSort.Substring(0, 4) == "The " ? info.SongInfo.ArtistSort.Substring(4, info.SongInfo.ArtistSort.Length - 4) + ",The" : info.SongInfo.ArtistSort);
                                            if (info.SongInfo.ArtistSort.Length > 4) info.SongInfo.ArtistSort = (info.SongInfo.ArtistSort.Substring(0, 4) == "Die " ? info.SongInfo.ArtistSort.Substring(4, info.SongInfo.ArtistSort.Length - 4) + ",Die" : info.SongInfo.ArtistSort);
                                            if (info.SongInfo.ArtistSort.Length > 4) info.SongInfo.ArtistSort = (info.SongInfo.ArtistSort.Substring(0, 4) == "the " ? info.SongInfo.ArtistSort.Substring(4, info.SongInfo.ArtistSort.Length - 4) + ",The" : info.SongInfo.ArtistSort);
                                            if (info.SongInfo.ArtistSort.Length > 4) info.SongInfo.ArtistSort = (info.SongInfo.ArtistSort.Substring(0, 4) == "die " ? info.SongInfo.ArtistSort.Substring(4, info.SongInfo.ArtistSort.Length - 4) + ",Die" : info.SongInfo.ArtistSort);
                                            if (info.SongInfo.ArtistSort.Length > 4) info.SongInfo.ArtistSort = (info.SongInfo.ArtistSort.Substring(0, 4) == "THE " ? info.SongInfo.ArtistSort.Substring(4, info.SongInfo.ArtistSort.Length - 4) + ",The" : info.SongInfo.ArtistSort);
                                            if (info.SongInfo.ArtistSort.Length > 4) info.SongInfo.ArtistSort = (info.SongInfo.ArtistSort.Substring(0, 4) == "DIE " ? info.SongInfo.ArtistSort.Substring(4, info.SongInfo.ArtistSort.Length - 4) + ",Die" : info.SongInfo.ArtistSort);
                                        }
                                        //rtxt_StatisticsOnReadDLCs.Text = "6" + "\n" + rtxt_StatisticsOnReadDLCs.Text;

                                        //if (i == 0) MessageBox.Show("3");
                                        rtxt_StatisticsOnReadDLCs.Text = "\n Song " + (i + 1) + ": " + info.SongInfo.Artist + " - " + info.SongInfo.SongDisplayName + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                        pB_ReadDLCs.Increment(1);

                                        //calculate if has DD (Dynamic Dificulty)..if at least 1 track has a difficulty bigger than 1 then it has
                                        var xmlFiles = Directory.GetFiles(unpackedDir, "*.xml", SearchOption.AllDirectories);
                                        platform = FullPath.GetPlatform();
                                        var g = 0;
                                        List<string> clist = new List<string>();
                                        List<string> dlist = new List<string>();
                                        foreach (var xml in xmlFiles)
                                        {
                                            if (Path.GetFileNameWithoutExtension(xml).ToLower().Contains("vocal"))
                                            {
                                                clist.Add("");
                                                dlist.Add("No"); continue;
                                            }

                                            if (Path.GetFileNameWithoutExtension(xml).ToLower().Contains("showlight"))
                                            {
                                                clist.Add("");
                                                dlist.Add("No"); continue;
                                            }

                                            // rtxt_StatisticsOnReadDLCs.Text = "ffff\n" + rtxt_StatisticsOnReadDLCs.Text;
                                            platform.version = RocksmithToolkitLib.GameVersion.RS2014;
                                            //rtxt_StatisticsOnReadDLCs.Text = "ddf\n" + rtxt_StatisticsOnReadDLCs.Text;
                                            Song2014 xmlContent = null;
                                            try
                                            {
                                                xmlContent = Song2014.LoadFromFile(xml);
                                            }
                                            catch (Exception ee)
                                            {
                                                MessageBox.Show(ee.Message, MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                rtxt_StatisticsOnReadDLCs.Text = ee.Message + " Broken Song Not Imported" + "----" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                Console.WriteLine(ee.Message);
                                                var Pathh = broken_Path_Import + "\\" + ds.Tables[0].Rows[i].ItemArray[2].ToString();
                                                if (chbx_Additional_Manipulations.GetItemChecked(30))
                                                {
                                                    File.Copy(FullPath, Pathh, true);//.GetPlatform() FullPath.Substring(FullPath.LastIndexOf("\\")+1, FullPath.Length));
                                                    File.Delete(FullPath);
                                                }
                                                rtxt_StatisticsOnReadDLCs.Text = "FAILED2 @XML parse but copied in the broken folder" + ee.Message + "----" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                Console.WriteLine(ee.Message);
                                                continue;
                                            }
                                            //rtxt_StatisticsOnReadDLCs.Text = "xxx\n" + rtxt_StatisticsOnReadDLCs.Text;
                                            var manifestFunctions = new ManifestFunctions(platform.version);
                                            //rtxt_StatisticsOnReadDLCs.Text = "aaa\n" + rtxt_StatisticsOnReadDLCs.Text;
                                            //Get sections and lastconvdate
                                            var json = Directory.GetFiles(unpackedDir, String.Format("*{0}.json", Path.GetFileNameWithoutExtension(xml)), SearchOption.AllDirectories);
                                            //rtxt_StatisticsOnReadDLCs.Text = json.Length + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                            if (json.Length > 0)//&& g==1
                                            {
                                                foreach (var fl in json)
                                                {
                                                    //rtxt_StatisticsOnReadDLCs.Text = Path.GetFileNameWithoutExtension(fl).ToLower() + " name " +"\n" + rtxt_StatisticsOnReadDLCs.Text;

                                                    if (Path.GetFileNameWithoutExtension(fl).ToLower().Contains("bass") || Path.GetFileNameWithoutExtension(fl).ToLower().Contains("lead") || Path.GetFileNameWithoutExtension(fl).ToLower().Contains("rhythm") || Path.GetFileNameWithoutExtension(fl).ToLower().Contains("combo"))
                                                    {
                                                        Attributes2014 attr = Manifest2014<Attributes2014>.LoadFromFile(fl).Entries.ToArray()[0].Value.ToArray()[0].Value;
                                                        manifestFunctions.GenerateSectionData(attr, xmlContent);
                                                        //rtxt_StatisticsOnReadDLCs.Text = Path.GetFileNameWithoutExtension(fl).ToLower() + " json lastconv date: " + attr.LastConversionDateTime + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                        //rtxt_StatisticsOnReadDLCs.Text = json.Length + "sections: " + attr.Sections.Count + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                        if (attr.Sections.Count == 0) sect1on = "No";
                                                        clist.Add(attr.LastConversionDateTime);
                                                        dlist.Add((attr.Sections.Count > 0 ? "Yes" : "No"));
                                                        //rtxt_StatisticsOnReadDLCs.Text = "techniques count: " + attr.Techniques.Count + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                    }
                                                    else
                                                    {
                                                        rtxt_StatisticsOnReadDLCs.Text = "no section/lastconvdate" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                        clist.Add("");
                                                        dlist.Add("No");
                                                    }
                                                }
                                            }

                                            g++;

                                            if (manifestFunctions.GetMaxDifficulty(xmlContent) > 1) DD = "Yes";

                                            //Bass_Has_DD
                                            //rtxt_StatisticsOnReadDLCs.Text = "\n chekin for BassDD" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                            var manifestFunctions1 = new ManifestFunctions(platform.version);
                                            if (Path.GetFileNameWithoutExtension(xml).ToLower().Contains("bass"))
                                            {
                                                //rtxt_StatisticsOnReadDLCs.Text = "\n still chekin for BassDD" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                platform.version = RocksmithToolkitLib.GameVersion.RS2014;
                                                Song2014 xmlContent1 = Song2014.LoadFromFile(xml);

                                                if (manifestFunctions1.GetMaxDifficulty(xmlContent1) > 1)
                                                    Bass_Has_DD = "Yes";
                                            }
                                        }

                                        // READ ARRANGEMENTS
                                        //rtxt_StatisticsOnReadDLCs.Text = "3" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                        //var updateAcmd = "";
                                        var Lead = "No";
                                        var Bass = "No";
                                        var Vocalss = "No";
                                        var Guitar = "No";
                                        var Rhythm = "No";
                                        var Combo = "No";
                                        var PluckedType = "";
                                        var Tunings = "";
                                        var bonus = "No";
                                        List<string> alist = new List<string>();
                                        List<string> blist = new List<string>();
                                        //var jsonFiles = Directory.GetFiles(unpackedDir, "*.json", SearchOption.AllDirectories); //Get directory of JSON files in case song dir is not ORGANIZED :)
                                        foreach (var arg in info.Arrangements)
                                        {
                                            if (arg.BonusArr) bonus = "Yes";

                                            if (arg.ArrangementType == ArrangementType.Guitar)
                                            {
                                                Guitar = "Yes";
                                                if (arg.Tuning != Tunings && Tunings != "") Tunings = "Different";
                                                else Tunings = arg.Tuning;

                                                if (arg.Name == ArrangementName.Lead) Lead = "Yes";
                                                else if (arg.Name == ArrangementName.Rhythm) Rhythm = "Yes";
                                                else if (arg.Name == ArrangementName.Combo) Combo = "Yes";
                                            }

                                            else if (arg.ArrangementType == ArrangementType.Vocal) Vocalss = "Yes";
                                            else if (arg.ArrangementType == ArrangementType.Bass)
                                            {
                                                Bass = "Yes";

                                                PluckedType = arg.PluckedType.ToString();
                                                if (arg.Tuning != Tunings && Tunings != "") Tunings = "Different";
                                                else Tunings = arg.Tuning;
                                            }
                                            //rtxt_StatisticsOnReadDLCs.Text = "gen ar hashes: " +arg.SongXml.File+"/"+arg.SongXml.File + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                            var s1 = arg.SongXml.File;
                                            using (FileStream fs = File.OpenRead(s1))
                                            {
                                                SHA1 sha = new SHA1Managed();
                                                alist.Add((BitConverter.ToString(sha.ComputeHash(fs))).ToString());
                                                fs.Close();
                                            }

                                            if (chbx_Additional_Manipulations.GetItemChecked(36)) //37. Keep the Uncompressed Songs superorganized
                                                s1 = (arg.SongXml.File.Replace(".xml", ".json").Replace("\\EOF\\", "\\Toolkit\\"));
                                            else
                                                s1 = arg.SongXml.File.Replace(".xml", ".json").Replace("\\songs\\arr", "\\" + calc_path(Directory.GetFiles(unpackedDir, "*.json", SearchOption.AllDirectories)[0]));

                                            if (File.Exists(s1))
                                                using (FileStream fss = File.OpenRead(s1))
                                                {
                                                    SHA1 sha = new SHA1Managed();
                                                    blist.Add((BitConverter.ToString(sha.ComputeHash(fss))).ToString());
                                                    fss.Close();
                                                }
                                            else blist.Add("0");
                                            //rtxt_StatisticsOnReadDLCs.Text = "done ar hashes: " +"\n" + rtxt_StatisticsOnReadDLCs.Text;

                                        }
                                        //rtxt_StatisticsOnReadDLCs.Text = "4" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                        //Check Tones
                                        var Tones_Custom = "No";
                                        foreach (var tn in info.TonesRS2014)//, Type
                                        {
                                            if (tn.IsCustom)
                                                Tones_Custom = "Yes";
                                        }

                                        var alt = "";
                                        var trackno = -1;

                                        Is_MultiTrack = "";
                                        MultiTrack_Version = "";

                                        //Get TrackNo
                                        trackno = 0;
                                        if (chbx_Additional_Manipulations.GetItemChecked(41))
                                            trackno = (MainDB.GetTrackNo(info.SongInfo.Artist, info.SongInfo.Album, info.SongInfo.SongDisplayName));
                                        ExistingTrackNo = "";
                                        //Get Author and Toolkit version
                                        var versionFile = Directory.GetFiles(unpackedDir, "toolkit.version", SearchOption.AllDirectories);
                                        tkversion = "";
                                        author = "";
                                        var Has_author = "";
                                        if (versionFile.Length > 0)
                                            tkversion = ReadPackageToolkitVersion(versionFile[0]);

                                        if (versionFile.Length > 0)
                                        {
                                            author = ReadPackageAuthor(versionFile[0]);
                                            if (tkversion.Length == 0)
                                                tkversion = ReadPackageOLDToolkitVersion(versionFile[0]);
                                        }
                                        if (author == "" && tkversion != "") { author = "Custom Song Creator"; Has_author = "No"; }
                                        else Has_author = "Yes";

                                        //rtxt_StatisticsOnReadDLCs.Text = vpos + "===" + txt.Length+ "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                        if (versionFile.Length <= 0) Is_Original = "Yes";
                                        else Is_Original = "No";
                                        //rtxt_StatisticsOnReadDLCs.Text = Is_Original + "===" + versionFile.Length+ "\n" + rtxt_StatisticsOnReadDLCs.Text;

                                        //Get Version from FileName
                                        var import_path = ds.Tables[0].Rows[i].ItemArray[1].ToString();
                                        var original_FileName = ds.Tables[0].Rows[i].ItemArray[2].ToString();
                                        string txt = original_FileName;

                                        int vpos = (txt.IndexOf("_v")) + 2;
                                        //if (vpos == 0) vpos = (txt.IndexOf("-v")) + 1;
                                        //if (vpos == 0) vpos = (txt.IndexOf(" v")) + 1;
                                        //if (vpos == 0) vpos = (txt.IndexOf(".v")) + 1;
                                        string major = "";
                                        string minor = "";

                                        if (info.PackageVersion.Length > 2) if (info.PackageVersion.Substring(info.PackageVersion.Length - 2, 2) == ".0") info.PackageVersion = info.PackageVersion.Substring(0, info.PackageVersion.Length - 2);

                                        if (txt.Substring(vpos, 1).ToInt32() >= 0 && vpos > 5)
                                        {
                                            major = txt.Substring(vpos, 1);

                                            var ends = txt.Substring(vpos, txt.Length - vpos).Replace("-", "").Replace("_", "").Replace(".", "").Replace(" ", "");
                                            for (var hh = 1; hh < ends.Length; hh++)
                                            {
                                                if (ends.Substring(hh, 1).ToInt32() >= 0)
                                                {
                                                    minor += ends.Substring(hh, 1);
                                                }
                                                else hh = ends.Length;
                                            }
                                            string ver = major + (minor != "" ? "." : "") + minor;

                                            if (ver.Length > 2) if (ver.Substring(ver.Length - 2, 2) == ".0") ver = ver.Substring(0, ver.Length - 2);
                                            if (Convert.ToSingle(info.PackageVersion) < Convert.ToSingle(ver)) info.PackageVersion = ver;
                                        }
                                        //rtxt_StatisticsOnReadDLCs.Text = "=___" + vv + "---" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                        //foreach (var infofile in versionFile)
                                        //{
                                        //    rtxt_StatisticsOnReadDLCs.Text += "\n last verrsfi " + infofile;
                                        //    tkversion += infofile;
                                        //}

                                        //example of properly working with sql
                                        // Command to Insert Records
                                        //OleDbCommand cmdInsert = new OleDbCommand();
                                        //cmdInsert.CommandText = "INSERT INTO AutoIncrementTest (Description) VALUES (?)";
                                        //cmdInsert.Connection = cnJetDB;
                                        //cmdInsert.Parameters.Add(new OleDbParameter("Description", OleDbType.VarChar, 40, "Description"));
                                        //oleDa.InsertCommand = cmdInsert;

                                        //rtxt_StatisticsOnReadDLCs.Text = info.AlbumArtPath+"---" + "\n" + rtxt_StatisticsOnReadDLCs.Text;

                                        //Set appID
                                        if (chbx_Additional_Manipulations.GetItemChecked(43)) AppIdD = ConfigRepository.Instance()["general_defaultappid_RS2014"];
                                        else AppIdD = info.AppId;

                                        //Set MultiTrack absed on FileName
                                        //No Bass
                                        //No Lead
                                        //No Rhythm
                                        //No Drums
                                        //No Vocal
                                        //(No Guitars)
                                        //Only Bass
                                        //Only Lead
                                        //Only Rhythm
                                        //Only Drums
                                        //Only Vocal
                                        //(Only BackTrack)
                                        string origFN = ds.Tables[0].Rows[i].ItemArray[2].ToString().ToLower();
                                        if (origFN.IndexOf("noguitar") > 0 || origFN.IndexOf("no guitar") > 0 || origFN.IndexOf("no_guitar") > 0 || origFN.IndexOf("no-guitar") > 0)
                                        {
                                            Is_MultiTrack = "Yes"; MultiTrack_Version = "(No Guitars)";
                                        }
                                        if (origFN.IndexOf("noband") > 0 || origFN.IndexOf("no band") > 0 || origFN.IndexOf("no_band") > 0 || origFN.IndexOf("no-band") > 0)
                                        {
                                            Is_MultiTrack = "Yes"; MultiTrack_Version = "(Only Guitars)";
                                        }
                                        if (origFN.IndexOf("nobass") > 0 || origFN.IndexOf("no bass") > 0 || origFN.IndexOf("no_bass") > 0 || origFN.IndexOf("no-bass") > 0)
                                        {
                                            Is_MultiTrack = "Yes"; MultiTrack_Version = "No Bass";
                                        }
                                        if (origFN.IndexOf("nolead") > 0 || origFN.IndexOf("no lead") > 0 || origFN.IndexOf("no_lead") > 0 || origFN.IndexOf("no-lead") > 0)
                                        {
                                            Is_MultiTrack = "Yes"; MultiTrack_Version = "No Lead";
                                        }
                                        if (origFN.IndexOf("norhythm") > 0 || origFN.IndexOf("no rhythm") > 0 || origFN.IndexOf("no_rhythm") > 0 || origFN.IndexOf("no-rhythm") > 0)
                                        {
                                            Is_MultiTrack = "Yes"; MultiTrack_Version = "No Rhythm";
                                        }
                                        if (origFN.IndexOf("novocals") > 0 || origFN.IndexOf("no vocals") > 0 || origFN.IndexOf("no_vocals") > 0 || origFN.IndexOf("no-vocals") > 0)
                                        {
                                            Is_MultiTrack = "Yes"; MultiTrack_Version = "No Vocal";
                                        }
                                        if (origFN.IndexOf("backingonly") > 0 || origFN.IndexOf("backing only") > 0 || origFN.IndexOf("backing_only") > 0 || origFN.IndexOf("backing-only") > 0)
                                        {
                                            Is_MultiTrack = "Yes"; MultiTrack_Version = "(Only BackTrack)";
                                        }

                                        if (Is_MultiTrack == "Yes") rtxt_StatisticsOnReadDLCs.Text = "Multitrack=-=" + MultiTrack_Version + "\n" + rtxt_StatisticsOnReadDLCs.Text;

                                        //Generating the HASH code
                                        art_hash = "";
                                        string audio_hash = "";
                                        string audioPreview_hash = "";
                                        AlbumArtPath = info.AlbumArtPath;
                                        string ss = "";
                                        try
                                        {
                                            using (FileStream fs = File.OpenRead(AlbumArtPath))
                                            {
                                                SHA1 sha = new SHA1Managed();
                                                art_hash = BitConverter.ToString(sha.ComputeHash(fs));//MessageBox.Show(FileHash+"-"+ss);
                                                                                                      //convert to png
                                                ExternalApps.Dds2Png(AlbumArtPath);
                                                fs.Close();
                                            }
                                            //rtxt_StatisticsOnReadDLCs.Text = "hashes: " + ss + " - " + audio_hash + " - " + audioPreview_hash + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                            ss = info.OggPath;
                                            using (FileStream fs = File.OpenRead(ss))
                                            {
                                                SHA1 sha = new SHA1Managed();
                                                audio_hash = BitConverter.ToString(sha.ComputeHash(fs));
                                                fs.Close();
                                            }

                                            ss = info.OggPreviewPath;
                                            //rtxt_StatisticsOnReadDLCs.Text = "rhashes: " + rtxt_StatisticsOnReadDLCs.Text;
                                            if (ss != null)
                                                using (FileStream fs = File.OpenRead(ss))
                                                {
                                                    SHA1 sha = new SHA1Managed();
                                                    audioPreview_hash = BitConverter.ToString(sha.ComputeHash(fs));
                                                    fs.Close();
                                                }
                                            //rtxt_StatisticsOnReadDLCs.Text = "6" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                        }
                                        catch (Exception ex)
                                        {
                                            // MessageBox.Show(ex.Message, MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                            // MessageBox.Show("Error decompressing the file!(BACH OFFICIAL DLC CAUSE OF WEIRD CHAR IN FILENAME) " + "-" );
                                            rtxt_StatisticsOnReadDLCs.Text = ex.Message + ss + "problem at hash" + "..." + rtxt_StatisticsOnReadDLCs.Text;
                                            errr = false;
                                        }
                                        //rtxt_StatisticsOnReadDLCs.Text = "rhashes: " + art_hash + " - " + audio_hash + " - " + audioPreview_hash + "\n" + rtxt_StatisticsOnReadDLCs.Text;

                                        //Check if CDLC have already been imported (hash key)
                                        // 1. If hash already exists do not insert
                                        // 2. If hash does not exists then:
                                        // 2.1.1 If Artist+Album+Title or dlcname exists check author. If same check version
                                        // 2.1.1.1 If (Artist+Album+Title or dlcname)+author the same check version If bigger add
                                        // 2.1.1.2 If (Artist+Album+Title or dlcname)+author the same check version If smaller ignore
                                        // 2.1.1.3 If (Artist+Album+Title or dlcname)+author the same check version If same ?
                                        // 3.1.2 If (Artist+Album+Title or dlcname) exists check author. If the not the same add as alternate
                                        // 4.1.3 If (Artist+Album+Title or dlcname) exists check author. If empty/generic(Custom Song Creator) show statistics and add as give choice to alternate or ignore
                                        //SELECT if the same artist, album, songname
                                        var sel = "SELECT * FROM Main WHERE LCASE(Artist)=LCASE(\"" + info.SongInfo.Artist + "\") AND "; //AND LCASE(Album)=LCASE(\"" + info.SongInfo.Album + "\")
                                        sel += "(LCASE(Song_Title) = LCASE(\"" + info.SongInfo.SongDisplayName + "\") ";
                                        sel += "OR LCASE(Song_Title) like \"%" + info.SongInfo.SongDisplayName.ToLower() + "%\" ";
                                        //sel += "OR (\"%LCASE(Song_Title)%\" like LCASE(\"" + info.SongInfo.SongDisplayName + "\") ";
                                        sel += "OR LCASE(Song_Title_Sort) =LCASE(\"" + info.SongInfo.SongDisplayNameSort + "\")) OR LCASE(DLC_Name)=LCASE(\"" + info.Name + "\") ORDER BY Is_Original ASC";
                                        //Read from DB
                                        int norows = 0;
                                        norows = SQLAccess(sel);
                                        //rtxt_StatisticsOnReadDLCs.Text = "assesing " + norows  + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                        //MessageBox.Show("Chose: 1.Update\n2. Alternate\n3. Ignore", MESSAGEBOX_CAPTION, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                                        var b = 0;
                                        var artist = "Insert";
                                        string jk = ""; string k = "";
                                        var IDD = "";
                                        var folder_name = "";
                                        var filename = "";
                                        bool newold = chbx_Additional_Manipulations.GetItemChecked(32);
                                        Random random = new Random();
                                        //info.Name = Name;
                                        //info.SongInfo.SongDisplayName =  info.SongInfo.SongDisplayName;
                                        if (norows > 0)
                                            foreach (var file in files)
                                            {
                                                SongDisplayName = "";
                                                Namee = "";
                                                //rtxt_StatisticsOnReadDLCs.Text = "\n ------"+ file.Folder_Name.ToString() + "------ " + b + " ------"+ file.Current_FileName.ToString() + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                if (b >= norows) break;
                                                folder_name = file.Folder_Name;
                                                filename = file.Current_FileName;
                                                //rtxt_StatisticsOnReadDLCs.Text =file.Author.ToLower() +"-"+author.ToLower() + "\n" + rtxt_StatisticsOnReadDLCs.Text;

                                                //When importing a original when there is already a similar CDLC
                                                if (author == "" && tkversion == "" && chbx_Additional_Manipulations.GetItemChecked(14))
                                                {
                                                    artist = "Insert";

                                                    //Generate MAX Alternate NO
                                                    var sel1 = sel.Replace("SELECT *", "SELECT max(Alternate_Version_No)");
                                                    sel1 = sel1.Replace(" ORDER BY Is_Original ASC", "");
                                                    //rtxt_StatisticsOnReadDLCs.Text = sel1 + "-" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                    DataSet ddzv = new DataSet();
                                                    OleDbDataAdapter dat = new OleDbDataAdapter(sel1, cnn);
                                                    dat.Fill(ddzv, "Main");
                                                    dat.Dispose();

                                                    //UPDATE the 1(s) not an alternate already
                                                    int max = ddzv.Tables[0].Rows[0].ItemArray[0].ToString().ToInt32() + 1;
                                                    var sel2 = "Update Main Set Song_Title = Song_Title+\" a." + max + "\", Song_Title_Sort = Song_Title_Sort+\" a." + max + "\", Is_Alternate = \"Yes\", Alternate_Version_No=" + max + " where ID in (" + sel.Replace("*", "ID") + ") and Is_Alternate=\"No\"";
                                                    //rtxt_StatisticsOnReadDLCs.Text = max.ToString()+"-"+sel2 + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                    DataSet dxr = new DataSet();
                                                    OleDbDataAdapter dax = new OleDbDataAdapter(sel2, cnn);
                                                    dax.Fill(dxr, "Main");
                                                    dax.Dispose();

                                                    //Add also a random DLCName if any of the Alternates has the same DLC Name ssame as the original
                                                    var sel3 = "UPDATE Main SET DLC_Name = DLC_Name+\"" + random.Next(0, 100000) + "\" WHERE ID in (" + sel.Replace("*", "ID") + ") and LCASE(DLC_Name) = \"" + info.Name.ToLower() + "\"";
                                                    //rtxt_StatisticsOnReadDLCs.Text =  random.Next(0, 100000) + "-"+sel3 + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                    DataSet dxf = new DataSet();
                                                    OleDbDataAdapter dbx = new OleDbDataAdapter(sel3, cnn);
                                                    dbx.Fill(dxf, "Main");
                                                    dbx.Dispose();
                                                    break;
                                                }

                                                //calculate the alternative no (in case is needed)
                                                var altver = "";
                                                try
                                                {
                                                    //using (OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DB_Path))
                                                    //{
                                                    //var sel = "";
                                                    sel = "SELECT max(Alternate_Version_No) FROM Main WHERE(LCASE(Artist) =LCASE(\"" + info.SongInfo.Artist + "\") AND LCASE(Album)=LCASE(\"" + info.SongInfo.Album + "\") AND ";
                                                    sel += "(LCASE(Song_Title)=LCASE(\"" + info.SongInfo.SongDisplayName + "\") OR ";
                                                    sel += "LCASE(Song_Title) like \"%" + info.SongInfo.SongDisplayName.ToLower() + "%\" OR ";
                                                    sel += "LCASE(Song_Title_Sort) =LCASE(\"" + info.SongInfo.SongDisplayNameSort + "\"))) OR LCASE(DLC_Name)=LCASE(\"" + info.Name + "\");";
                                                    //Get last inserted ID
                                                    //rtxt_StatisticsOnReadDLCs.Text = sel + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                    DataSet dds = new DataSet();
                                                    OleDbDataAdapter dda = new OleDbDataAdapter(sel, cnn);
                                                    dda.Fill(dds, "Main");
                                                    dda.Dispose();

                                                    var altvert = dds.Tables[0].Rows[0].ItemArray[0].ToString().ToInt32() == -1 ? 0 : dds.Tables[0].Rows[0].ItemArray[0].ToString().ToInt32();
                                                    if (Is_Original == "No") altver = (altvert + 1).ToString(); //file.Alternate_Version_No//Add Alternative_Version_No
                                                                                                                //rtxt_StatisticsOnReadDLCs.Text = alt + "\n" + rtxt_StatisticsOnReadDLCs.Text;

                                                    //}
                                                }
                                                catch (System.IO.FileNotFoundException ee)
                                                {
                                                    // To inform the user and continue is
                                                    // sufficient for this demonstration.
                                                    // Your application may require different behavior.
                                                    Console.WriteLine(ee.Message);
                                                    rtxt_StatisticsOnReadDLCs.Text = "error at altver calc \n" + rtxt_StatisticsOnReadDLCs.Text;
                                                    //continue;
                                                }
                                                //if (Is_Original == "No") Alternate_No = (GetAlternateNo().ToInt32() + 1).ToString();
                                                var fsz = ds.Tables[0].Rows[i].ItemArray[4].ToString();
                                                //Namee = "";
                                                //SongDisplayName = "";
                                                Title_Sort = "";
                                                ArtistSort = "";
                                                Artist = "";
                                                Is_Alternate = "";
                                                Alternate_No = "";
                                                Album = "";
                                                PackageVersion = "";

                                                if ((author.ToLower() == file.Author.ToLower() && author != "" && file.Author != "" && file.Author != "Custom Song Creator" && author != "Custom Song Creator") || (file.DLC_Name == info.Name))
                                                {
                                                    if (file.DLC_Name.ToLower() == info.Name.ToLower())
                                                        if (chbx_Additional_Manipulations.GetItemChecked(50) && j == 0)
                                                        {
                                                            dupliSongs[i] = 1; duplit = true; break;
                                                        }
                                                        else artist = AssessConflict(file, info, author, tkversion, DD, Bass, Guitar, Combo, Rhythm, Lead, Vocalss, Tunings, b, norows, original_FileName, art_hash, audio_hash, audioPreview_hash, alist, blist, DB_Path, clist, dlist, newold, Is_Original, altver, fsz, unpackedDir, Is_MultiTrack, MultiTrack_Version);
                                                    else
                                                    {
                                                        if (file.Version.ToInt32() > info.PackageVersion.ToInt32()) artist = "Update";
                                                        if (file.Version.ToInt32() < info.PackageVersion.ToInt32())
                                                            if (file.Is_Alternate != "Yes") { artist = "Ignore"; rtxt_StatisticsOnReadDLCs.Text = "IGNORED" + "\n" + rtxt_StatisticsOnReadDLCs.Text; }
                                                            else if (chbx_Additional_Manipulations.GetItemChecked(50) && j == 0)
                                                            {
                                                                dupliSongs[i] = 1; duplit = true; break;
                                                            }
                                                            else artist = AssessConflict(file, info, author, tkversion, DD, Bass, Guitar, Combo, Rhythm, Lead, Vocalss, Tunings, b, norows, original_FileName, art_hash, audio_hash, audioPreview_hash, alist, blist, DB_Path, clist, dlist, newold, Is_Original, altver, fsz, unpackedDir, Is_MultiTrack, MultiTrack_Version);
                                                        if (file.Version.ToInt32() == info.PackageVersion.ToInt32())
                                                            if (chbx_Additional_Manipulations.GetItemChecked(50) && j == 0)
                                                            {
                                                                dupliSongs[i] = 1; duplit = true; break;
                                                            }
                                                            else artist = AssessConflict(file, info, author, tkversion, DD, Bass, Guitar, Combo, Rhythm, Lead, Vocalss, Tunings, b, norows, original_FileName, art_hash, audio_hash, audioPreview_hash, alist, blist, DB_Path, clist, dlist, newold, Is_Original, altver, fsz, unpackedDir, Is_MultiTrack, MultiTrack_Version);
                                                        else { artist = "Ignore"; rtxt_StatisticsOnReadDLCs.Text = "IGNORED" + "\n" + rtxt_StatisticsOnReadDLCs.Text; }
                                                        // assess=alternate, update or ignore//as maybe a new package(ing) is desired to be inserted in the DB
                                                    }
                                                }
                                                else
                                                    if (author.ToLower() != file.Author.ToLower() && (author != "" && author != "Custom Song Creator" && file.Author != "Custom Song Creator" && file.Author != ""))
                                                    artist = "Alternate";
                                                else if (chbx_Additional_Manipulations.GetItemChecked(50) && j == 0)
                                                {
                                                    dupliSongs[i] = 1; duplit = true; break;
                                                }
                                                else artist = AssessConflict(file, info, author, tkversion, DD, Bass, Guitar, Combo, Rhythm, Lead, Vocalss, Tunings, b, norows, original_FileName, art_hash, audio_hash, audioPreview_hash, alist, blist, DB_Path, clist, dlist, newold, Is_Original, altver, fsz, unpackedDir, Is_MultiTrack, MultiTrack_Version);
                                                //rtxt_StatisticsOnReadDLCs.Text = "7 "+b + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                //Exit condition

                                                if (artist == "Alternate")
                                                {
                                                    alt = "1";
                                                    //txt = (info.PackageVersion != null ? "No" : "Yes");
                                                    //rtxt_StatisticsOnReadDLCs.Text = "\n" + "-" + "\n-" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                    if (Namee != "") info.Name = Namee;
                                                    if (SongDisplayName != "") info.SongInfo.SongDisplayName = SongDisplayName;
                                                    if (Title_Sort != "") info.SongInfo.SongDisplayNameSort = Title_Sort;
                                                    if (ArtistSort != "") info.SongInfo.ArtistSort = ArtistSort;
                                                    if (Artist != "") info.SongInfo.Artist = Artist;
                                                    //?
                                                    if (Is_Alternate != "" && Is_Original == "No") alt = Alternate_No;
                                                    if (Alternate_No != "" && Is_Original == "No") alt = Alternate_No;
                                                    //end?
                                                    if (Album != "") info.SongInfo.Album = Album;
                                                    if (PackageVersion != "") info.PackageVersion = PackageVersion;
                                                    //if (AlbumArtPath != "") info.Name = Name;
                                                    //if (art_hash != "") info.Name = Name;
                                                    //if (txt == "No") info.PackageVersion = null;
                                                    //rtxt_StatisticsOnReadDLCs.Text = "\n"+"-"+ (PackageVersion != "" && info.PackageVersion != null ? "No" : "Yes") + "\n-"+ info.PackageVersion + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                    artist = "Insert";

                                                    //Get the higgest Alternate Number
                                                    //sel = "SELECT max(Alternate_Version_No) FROM Main WHERE(LCASE(Artist) =LCASE(\"" + info.SongInfo.Artist + "\") AND LCASE(Album)=LCASE(\"" + info.SongInfo.Album + "\") AND ";
                                                    //sel += "(LCASE(Song_Title)=LCASE(\"" + info.SongInfo.SongDisplayName + "\") OR ";
                                                    //sel += "LCASE(Song_Title) like \"%" + info.SongInfo.SongDisplayName.ToLower() + "%\" OR ";
                                                    //sel += "LCASE(Song_Title_Sort) =LCASE(\"" + info.SongInfo.SongDisplayNameSort + "\"))) OR LCASE(DLC_Name)=LCASE(\"" + info.Name + "\");";
                                                    ////Get last inserted ID
                                                    ////rtxt_StatisticsOnReadDLCs.Text = sel + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                    //DataSet dsr = new DataSet();
                                                    //OleDbDataAdapter dad = new OleDbDataAdapter(sel, cnn);
                                                    //dad.Fill(dsr, "Main");
                                                    //dad.Dispose();
                                                    //string altver = "";
                                                    //foreach (DataRow dataRow in dsr.Tables[0].Rows)
                                                    //{
                                                    //    altver = dataRow.ItemArray[0].ToString();

                                                    //if (Is_Original == "No" && Alternate_No == "") alt = "99";// Alternate_No; //Add Alternative_Version_No
                                                    //WHAT HAPPENED HERE

                                                    //    //rtxt_StatisticsOnReadDLCs.Text = alt + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                    //}

                                                    if (file.DLC_Name.ToLower() == info.Name.ToLower()) info.Name = random.Next(0, 100000) + info.Name;
                                                    if (file.Song_Title.ToLower() == info.SongInfo.SongDisplayName.ToLower() && Is_Original == "No") info.SongInfo.SongDisplayName += " a." + (alt.ToInt32() + 1).ToString() + ((author == null || author == "Custom Song Creator") ? "" : " " + author);// ;//random.Next(0, 100000).ToString()
                                                                                                                                                                                                                                                                                                         //if (file.Song_Title_Sort == info.SongInfo.SongDisplayNameSort) info.SongInfo.SongDisplayNameSort += random.Next(0, 100000);

                                                    // rtxt_StatisticsOnReadDLCs.Text = "highest " + altver + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                }

                                                //if (artist != "Ignore")
                                                //{
                                                //    b ++;
                                                //rtxt_StatisticsOnReadDLCs.Text = txt_RocksmithDLCPath.Text + "\\" + original_FileName + " ccccc\n"+ dupli_Path_Import + "\\" + original_FileName + rtxt_StatisticsOnReadDLCs.Text;

                                                //} //exit if an update/alternate=insert was triggered..autom or by choice(asses)
                                                //else
                                                b++;
                                                //rtxt_StatisticsOnReadDLCs.Text =  "\\" + original_FileName + rtxt_StatisticsOnReadDLCs.Text;
                                                IDD = file.ID; //Save Id in case of update or asses-update
                                                               //rtxt_StatisticsOnReadDLCs.Text = "\\" + original_FileName + rtxt_StatisticsOnReadDLCs.Text;
                                                jk = file.Version;
                                                //rtxt_StatisticsOnReadDLCs.Text = "dd" + original_FileName + rtxt_StatisticsOnReadDLCs.Text;
                                                k = file.Author;
                                                if (b >= norows || artist != "Insert" || IgnoreRest) break;
                                            }
                                        //rtxt_StatisticsOnReadDLCs.Text = "6" + original_FileName + rtxt_StatisticsOnReadDLCs.Text;

                                        if (duplit) ;
                                        else
                                        {
                                            //Move file New file to duplicates Ignore is selet
                                            if (artist == "Ignore" && chbx_Additional_Manipulations.GetItemChecked(29))//30. When NOT importing a duplicate Move it to _duplicate
                                            {
                                                //rtxt_StatisticsOnReadDLCs.Text = dupli_Path_Import + "\\" + original_FileName + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                if (!File.Exists(dupli_Path_Import + "\\" + original_FileName))
                                                {
                                                    Available_Duplicate = "Yes";
                                                    try
                                                    {
                                                        File.Move(txt_RocksmithDLCPath.Text + "\\" + original_FileName, dupli_Path_Import + "\\" + original_FileName);
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        MessageBox.Show(ex.Message, MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                        MessageBox.Show("Issues when moving to duplicate folder" + "-" + ex.Message + filename);
                                                    }
                                                }
                                                else File.Delete(txt_RocksmithDLCPath.Text + "\\" + original_FileName);

                                            }

                                            //Move file Original file to duplicates if Main DB record is being overitten
                                            if (artist == "Update" && chbx_Additional_Manipulations.GetItemChecked(29))//30. When NOT importing a duplicate Move it to _duplicate
                                            {
                                                sel = "SELECT Original_FileName FROM Main WHERE ID=" + IDD + ";";
                                                DataSet dzr = new DataSet();
                                                OleDbDataAdapter dad = new OleDbDataAdapter(sel, cnn);
                                                dad.Fill(dzr, "Main");
                                                dad.Dispose();
                                                //rtxt_StatisticsOnReadDLCs.Text = dupli_Path_Import + "\\" + original_FileName + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                var Original_FileName = dzr.Tables[0].Rows[0].ItemArray[0].ToString();
                                                if (!File.Exists(dupli_Path_Import + "\\" + Original_FileName))
                                                {
                                                    if (!File.Exists(txt_TempPath.Text + "\\0_old\\" + Original_FileName))
                                                    {
                                                        Available_Duplicate = "Yes";
                                                        try
                                                        {
                                                            File.Move(txt_TempPath.Text + "\\0_old\\" + Original_FileName, dupli_Path_Import + "\\" + Original_FileName);
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            MessageBox.Show(ex.Message, MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                            MessageBox.Show("Issues when moving to duplicate folder" + "-" + ex.Message + filename);
                                                        }
                                                    }
                                                }
                                                else File.Delete(txt_RocksmithDLCPath.Text + "\\" + Original_FileName);

                                            }

                                            //var platformdlc = "";
                                            //var Has_Track_No = "";

                                            //Set Preview
                                            if (chbx_Additional_Manipulations.GetItemChecked(34) && (info.OggPreviewPath == null))
                                            {
                                                rtxt_StatisticsOnReadDLCs.Text = "Trying to add preview as missing.\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                var startInfo = new ProcessStartInfo();
                                                startInfo.FileName = Path.Combine(AppWD, "oggcut.exe");
                                                startInfo.WorkingDirectory = AppWD;// Path.GetDirectoryName();
                                                var t = info.OggPath.Replace(".wem", "_fixed.ogg"); ;//"C:\\GitHub\\tmp\\0\\0_dlcpacks\\rs1compatibilitydisc_PS3\\audio\\ps3\\149627248.ogg";//txt_TempPath.Text + "\\0_dlcpacks\\rs1compatibilitydlc.psarc";
                                                var tt = t.Replace(".ogg", "_preview.ogg");
                                                var times = "00:30";
                                                string[] timepieces = times.Split(':');
                                                TimeSpan r = new TimeSpan(0, timepieces[0].ToInt32(), timepieces[1].ToInt32());
                                                startInfo.Arguments = String.Format(" -i \"{0}\" -o \"{1}\" -s \"{2}\" -e \"{3}\"",
                                                                                    t,
                                                                                    tt,
                                                                                    r.TotalMilliseconds,
                                                                                    (r.TotalMilliseconds + (30 * 1000)));
                                                startInfo.UseShellExecute = true; startInfo.CreateNoWindow = true; //startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true;

                                                if (File.Exists(t))
                                                    using (var DDC = new Process())
                                                    {
                                                        DDC.StartInfo = startInfo; DDC.Start(); DDC.WaitForExit(1000 * 60 * 1); //wait 1min
                                                        if (DDC.ExitCode == 0)
                                                        {
                                                            MainDB.Converters(tt, MainDB.ConverterTypes.Ogg2Wem, false);
                                                            info.OggPreviewPath = tt;
                                                            //2info.= tt.Replace();

                                                            if (File.Exists(tt))
                                                                using (FileStream fss = File.OpenRead(tt))
                                                                {
                                                                    SHA1 sha = new SHA1Managed();
                                                                    audioPreview_hash = BitConverter.ToString(sha.ComputeHash(fss));
                                                                    fss.Close();
                                                                }
                                                            PreviewTime = "00:30";
                                                            PreviewLenght = "30";
                                                        }

                                                    }
                                            }

                                            //Define final path for the imported song
                                            //rtxt_StatisticsOnReadDLCs.Text = info.PackageVersion + " ccccc\n" + rtxt_StatisticsOnReadDLCs.Text;
                                            var norm_path = txt_TempPath.Text + "\\" + (Is_Original == "Yes" ? "ORIG" : "CDLC") + "_" + info.SongInfo.Artist + "_" + info.SongInfo.SongYear + "_" + info.SongInfo.Album + "_" + info.SongInfo.SongDisplayName;
                                            //if (artist == "ignore") ;

                                            //@Provider=Microsoft.ACE.OLEDB.12.0;Data Source=
                                            connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DB_Path); //+ ";Persist Security Info=False"
                                            command = connection.CreateCommand();
                                            //rtxt_StatisticsOnReadDLCs.Text = "00 " + original_FileName + rtxt_StatisticsOnReadDLCs.Text;
                                            if (artist == "Update")
                                            {
                                                //Update MainDB
                                                rtxt_StatisticsOnReadDLCs.Text = "Updating / Overriting " + IDD + "-" + j + "-" + info.PackageVersion + "-" + k + ".." + rtxt_StatisticsOnReadDLCs.Text;

                                                //SqlCommand cmds = new SqlCommand(sqlCmd, conn2);
                                                command.CommandText = "UPDATE Main SET ";
                                                command.CommandText += "Import_Path = @param1, ";
                                                command.CommandText += "Original_FileName = @param2, ";
                                                command.CommandText += "Current_FileName = @param3, ";
                                                command.CommandText += "File_Hash = @param4, ";
                                                command.CommandText += "Original_File_Hash = @param5, ";
                                                command.CommandText += "File_Size = @param6, ";
                                                command.CommandText += "Import_Date = @param7, ";
                                                command.CommandText += "Folder_Name = @param8, ";
                                                command.CommandText += "Song_Title = @param9, ";
                                                command.CommandText += "Song_Title_Sort = @param10, ";
                                                command.CommandText += "Album = @param11, ";
                                                command.CommandText += "Artist = @param12, ";
                                                command.CommandText += "Artist_Sort = @param13, ";
                                                command.CommandText += "Album_Year = @param14, ";
                                                command.CommandText += "Version = @param15, ";
                                                command.CommandText += "AverageTempo = @param16, ";
                                                command.CommandText += "Volume = @param17, ";
                                                command.CommandText += "Preview_Volume = @param18, ";
                                                command.CommandText += "DLC_Name = @param19, ";
                                                command.CommandText += "DLC_AppID = @param20, ";
                                                command.CommandText += "AlbumArtPath = @param21, ";
                                                command.CommandText += "AudioPath = @param22, ";
                                                command.CommandText += "audioPreviewPath = @param23, ";
                                                command.CommandText += "Has_Bass = @param24, ";
                                                command.CommandText += "Has_Guitar = @param25, ";
                                                command.CommandText += "Has_Lead = @param26, ";
                                                command.CommandText += "Has_Rhythm = @param27, ";
                                                command.CommandText += "Has_Combo = @param28, ";
                                                command.CommandText += "Has_Vocals = @param29, ";
                                                command.CommandText += "Has_Sections = @param30, ";
                                                command.CommandText += "Has_Cover = @param31, ";
                                                command.CommandText += "Has_Preview = @param32, ";
                                                command.CommandText += "Has_Custom_Tone = @param33, ";
                                                command.CommandText += "Has_DD = @param34, ";
                                                command.CommandText += "Has_Version = @param35, ";
                                                command.CommandText += "Has_Author = @param36, ";
                                                command.CommandText += "Tunning = @param37, ";
                                                command.CommandText += "Bass_Picking = @param38, ";
                                                command.CommandText += "DLC = @param39, ";
                                                command.CommandText += "SignatureType = @param40, ";
                                                command.CommandText += "Author = @param41, ";
                                                command.CommandText += "ToolkitVersion = @param42, ";
                                                command.CommandText += "Is_Original = @param43, ";
                                                command.CommandText += "Is_Alternate = @param44, ";
                                                command.CommandText += "Alternate_Version_No = @param45, ";
                                                command.CommandText += "AlbumArt_Hash = @param46, ";
                                                command.CommandText += "Audio_Hash = @param47, ";
                                                command.CommandText += "audioPreview_Hash = @param48, ";
                                                command.CommandText += "Bass_Has_DD = @param49, ";
                                                command.CommandText += "Has_Bonus_Arrangement = @param50, ";
                                                command.CommandText += "Available_Duplicate = @param51, ";
                                                command.CommandText += "Available_Old = @param52, ";
                                                command.CommandText += "Description = @param53, ";
                                                command.CommandText += "Comments = @param54, ";
                                                command.CommandText += "OggPath = @param55, ";
                                                command.CommandText += "OggPreviewPath = @param56, ";
                                                command.CommandText += "Has_Track_No = @param57, ";
                                                command.CommandText += "Track_No = @param58, ";
                                                command.CommandText += "Platform = @param59, ";
                                                command.CommandText += "Is_Multitrack = @param60, ";
                                                command.CommandText += "MultiTrack_Version = @param61, ";
                                                command.CommandText += "YouTube_Link = @param62, ";
                                                command.CommandText += "CustomsForge_Link = @param63, ";
                                                command.CommandText += "CustomsForge_Like = @param64, ";
                                                command.CommandText += "CustomsForge_ReleaseNotes = @param65, ";
                                                command.CommandText += "PreviewTime = @param66, ";
                                                command.CommandText += "PreviewLenght = @param67 ";
                                                command.CommandText += "WHERE ID = " + IDD;

                                                command.Parameters.AddWithValue("@param1", import_path);
                                                command.Parameters.AddWithValue("@param2", original_FileName);
                                                command.Parameters.AddWithValue("@param3", original_FileName);
                                                command.Parameters.AddWithValue("@param4", ds.Tables[0].Rows[i].ItemArray[3].ToString());
                                                command.Parameters.AddWithValue("@param5", ds.Tables[0].Rows[i].ItemArray[3].ToString());
                                                command.Parameters.AddWithValue("@param6", ds.Tables[0].Rows[i].ItemArray[4].ToString());
                                                command.Parameters.AddWithValue("@param7", ds.Tables[0].Rows[i].ItemArray[5].ToString());
                                                command.Parameters.AddWithValue("@param8", unpackedDir);
                                                command.Parameters.AddWithValue("@param9", info.SongInfo.SongDisplayName);
                                                command.Parameters.AddWithValue("@param10", info.SongInfo.SongDisplayNameSort);
                                                command.Parameters.AddWithValue("@param11", info.SongInfo.Album);
                                                command.Parameters.AddWithValue("@param12", info.SongInfo.Artist);
                                                command.Parameters.AddWithValue("@param13", info.SongInfo.ArtistSort);
                                                command.Parameters.AddWithValue("@param14", info.SongInfo.SongYear);
                                                command.Parameters.AddWithValue("@param15", ((info.PackageVersion == null) ? "1" : info.PackageVersion));
                                                command.Parameters.AddWithValue("@param16", info.SongInfo.AverageTempo);
                                                command.Parameters.AddWithValue("@param17", info.Volume);
                                                command.Parameters.AddWithValue("@param18", info.PreviewVolume);
                                                command.Parameters.AddWithValue("@param19", info.Name);
                                                command.Parameters.AddWithValue("@param20", AppIdD);
                                                command.Parameters.AddWithValue("@param21", info.AlbumArtPath ?? DBNull.Value.ToString());
                                                command.Parameters.AddWithValue("@param22", info.OggPath);
                                                command.Parameters.AddWithValue("@param23", info.OggPreviewPath ?? DBNull.Value.ToString());
                                                command.Parameters.AddWithValue("@param24", Bass);
                                                command.Parameters.AddWithValue("@param25", Guitar);
                                                command.Parameters.AddWithValue("@param26", ((Lead != "") ? Lead : "No"));
                                                command.Parameters.AddWithValue("@param27", ((Rhythm != "") ? Rhythm : "No"));
                                                command.Parameters.AddWithValue("@param28", ((Combo != "") ? Combo : "No"));
                                                command.Parameters.AddWithValue("@param29", ((Vocalss != "") ? Vocalss : "No"));
                                                command.Parameters.AddWithValue("@param30", sect1on);
                                                command.Parameters.AddWithValue("@param31", ((info.AlbumArtPath != "") ? "Yes" : "No"));
                                                command.Parameters.AddWithValue("@param32", ((info.OggPreviewPath != null) ? "Yes" : "No"));
                                                command.Parameters.AddWithValue("@param33", Tones_Custom);
                                                command.Parameters.AddWithValue("@param34", DD);
                                                command.Parameters.AddWithValue("@param35", ((info.PackageVersion != null && tkversion != "" && Is_Original == "No") ? "Yes" : "No"));
                                                command.Parameters.AddWithValue("@param36", Has_author);//((((author != "" && tkversion != "") || author == "Custom Song Creator") && Is_Original == "No") ? "Yes" : "No"));
                                                command.Parameters.AddWithValue("@param37", Tunings);
                                                command.Parameters.AddWithValue("@param38", PluckedType);
                                                command.Parameters.AddWithValue("@param39", ((Is_Original == "Yes") ? "ORIG" : "CDLC"));
                                                command.Parameters.AddWithValue("@param40", info.SignatureType);
                                                command.Parameters.AddWithValue("@param41", ((author != "") ? author : (tkversion != "" ? "Custom Song Creator" : "")));
                                                command.Parameters.AddWithValue("@param42", tkversion);
                                                command.Parameters.AddWithValue("@param43", Is_Original);
                                                command.Parameters.AddWithValue("@param44", ((alt == "" || alt == null) ? "No" : "Yes"));
                                                command.Parameters.AddWithValue("@param45", alt);
                                                command.Parameters.AddWithValue("@param46", art_hash);
                                                command.Parameters.AddWithValue("@param47", audio_hash);
                                                command.Parameters.AddWithValue("@param48", audioPreview_hash);
                                                command.Parameters.AddWithValue("@param49", Bass_Has_DD ?? DBNull.Value.ToString());
                                                command.Parameters.AddWithValue("@param50", bonus ?? DBNull.Value.ToString());
                                                command.Parameters.AddWithValue("@param51", Available_Duplicate ?? DBNull.Value.ToString());
                                                command.Parameters.AddWithValue("@param52", Available_Old ?? DBNull.Value.ToString());
                                                command.Parameters.AddWithValue("@param53", description ?? DBNull.Value.ToString());
                                                command.Parameters.AddWithValue("@param54", comment ?? DBNull.Value.ToString());
                                                command.Parameters.AddWithValue("@param55", info.OggPath.Replace(".wem", "_fixed.ogg"));
                                                command.Parameters.AddWithValue("@param56", (info.OggPreviewPath == null ? DBNull.Value.ToString() : info.OggPreviewPath.Replace(".wem", "_fixed.ogg")));
                                                command.Parameters.AddWithValue("@param57", (trackno == 0 ? "No" : "Yes"));
                                                command.Parameters.AddWithValue("@param58", trackno.ToString());
                                                command.Parameters.AddWithValue("@param59", packagePlatform.platform);
                                                command.Parameters.AddWithValue("@param60", Is_MultiTrack);
                                                command.Parameters.AddWithValue("@param61", MultiTrack_Version);
                                                command.Parameters.AddWithValue("@param62", YouTube_Link);
                                                command.Parameters.AddWithValue("@param63", CustomsForge_Link);
                                                command.Parameters.AddWithValue("@param64", CustomsForge_Like);
                                                command.Parameters.AddWithValue("@param65", CustomsForge_ReleaseNotes);
                                                command.Parameters.AddWithValue("@param66", PreviewTime ?? DBNull.Value.ToString());
                                                command.Parameters.AddWithValue("@param67", PreviewLenght ?? DBNull.Value.ToString());
                                                //EXECUTE SQL/INSERT
                                                try
                                                {
                                                    command.CommandType = CommandType.Text;
                                                    connection.Open();
                                                    command.ExecuteNonQuery();
                                                    //Deleted old folder
                                                    Directory.Delete(folder_name, true);
                                                    ////remove original dir TO DO
                                                    //Directory.Delete(source_dir, true);
                                                    //move old/aleady imported&saved file
                                                    if (chbx_Additional_Manipulations.GetItemChecked(29))//30. When NOT importing a duplicate Move it to _duplicate
                                                    {
                                                        rtxt_StatisticsOnReadDLCs.Text = old_Path_Import + "\\" + filename + "dupli_Path_Import arrangement:" + dupli_Path_Import + "\\" + filename + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                        try
                                                        {
                                                            if (!File.Exists(dupli_Path_Import + "\\" + filename))
                                                                if (File.Exists(old_Path_Import + "\\" + filename))
                                                                {
                                                                    File.Move(old_Path_Import + "\\" + filename, dupli_Path_Import + "\\" + filename);
                                                                    Available_Duplicate = "Yes";
                                                                }
                                                                else rtxt_StatisticsOnReadDLCs.Text = "___" + rtxt_StatisticsOnReadDLCs.Text;
                                                            else
                                                            {
                                                                File.Delete(txt_RocksmithDLCPath.Text + "\\" + filename);
                                                                Available_Duplicate = "Yes";
                                                            }
                                                            rtxt_StatisticsOnReadDLCs.Text = "deleting...dele...\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            MessageBox.Show(ex.Message, MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                            MessageBox.Show("Issues at duplicate folder" + "-" + ex.Message + filename);
                                                        }
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    MessageBox.Show(ex.Message, MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                    MessageBox.Show("Can not open Arrangements DB connection in Import ! " + DB_Path + "-" + original_FileName + "-" + command.CommandText);

                                                    //throw;
                                                }
                                                finally
                                                {
                                                    if (connection != null) connection.Close();
                                                }
                                            }

                                            //Read Track no
                                            //www.metrolyrics.com: Nirvana Bleach Swap Meet
                                            if (ExistingTrackNo != "")
                                            {
                                                trackno = ExistingTrackNo.ToInt32();
                                                //HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&es_th=1&ie=UTF-8#q=www.metrolyrics.com:" + info.SongInfo.Artist + info.SongInfo.Album + info.SongInfo.SongDisplayName.Replace(" ", "+"));
                                                //request.Proxy = WebProxy.GetDefaultProxy();
                                                //request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
                                            }
                                            //else

                                            //rtxt_StatisticsOnReadDLCs.Text = Available_Duplicate + "==" + Available_Old + rtxt_StatisticsOnReadDLCs.Text;
                                            if (artist == "Insert")
                                            {
                                                //Update by INSERT into Main DB+info.AlbumArtPath+"____________"
                                                rtxt_StatisticsOnReadDLCs.Text = "Inserting " + "..." + rtxt_StatisticsOnReadDLCs.Text;
                                                //connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+DB_Path+";Persist Security Info=False");
                                                //command = connection.CreateCommand();
                                                //SqlCommand cmds = new SqlCommand(sqlCmd, conn2);
                                                command.CommandText = "INSERT INTO Main(";
                                                command.CommandText += "Import_Path, ";//1-ds.Tables[0].Rows[i].ItemArray[1].ToString()
                                                command.CommandText += "Original_FileName, ";//2-ds.Tables[0].Rows[i].ItemArray[2].ToString()
                                                command.CommandText += "Current_FileName, ";//3-ds.Tables[0].Rows[i].ItemArray[2].ToString()
                                                command.CommandText += "File_Hash, ";//4-ds.Tables[0].Rows[i].ItemArray[3].ToString()
                                                command.CommandText += "Original_File_Hash, ";//5-ds.Tables[0].Rows[i].ItemArray[3].ToString()
                                                command.CommandText += "File_Size, ";//6-ds.Tables[0].Rows[i].ItemArray[4].ToString()
                                                command.CommandText += "Import_Date, ";//7-ds.Tables[0].Rows[i].ItemArray[5].ToString()
                                                command.CommandText += "Folder_Name, ";//8-unpackedDir
                                                command.CommandText += "Song_Title, ";//9-info.SongInfo.SongDisplayName
                                                command.CommandText += "Song_Title_Sort, ";//10-info.SongInfo.SongDisplayNameSort
                                                command.CommandText += "Album, ";//11-info.SongInfo.Album
                                                command.CommandText += "Artist, ";//12-info.SongInfo.Artist
                                                command.CommandText += "Artist_Sort, ";//13-info.SongInfo.ArtistSort
                                                command.CommandText += "Album_Year, ";//14-info.SongInfo.SongYear
                                                command.CommandText += "Version, ";//15-((info.PackageVersion == null) ? "1" : info.PackageVersion)
                                                command.CommandText += "AverageTempo, ";//16-info.SongInfo.AverageTempo
                                                command.CommandText += "Volume, ";//17-info.Volume
                                                command.CommandText += "Preview_Volume, ";//18-info.PreviewVolume
                                                command.CommandText += "DLC_Name, ";//19-info.Name
                                                command.CommandText += "DLC_AppID, ";//20-info.AppId
                                                command.CommandText += "AlbumArtPath, ";//21-info.AlbumArtPath
                                                command.CommandText += "AudioPath, ";//22-info.OggPath
                                                command.CommandText += "audioPreviewPath, ";//23-info.OggPreviewPath
                                                command.CommandText += "Has_Bass, ";//24-Bass
                                                command.CommandText += "Has_Guitar, ";//25-Guitar
                                                command.CommandText += "Has_Lead, ";//26-((Lead != "") ? Lead : "No")
                                                command.CommandText += "Has_Rhythm, ";//27-((Rhythm != "") ? Rhythm : "No")
                                                command.CommandText += "Has_Combo, ";//28-((Combo != "") ? Combo : "No")
                                                command.CommandText += "Has_Vocals, ";//29-((Vocals != "") ? Vocals : "No")
                                                command.CommandText += "Has_Sections, ";//30-"sect1on"
                                                command.CommandText += "Has_Cover, ";//31-((info.AlbumArtPath != null) ? "Yes" : "No")
                                                command.CommandText += "Has_Preview, ";//32-((info.OggPreviewPath != null) ? "Yes" : "No")
                                                command.CommandText += "Has_Custom_Tone, ";//33-Tones_Custom
                                                command.CommandText += "Has_DD, ";//34-DD
                                                command.CommandText += "Has_Version, ";//35-((info.PackageVersion != "" && tkversion != "") ? "Yes" : "No")
                                                command.CommandText += "Has_Author, ";//36-((author != "" && tkversion != "") ? "Yes" : "No")
                                                command.CommandText += "Tunning, ";//37-Tunings
                                                command.CommandText += "Bass_Picking, ";//38-PluckedType
                                                command.CommandText += "DLC, ";//39-((info.PackageVersion == null) ? "Original" : "CDLC")
                                                command.CommandText += "SignatureType, ";//40-info.SignatureType
                                                command.CommandText += "Author, ";//41-((author != "") ? author : (tkversion != "" ? "Custom Song Creator" : ""))
                                                command.CommandText += "ToolkitVersion, ";//42-tkversion
                                                command.CommandText += "Is_Original, ";//43-tkversion
                                                command.CommandText += "Is_Alternate, ";//43-tkversion
                                                command.CommandText += "Alternate_Version_No, ";//44-alt
                                                command.CommandText += "AlbumArt_Hash, ";
                                                command.CommandText += "Audio_Hash, ";
                                                command.CommandText += "audioPreview_Hash, ";
                                                command.CommandText += "Bass_Has_DD, ";
                                                command.CommandText += "Has_Bonus_Arrangement, ";
                                                command.CommandText += "Available_Duplicate, ";
                                                command.CommandText += "Available_Old, ";
                                                command.CommandText += "Description, ";
                                                command.CommandText += "Comments, ";
                                                command.CommandText += "OggPath, ";
                                                command.CommandText += "OggPreviewPath, ";
                                                command.CommandText += "Has_Track_No, ";
                                                command.CommandText += "Track_No, ";
                                                command.CommandText += "Platform, ";
                                                command.CommandText += "Is_Multitrack, ";
                                                command.CommandText += "MultiTrack_Version, ";
                                                command.CommandText += "YouTube_Link, ";
                                                command.CommandText += "CustomsForge_Link, ";
                                                command.CommandText += "CustomsForge_Like, ";
                                                command.CommandText += "CustomsForge_ReleaseNotes, ";
                                                command.CommandText += "PreviewTime, ";
                                                command.CommandText += "PreviewLenght ";
                                                command.CommandText += ") VALUES (@param1,@param2,@param3,@param4,@param5,@param6,@param7,@param8,@param9";
                                                command.CommandText += ",@param10,@param11,@param12,@param13,@param14,@param15,@param16,@param17,@param18,@param19";
                                                command.CommandText += ",@param20,@param21,@param22,@param23,@param24,@param25,@param26,@param27,@param28,@param29";
                                                command.CommandText += ",@param30,@param31,@param32,@param33,@param34,@param35,@param36,@param37,@param38,@param39";
                                                command.CommandText += ",@param40,@param41,@param42,@param43,@param44,@param45,@param46,@param47,@param48,@param49";
                                                command.CommandText += ",@param50,@param51,@param52,@param53,@param54,@param55,@param56,@param57,@param58,@param59";
                                                command.CommandText += ",@param60,@param61,@param62,@param63,@param64,@param65,@param66,@param67" + ")"; //,@param44,@param45,@param46,@param47,@param48,@param49
                                                                                                                                                         //command.CommandText += ") VALUES(@param50,@param51,@param52" + ")"; //,@param33,@param44,@param44,@param45,@param46,@param47,@param48,@param49

                                                command.Parameters.AddWithValue("@param1", import_path);
                                                command.Parameters.AddWithValue("@param2", original_FileName);
                                                command.Parameters.AddWithValue("@param3", original_FileName);
                                                command.Parameters.AddWithValue("@param4", ds.Tables[0].Rows[i].ItemArray[3]);
                                                command.Parameters.AddWithValue("@param5", ds.Tables[0].Rows[i].ItemArray[3]);
                                                command.Parameters.AddWithValue("@param6", ds.Tables[0].Rows[i].ItemArray[4]);
                                                command.Parameters.AddWithValue("@param7", ds.Tables[0].Rows[i].ItemArray[5]);
                                                command.Parameters.AddWithValue("@param8", unpackedDir);
                                                command.Parameters.AddWithValue("@param9", info.SongInfo.SongDisplayName);
                                                command.Parameters.AddWithValue("@param10", info.SongInfo.SongDisplayNameSort);
                                                command.Parameters.AddWithValue("@param11", info.SongInfo.Album);
                                                command.Parameters.AddWithValue("@param12", info.SongInfo.Artist);
                                                command.Parameters.AddWithValue("@param13", info.SongInfo.ArtistSort);
                                                command.Parameters.AddWithValue("@param14", info.SongInfo.SongYear);
                                                command.Parameters.AddWithValue("@param15", ((info.PackageVersion == null) ? "1" : info.PackageVersion));
                                                command.Parameters.AddWithValue("@param16", info.SongInfo.AverageTempo);
                                                command.Parameters.AddWithValue("@param17", info.Volume);
                                                command.Parameters.AddWithValue("@param18", info.PreviewVolume);
                                                command.Parameters.AddWithValue("@param19", info.Name);
                                                command.Parameters.AddWithValue("@param20", AppIdD);
                                                command.Parameters.AddWithValue("@param21", info.AlbumArtPath ?? DBNull.Value.ToString());
                                                command.Parameters.AddWithValue("@param22", info.OggPath);
                                                command.Parameters.AddWithValue("@param23", (info.OggPreviewPath ?? DBNull.Value.ToString()));// ((info.OggPreviewPath == "") ? DBNull.Value : info.OggPreviewPath));
                                                command.Parameters.AddWithValue("@param24", Bass);
                                                command.Parameters.AddWithValue("@param25", Guitar);
                                                command.Parameters.AddWithValue("@param26", ((Lead != "") ? Lead : "No"));
                                                command.Parameters.AddWithValue("@param27", ((Rhythm != "") ? Rhythm : "No"));
                                                command.Parameters.AddWithValue("@param28", ((Combo != "") ? Combo : "No"));
                                                command.Parameters.AddWithValue("@param29", ((Vocalss != "") ? Vocalss : "No"));
                                                command.Parameters.AddWithValue("@param30", sect1on);
                                                command.Parameters.AddWithValue("@param31", ((info.AlbumArtPath != "") ? "Yes" : "No"));
                                                command.Parameters.AddWithValue("@param32", ((info.OggPreviewPath != null) ? "Yes" : "No"));
                                                command.Parameters.AddWithValue("@param33", Tones_Custom);
                                                command.Parameters.AddWithValue("@param34", DD);
                                                command.Parameters.AddWithValue("@param35", ((info.PackageVersion != null && tkversion != "" && Is_Original == "No") ? "Yes" : "No"));
                                                command.Parameters.AddWithValue("@param36", Has_author);//((((author != "" && tkversion != "") || author == "Custom Song Creator") && Is_Original == "No") ? "Yes" : "No"));
                                                command.Parameters.AddWithValue("@param37", Tunings);
                                                command.Parameters.AddWithValue("@param38", PluckedType);
                                                command.Parameters.AddWithValue("@param39", ((Is_Original == "Yes") ? "ORIG" : "CDLC"));
                                                command.Parameters.AddWithValue("@param40", info.SignatureType);
                                                command.Parameters.AddWithValue("@param41", ((author != "") ? author : (tkversion != "" ? "Custom Song Creator" : "")));
                                                command.Parameters.AddWithValue("@param42", tkversion);
                                                command.Parameters.AddWithValue("@param43", Is_Original);
                                                command.Parameters.AddWithValue("@param44", ((alt == "" || alt == null) ? "No" : "Yes"));
                                                command.Parameters.AddWithValue("@param45", alt ?? DBNull.Value.ToString());
                                                command.Parameters.AddWithValue("@param46", art_hash);
                                                command.Parameters.AddWithValue("@param47", audio_hash);
                                                command.Parameters.AddWithValue("@param48", audioPreview_hash);
                                                command.Parameters.AddWithValue("@param49", Bass_Has_DD);
                                                command.Parameters.AddWithValue("@param50", bonus);
                                                command.Parameters.AddWithValue("@param51", Available_Duplicate);
                                                command.Parameters.AddWithValue("@param52", Available_Old);
                                                command.Parameters.AddWithValue("@param53", description);
                                                command.Parameters.AddWithValue("@param54", comment);
                                                command.Parameters.AddWithValue("@param55", info.OggPath.Replace(".wem", "_fixed.ogg"));
                                                command.Parameters.AddWithValue("@param56", (info.OggPreviewPath == null ? DBNull.Value.ToString() : info.OggPreviewPath.Replace(".wem", "_fixed.ogg")));
                                                command.Parameters.AddWithValue("@param57", (trackno == 0 ? "No" : "Yes"));
                                                command.Parameters.AddWithValue("@param58", trackno.ToString());
                                                command.Parameters.AddWithValue("@param59", packagePlatform.platform.ToString());
                                                command.Parameters.AddWithValue("@param60", Is_MultiTrack);
                                                command.Parameters.AddWithValue("@param61", MultiTrack_Version);
                                                command.Parameters.AddWithValue("@param62", YouTube_Link);
                                                command.Parameters.AddWithValue("@param63", CustomsForge_Link);
                                                command.Parameters.AddWithValue("@param64", CustomsForge_Like);
                                                command.Parameters.AddWithValue("@param65", CustomsForge_ReleaseNotes);
                                                command.Parameters.AddWithValue("@param66", PreviewTime ?? DBNull.Value.ToString());
                                                command.Parameters.AddWithValue("@param67", PreviewLenght ?? DBNull.Value.ToString());
                                                //EXECUTE SQL/INSERT
                                                try
                                                {
                                                    command.CommandType = CommandType.Text;
                                                    connection.Open();
                                                    command.ExecuteNonQuery();
                                                }
                                                catch (Exception)
                                                {
                                                    rtxt_StatisticsOnReadDLCs.Text = "error at update" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                    throw;
                                                }
                                                finally
                                                {
                                                    if (connection != null) connection.Close();
                                                }
                                                //If No version found then defaulted to 1
                                                //TO DO If default album cover then mark it as suck !?
                                                //If no version found must by Rocksmith Original or DLC

                                                rtxt_StatisticsOnReadDLCs.Text = "Records inserted in Main= " + (i + 1) + "..." + rtxt_StatisticsOnReadDLCs.Text;
                                            }
                                            //rtxt_StatisticsOnReadDLCs.Text = artist + "...||..." + rtxt_StatisticsOnReadDLCs.Text;
                                            if (artist == "Insert" || artist == "Update") //Common set of action for all
                                            {
                                                //Get last inserted ID
                                                DataSet dus = new DataSet();
                                                OleDbDataAdapter dad = new OleDbDataAdapter("SELECT ID FROM Main WHERE File_Hash=\"" + ds.Tables[0].Rows[i].ItemArray[3].ToString() + "\"", cnn);
                                                dad.Fill(dus, "Main");
                                                dad.Dispose();
                                                //rtxt_StatisticsOnReadDLCs.Text ="last id= " + dus.Tables[0].Rows[0].ItemArray[0].ToString() + "..." + rtxt_StatisticsOnReadDLCs.Text;

                                                //OleDbDataAdapter objAdapter = new OleDbDataAdapter("SELECT @@IDENTITY AS 'ID';", cnn);

                                                //Useful
                                                // Get and Store IDENTITY (Primary Key) for further
                                                // INSERTS in child table [Order Details]
                                                //cmd.CommandText = "SELECT @@identity";
                                                //string id = cmd.ExecuteScalar().ToString();
                                                //objAdapter.Fill(dus, "Main");
                                                //string strID = dus.Tables["Main"].Rows[0].ToString();

                                                //UPDATE ArarngementsDB
                                                var CDLC_ID = dus.Tables[0].Rows[0].ItemArray[0].ToString();
                                                connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DB_Path); //+ ";Persist Security Info=False"
                                                int n = 0;
                                                foreach (var arg in info.Arrangements)//, Type
                                                {
                                                    command = connection.CreateCommand();
                                                    //ss = arg.SongXml.File.ToString();
                                                    //string XMLFile_hash="";
                                                    //using (FileStream fs = File.OpenRead(ss))
                                                    //{
                                                    //    SHA1 sha = new SHA1Managed();
                                                    //    XMLFile_hash = BitConverter.ToString(sha.ComputeHash(fs));
                                                    //}

                                                    try
                                                    {
                                                        var mss = arg.SongXml.File.ToString();
                                                        int poss = 0;
                                                        if (mss.Length > 0)
                                                        {
                                                            poss = mss.ToString().LastIndexOf("\\") + 1;
                                                            //rtxt_StatisticsOnReadDLCs.Text = norm_path+"__________" + arg.SongFile.File + "...\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                            if (chbx_Additional_Manipulations.GetItemChecked(36)) //37. Keep the Uncompressed Songs superorganized
                                                            {
                                                                arg.SongXml.File = norm_path + "\\EOF\\" + mss.Substring(poss);
                                                                arg.SongFile.File = norm_path + "\\Toolkit\\" + (mss.Substring(poss)).Replace(".xml", ".json");
                                                            }
                                                            else
                                                            {
                                                                arg.SongXml.File = norm_path + "\\songs\\arr\\" + mss.Substring(poss);
                                                                arg.SongFile.File = arg.SongXml.File.Replace(".xml", ".json").Replace("\\songs\\arr", "\\" + calc_path(Directory.GetFiles(unpackedDir, "*.json", SearchOption.AllDirectories)[0]));
                                                            }
                                                        }

                                                        command.CommandText = "INSERT INTO Arrangements(";
                                                        command.CommandText += "CDLC_ID, ";
                                                        command.CommandText += "Arrangement_Name, ";
                                                        command.CommandText += "Tunning, ";
                                                        command.CommandText += "SNGFilePath, ";
                                                        command.CommandText += "SNGFileName, ";
                                                        command.CommandText += "SNGFileLLID, ";
                                                        command.CommandText += "SNGFileUUID, ";
                                                        command.CommandText += "XMLFilePath, ";
                                                        command.CommandText += "XMLFileName, ";
                                                        command.CommandText += "XMLFileLLID, ";
                                                        command.CommandText += "XMLFileUUID, ";
                                                        command.CommandText += "ArrangementSort, ";
                                                        command.CommandText += "TuningPitch, ";
                                                        command.CommandText += "ScrollSpeed, ";
                                                        command.CommandText += "Bonus, ";
                                                        command.CommandText += "ToneBase, ";
                                                        command.CommandText += "ToneMultiplayer, ";
                                                        command.CommandText += "ToneA, ";
                                                        command.CommandText += "ToneB, ";
                                                        command.CommandText += "ToneC, ";
                                                        command.CommandText += "ToneD, ";
                                                        command.CommandText += "Idd, ";
                                                        command.CommandText += "MasterId, ";
                                                        command.CommandText += "ArrangementType, ";
                                                        command.CommandText += "String0, ";
                                                        command.CommandText += "String1, ";
                                                        command.CommandText += "String2, ";
                                                        command.CommandText += "String3, ";
                                                        command.CommandText += "String4, ";
                                                        command.CommandText += "String5, ";
                                                        command.CommandText += "PluckedType, ";
                                                        command.CommandText += "RouteMask,";
                                                        command.CommandText += "XMLFile_Hash,";
                                                        command.CommandText += "SNGFileHash,";
                                                        command.CommandText += "lastConversionDateTime,";
                                                        command.CommandText += "Has_Sections";
                                                        command.CommandText += ") VALUES(@param1,@param2,@param3,@param4,@param5,@param6,@param7,@param8,@param9";
                                                        command.CommandText += ",@param10,@param11,@param12,@param13,@param14,@param15,@param16,@param17,@param18,@param19";
                                                        command.CommandText += ",@param20,@param21,@param22,@param23,@param24,@param25,@param26,@param27,@param28,@param29";
                                                        command.CommandText += ",@param30,@param31,@param32,@param33,@param34,@param35,@param36";
                                                        command.CommandText += ")";
                                                        command.Parameters.AddWithValue("@param1", CDLC_ID);
                                                        command.Parameters.AddWithValue("@param2", arg.Name);
                                                        command.Parameters.AddWithValue("@param3", arg.Tuning ?? DBNull.Value.ToString());
                                                        command.Parameters.AddWithValue("@param4", (arg.SongFile.File ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param5", (arg.SongFile.Name ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param6", (arg.SongFile.LLID.ToString() ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param7", (arg.SongFile.UUID.ToString() ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param8", (arg.SongXml.File ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param9", (arg.SongXml.Name ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param10", (arg.SongXml.LLID.ToString() ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param11", (arg.SongXml.UUID.ToString() ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param12", (arg.ArrangementSort.ToString() ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param13", (arg.TuningPitch.ToString() ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param14", (arg.ScrollSpeed.ToString() ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param15", (arg.BonusArr.ToString() ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param16", (arg.ToneBase ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param17", (arg.ToneMultiplayer ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param18", (arg.ToneA ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param19", (arg.ToneB ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param20", (arg.ToneC ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param21", (arg.ToneD ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param22", (arg.Id.ToString() ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param23", (arg.MasterId.ToString() ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param24", (arg.ArrangementType.ToString() ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param25", (arg.TuningStrings == null ? "" : arg.TuningStrings.String0.ToString()));
                                                        command.Parameters.AddWithValue("@param26", (arg.TuningStrings == null ? "" : arg.TuningStrings.String1.ToString()));
                                                        command.Parameters.AddWithValue("@param27", (arg.TuningStrings == null ? "" : arg.TuningStrings.String2.ToString()));
                                                        command.Parameters.AddWithValue("@param28", (arg.TuningStrings == null ? "" : arg.TuningStrings.String3.ToString()));
                                                        command.Parameters.AddWithValue("@param29", (arg.TuningStrings == null ? "" : arg.TuningStrings.String4.ToString()));
                                                        command.Parameters.AddWithValue("@param30", (arg.TuningStrings == null ? "" : arg.TuningStrings.String5.ToString()));
                                                        command.Parameters.AddWithValue("@param31", (arg.PluckedType.ToString() ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param32", (arg.RouteMask.ToString() ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param33", (alist[n].ToString() ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param34", (blist[n].ToString() ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param35", (clist[n].ToString() ?? DBNull.Value.ToString()));
                                                        command.Parameters.AddWithValue("@param36", (dlist[n].ToString() ?? DBNull.Value.ToString()));
                                                        n++;

                                                        //EXECUTE SQL/INSERT
                                                        try
                                                        {
                                                            command.CommandType = CommandType.Text;
                                                            connection.Open();
                                                            command.ExecuteNonQuery();
                                                        }
                                                        catch (Exception)
                                                        {
                                                            rtxt_StatisticsOnReadDLCs.Text = "error at insert " + command.CommandText + "\n" + arg.Name + rtxt_StatisticsOnReadDLCs.Text;
                                                            throw;
                                                        }
                                                        finally
                                                        {
                                                            if (connection != null) connection.Close();
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        MessageBox.Show(ex.Message, MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                        MessageBox.Show("Can not open Arrangements DB connection in Import ! " + DB_Path + "-" + arg.Name + "-" + command.CommandText);
                                                    }
                                                }
                                                rtxt_StatisticsOnReadDLCs.Text = "Arrangements Updated " + info.Arrangements.Count + "...\n" + rtxt_StatisticsOnReadDLCs.Text;

                                                //UPDATE TonesDB
                                                CDLC_ID = dus.Tables[0].Rows[0].ItemArray[0].ToString();
                                                connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DB_Path); //+ ";Persist Security Info=False"
                                                foreach (var tn in info.TonesRS2014)//, Type
                                                {
                                                    command = connection.CreateCommand();
                                                    try
                                                    {
                                                        command.CommandText = "INSERT INTO Tones(";
                                                        command.CommandText += "CDLC_ID, ";
                                                        command.CommandText += "Tone_Name, ";
                                                        command.CommandText += "Is_Custom, ";
                                                        command.CommandText += "SortOrder, ";
                                                        command.CommandText += "Volume, ";
                                                        command.CommandText += "Keyy, ";
                                                        command.CommandText += "NameSeparator, ";
                                                        command.CommandText += "AmpType, ";
                                                        command.CommandText += "AmpCategory, ";
                                                        //command.CommandText += "AmpKnobValues, ";
                                                        command.CommandText += "AmpPedalKey, ";
                                                        command.CommandText += "CabinetCategory, ";
                                                        //command.CommandText += "CabinetKnobValues, ";
                                                        command.CommandText += "CabinetPedalKey, ";
                                                        command.CommandText += "CabinetType, ";
                                                        command.CommandText += "PostPedal1, ";
                                                        command.CommandText += "PostPedal2, ";
                                                        command.CommandText += "PostPedal3, ";
                                                        command.CommandText += "PostPedal4, ";
                                                        command.CommandText += "PrePedal1, ";
                                                        command.CommandText += "PrePedal2, ";
                                                        command.CommandText += "PrePedal3, ";
                                                        command.CommandText += "PrePedal4, ";
                                                        command.CommandText += "Rack1, ";
                                                        command.CommandText += "Rack2, ";
                                                        command.CommandText += "Rack3, ";
                                                        command.CommandText += "Rack4";
                                                        command.CommandText += ") VALUES(@param1, @param2, @param3, @param4, @param5, @param6, @param7, @param8, @param9";//,@param10
                                                        command.CommandText += ",@param11,@param12,@param14,@param15,@param16,@param17,@param18,@param19";//;,@param13
                                                                                                                                                          //rtxt_StatisticsOnReadDLCs.Text = "1: " + tn.Name +"\n"+ rtxt_StatisticsOnReadDLCs.Text;
                                                                                                                                                          //rtxt_StatisticsOnReadDLCs.Text = "2: " + (tn.GearList.Amp== null ? "" : tn.GearList.Amp.Type) +"\n"+ rtxt_StatisticsOnReadDLCs.Text;
                                                                                                                                                          //rtxt_StatisticsOnReadDLCs.Text = "3: " + (tn.GearList.Amp== null ? "" : tn.GearList.Amp.KnobValues["1"]) + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                                                                                                                          //rtxt_StatisticsOnReadDLCs.Text = "4: " + (tn.GearList.Amp== null ? "" : tn.GearList.Amp.PedalKey)+"\n"+rtxt_StatisticsOnReadDLCs.Text;
                                                        command.CommandText += ",@param20,@param21,@param22,@param23,@param24,@param25,@param26,@param27";
                                                        command.CommandText += ")";
                                                        command.Parameters.AddWithValue("@param1", NullHandler(CDLC_ID));
                                                        command.Parameters.AddWithValue("@param2", NullHandler(tn.Name));
                                                        command.Parameters.AddWithValue("@param3", NullHandler(tn.IsCustom));
                                                        command.Parameters.AddWithValue("@param4", NullHandler(tn.SortOrder));
                                                        command.Parameters.AddWithValue("@param5", NullHandler(tn.Volume));
                                                        command.Parameters.AddWithValue("@param6", NullHandler(tn.Key));
                                                        command.Parameters.AddWithValue("@param7", NullHandler(tn.NameSeparator));
                                                        command.Parameters.AddWithValue("@param8", (tn.GearList.Amp == null ? DBNull.Value.ToString() : NullHandler(tn.GearList.Amp.Type)));
                                                        command.Parameters.AddWithValue("@param9", (tn.GearList.Amp == null ? DBNull.Value.ToString() : NullHandler(tn.GearList.Amp.Category)));
                                                        //command.Parameters.AddWithValue("@param10", (tn.GearList.Amp== null ==null ?DBNull.Value.ToString() :NullHandler(tn.GearList.Amp.KnobValues.Values)));
                                                        command.Parameters.AddWithValue("@param11", (tn.GearList.Amp == null ? DBNull.Value.ToString() : NullHandler(tn.GearList.Amp.PedalKey)));
                                                        command.Parameters.AddWithValue("@param12", (tn.GearList.Cabinet == null ? DBNull.Value.ToString() : NullHandler(tn.GearList.Cabinet.Category)));
                                                        //command.Parameters.AddWithValue("@param13", ((tn.GearList.Cabinet == null) ? DBNull.Value.ToString() : NullHandler(tn.GearList.Cabinet.KnobValues)));
                                                        command.Parameters.AddWithValue("@param14", (tn.GearList.Cabinet == null ? DBNull.Value.ToString() : NullHandler(tn.GearList.Cabinet.PedalKey)));
                                                        command.Parameters.AddWithValue("@param15", (tn.GearList.Cabinet == null ? DBNull.Value.ToString() : NullHandler(tn.GearList.Cabinet.Type)));
                                                        command.Parameters.AddWithValue("@param16", NullHandler(tn.GearList.PostPedal1));
                                                        command.Parameters.AddWithValue("@param17", NullHandler(tn.GearList.PostPedal2));
                                                        command.Parameters.AddWithValue("@param18", NullHandler(tn.GearList.PostPedal3));
                                                        command.Parameters.AddWithValue("@param19", NullHandler(tn.GearList.PostPedal4));
                                                        command.Parameters.AddWithValue("@param20", NullHandler(tn.GearList.PrePedal1));
                                                        command.Parameters.AddWithValue("@param21", NullHandler(tn.GearList.PrePedal2));
                                                        command.Parameters.AddWithValue("@param22", NullHandler(tn.GearList.PrePedal3));
                                                        command.Parameters.AddWithValue("@param23", NullHandler(tn.GearList.PrePedal4));
                                                        command.Parameters.AddWithValue("@param24", NullHandler(tn.GearList.Rack1));
                                                        command.Parameters.AddWithValue("@param25", NullHandler(tn.GearList.Rack2));
                                                        command.Parameters.AddWithValue("@param26", NullHandler(tn.GearList.Rack3));
                                                        command.Parameters.AddWithValue("@param27", NullHandler(tn.GearList.Rack4));

                                                        //rtxt_StatisticsOnReadDLCs.Text = command.CommandText + "\n" + tn.Name + rtxt_StatisticsOnReadDLCs.Text;
                                                        //EXECUTE SQL/INSERT
                                                        try
                                                        {
                                                            command.CommandType = CommandType.Text;
                                                            connection.Open();
                                                            command.ExecuteNonQuery();
                                                        }
                                                        catch (Exception)
                                                        {
                                                            rtxt_StatisticsOnReadDLCs.Text = "error in arag" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                            throw;
                                                        }
                                                        finally
                                                        {
                                                            if (connection != null)
                                                            {
                                                                connection.Close();
                                                            }
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        MessageBox.Show(ex.Message, MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                        MessageBox.Show("Can not open Tones DB connection in Import ! " + DB_Path + "-" + tn.Name + "-" + command.CommandText);
                                                    }
                                                }
                                                rtxt_StatisticsOnReadDLCs.Text = "ToneDB Updated " + info.TonesRS2014.Count + "..." + rtxt_StatisticsOnReadDLCs.Text;

                                                //Move Extracted Song to Temp Folder
                                                int pos = 0;
                                                int l = 0;
                                                DataSet dis = new DataSet();
                                                try //Move from _import into Temp folder (copy+delete as move sometimes fails)
                                                {
                                                    //Directory.(unpackedDir, norm_path);
                                                    string source_dir = @unpackedDir;
                                                    string destination_dir = @norm_path;

                                                    // substring is to remove destination_dir absolute path (E:\).

                                                    // Create subdirectory structure in destination
                                                    foreach (string dir in Directory.GetDirectories(source_dir, "*", System.IO.SearchOption.AllDirectories))
                                                    {
                                                        Directory.CreateDirectory(destination_dir + dir.Substring(source_dir.Length));
                                                        // Example:
                                                        //     > C:\sources (and not C:\E:\sources)
                                                    }

                                                    foreach (string file_name in Directory.GetFiles(source_dir, "*.*", System.IO.SearchOption.AllDirectories))
                                                    {
                                                        File.Copy(file_name, destination_dir + file_name.Substring(source_dir.Length), true);
                                                    }
                                                    Directory.Delete(source_dir, true);
                                                    //var ee = "";
                                                    //rtxt_StatisticsOnReadDLCs.Text = " DIR Moved" + "..." + rtxt_StatisticsOnReadDLCs.Text;
                                                }
                                                catch (Exception ee)
                                                {
                                                    rtxt_StatisticsOnReadDLCs.Text = "FAILED3 .." + "\n" + rtxt_StatisticsOnReadDLCs.Text;//ee.Message + "----" +
                                                    Console.WriteLine(ee.Message);
                                                }

                                                if (chbx_Additional_Manipulations.GetItemChecked(15)) //16. Move Original Imported files to temp/0_old
                                                {
                                                    //Move imported psarc into the old folder
                                                    //rtxt_StatisticsOnReadDLCs.Text = "predone" + "..." + rtxt_StatisticsOnReadDLCs.Text;
                                                    try
                                                    {
                                                        // if (!File.Exists(txt_RocksmithDLCPath.Text + "\\" + original_FileName))
                                                        File.Copy(txt_RocksmithDLCPath.Text + "\\" + original_FileName, old_Path_Import + "\\" + original_FileName, true);
                                                        File.Delete(txt_RocksmithDLCPath.Text + "\\" + original_FileName);
                                                        Available_Old = "Yes";
                                                        rtxt_StatisticsOnReadDLCs.Text = "File Moved to old" + "..." + rtxt_StatisticsOnReadDLCs.Text;
                                                    }
                                                    catch (System.IO.FileNotFoundException ee)
                                                    {
                                                        rtxt_StatisticsOnReadDLCs.Text = "FAILED2" + ee.Message + "----" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                        Console.WriteLine(ee.Message);
                                                    }
                                                }

                                                //Fixing any _preview_preview issue..Start
                                                //Correct moved file path audio,preview
                                                //Add wem
                                                //Corrent arrangements file path
                                                cmd = "UPDATE Main SET Available_Old=\"" + Available_Old + "\",";
                                                //var cmdA = "UPDATE Arrangements SET";
                                                //rtxt_StatisticsOnReadDLCs.Text = "0" + "..." + rtxt_StatisticsOnReadDLCs.Text;
                                                var audiopath = "";
                                                var audioprevpath = "";
                                                var ms = "";
                                                ms = info.AlbumArtPath;
                                                var cmd2 = "";
                                                if (ms != "" && ms != null)
                                                {
                                                    //rtxt_StatisticsOnReadDLCs.Text ="\n" +AlbumArtPath +"\n"+ info.AlbumArtPath+"\n000" + ms + "..." + rtxt_StatisticsOnReadDLCs.Text;
                                                    pos = ms.ToString().LastIndexOf("\\") + 1;
                                                    if (AlbumArtPath == info.AlbumArtPath)
                                                        if (chbx_Additional_Manipulations.GetItemChecked(36)) //37. Keep the Uncompressed Songs superorganized
                                                            cmd += " AlbumArtPath=\"" + (info.AlbumArtPath == "" ? "" : norm_path) + "\\Toolkit\\" + ms.Substring(pos) + "\"";
                                                        else
                                                            cmd += " AlbumArtPath=\"" + (info.AlbumArtPath == "" ? "" : norm_path) + "\\gfxassets\\album_art\\" + ms.Substring(pos) + "\"";
                                                    else //Override Album Art during the Duplication assements process
                                                    {
                                                        //rtxt_StatisticsOnReadDLCs.Text = "\nimg override"+ "..." + rtxt_StatisticsOnReadDLCs.Text;
                                                        cmd += " AlbumArt_Hash=\"" + art_hash + "\", AlbumArtPath=\"" + AlbumArtPath + "\"";
                                                    }

                                                    //If Cover was applied to the a original then update its album art
                                                    if (dupliID != "")
                                                    {
                                                        cmd2 = cmd + " WHERE ID=" + dupliID;
                                                        DataSet dhs = new DataSet();
                                                        using (OleDbConnection cBn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DB_Path))
                                                        {// 1. If hash already exists do not insert
                                                            OleDbDataAdapter dBs = new OleDbDataAdapter(cmd2, cBn);
                                                            dBs.Fill(dhs, "Main");
                                                            dBs.Dispose();
                                                            rtxt_StatisticsOnReadDLCs.Text = "Main DB aLBUM updated after DIR Moved&DUPLICATRE REASIG" + "..." + rtxt_StatisticsOnReadDLCs.Text;
                                                        }
                                                    }
                                                }
                                                //rtxt_StatisticsOnReadDLCs.Text = "1" + "..." + rtxt_StatisticsOnReadDLCs.Text;
                                                pos = (info.OggPath.LastIndexOf(".wem"));
                                                ms = info.OggPath;

                                                var path_decom1 = "";
                                                var path_decom2 = "";
                                                if (chbx_Additional_Manipulations.GetItemChecked(36)) //37. Keep the Uncompressed Songs superorganized
                                                {
                                                    path_decom1 = "\\Toolkit\\";
                                                    path_decom2 = "\\EOF\\";
                                                }
                                                else
                                                {
                                                    path_decom1 = "\\audio\\windows\\";
                                                    path_decom2 = "\\audio\\windows\\"; //"\\songs\\arr\\";
                                                }

                                                //Fix _preview.OGG having a diff name than _preview.wem after oggged
                                                var source_dir1 = norm_path + path_decom1;// Path.GetDirectoryName(info.OggPath);
                                                var destination_dir1 = source_dir1;
                                                var previewN = "";
                                                foreach (string preview_name in Directory.GetFiles(source_dir1, "*_preview.wem", System.IO.SearchOption.AllDirectories))
                                                {
                                                    //if (!File.Exists(preview_name.Replace(".wem",".ogg")))
                                                    foreach (string file_name in Directory.GetFiles(source_dir1, "*.ogg", System.IO.SearchOption.AllDirectories))
                                                    {
                                                        if (file_name.Replace("_fixed.ogg", ".ogg") != preview_name.Replace("_preview.wem", ".ogg"))// || file_name.IndexOf("_fixed") == 0)
                                                        {
                                                            previewN = preview_name.Replace(".wem", "_fixed.ogg");
                                                            if (!File.Exists(previewN))
                                                            {
                                                                File.Copy(file_name, previewN, true);
                                                                File.Delete(file_name);
                                                            }
                                                        }
                                                    }
                                                }

                                                //Delete any Wav file created..by....?ccc
                                                foreach (string wav_name in Directory.GetFiles(source_dir1, "*_preview.wav", System.IO.SearchOption.AllDirectories))
                                                {
                                                    File.Delete(wav_name);
                                                }

                                                //Delete any Wav file created..by....?ccc
                                                foreach (string wav_name in Directory.GetFiles(source_dir1, "*_preview.wav", System.IO.SearchOption.AllDirectories))
                                                {
                                                    File.Delete(wav_name);
                                                }

                                                if (ms.Length > 0 && pos > 1)
                                                {
                                                    ms = ms.Substring(0, pos);
                                                    if (info.OggPath.LastIndexOf("_preview.wem") > 1) ms = ms.Substring(0, ms.LastIndexOf("_preview"));
                                                    pos = ms.LastIndexOf("\\") + 1;
                                                    l = ms.Substring(pos).Length;
                                                    audiopath = norm_path + path_decom1 + ms.Substring(pos, l);
                                                    cmd += ((info.AlbumArtPath == "" || info.AlbumArtPath == null) ? "" : " ,") + " AudioPath=\"" + audiopath + ".wem\"";
                                                    cmd += " , OggPath=\"" + norm_path + path_decom2 + ms.Substring(pos, l) + "_fixed.ogg\"";
                                                }
                                                //rtxt_StatisticsOnReadDLCs.Text = "2" +cmd+ "..." + rtxt_StatisticsOnReadDLCs.Text;
                                                pos = (info.OggPath.LastIndexOf(".wem"));
                                                ms = info.OggPath;
                                                if (ms.Length > 0 && pos > 1 && (info.OggPreviewPath != null))
                                                {
                                                    ms = ms.Substring(0, pos);
                                                    if (info.OggPath.LastIndexOf("_preview_preview.wem") > 1) ms = ms.Substring(0, ms.LastIndexOf("_preview_preview"));
                                                    pos = ms.LastIndexOf("\\") + 1;
                                                    l = ms.Substring(pos).Length;
                                                    audioprevpath = norm_path + path_decom1 + ms.Substring(pos, l);
                                                    cmd += " , audioPreviewPath=\"" + audioprevpath + "_preview.wem\"";
                                                    cmd += " , oggPreviewPath=\"" + previewN + "\"";//_preview
                                                }
                                                //rtxt_StatisticsOnReadDLCs.Text = "3" + "..." + rtxt_StatisticsOnReadDLCs.Text;
                                                cmd += " , Folder_Name=\"" + norm_path + "\"";

                                                cmd += " WHERE ID=" + CDLC_ID;
                                                // rtxt_StatisticsOnReadDLCs.Text = "3" + cmd+ "..." + rtxt_StatisticsOnReadDLCs.Text;
                                                using (OleDbConnection cn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DB_Path))
                                                {// 1. If hash already exists do not insert
                                                    OleDbDataAdapter dgs = new OleDbDataAdapter(cmd, cn);
                                                    dgs.Fill(dis, "Main");
                                                    dgs.Dispose();
                                                    rtxt_StatisticsOnReadDLCs.Text = "Main DB updated after DIR Moved" + "..." + rtxt_StatisticsOnReadDLCs.Text;
                                                }
                                                //fix potentially issues with songs with the audio preview WEM  file the same as the original song(file size{no preview})
                                                //Move wem to KIT folder + rename
                                                //var WemFiles = Directory.GetFiles(unpackedDir, "*.wem", SearchOption.AllDirectories);
                                                //if (WemFiles.Count() <= 0)
                                                //    throw new InvalidDataException("Audio files not found.");
                                                if (info.OggPreviewPath != null)
                                                    if (info.OggPreviewPath.LastIndexOf("_preview_preview.wem") > 1)
                                                    {
                                                        try
                                                        {
                                                            File.Move((audiopath + "_preview.wem"), (audiopath + ".wem"));
                                                            File.Move((audioprevpath + "_preview.wem"), (audioprevpath + ".wem"));
                                                            rtxt_StatisticsOnReadDLCs.Text = "Issues w the WEM filenames when no preview " + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                        }
                                                        catch (Exception ee)
                                                        {
                                                            rtxt_StatisticsOnReadDLCs.Text = "FAILED1" + ee.Message + "----" + info.OggPath + "\n -" + audiopath + "\n -" + audioprevpath + ".wem" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                            Console.WriteLine(ee.Message);
                                                        }
                                                    }
                                                //Fixing any _preview_preview issue..End

                                            }
                                            //Updating the Standardization table
                                            try
                                            {
                                                cmd = "SELECT * FROM Standardization WHERE StrComp(Artist,\"" + info.SongInfo.Artist + "\", 0) = 0 AND StrComp(Album,\"" + info.SongInfo.Album + "\", 0) = 0;";
                                                //rtxt_StatisticsOnReadDLCs.Text = "assesing populating normalization" + cmd + "----" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                DataSet dzs = new DataSet();
                                                OleDbDataAdapter dam = new OleDbDataAdapter(cmd, cnn);
                                                dam.Fill(dzs, "Main");
                                                dam.Dispose();
                                                //rtxt_StatisticsOnReadDLCs.Text = "no of rows returned" + dzs.Tables[0].Rows.Count + "----" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                if (dzs.Tables[0].Rows.Count == 0)
                                                {
                                                    cmd = "INSERT INTO Standardization (Artist, Album) VALUES (\"" + info.SongInfo.Artist + "\",\"" + info.SongInfo.Album + "\")";
                                                    //rtxt_StatisticsOnReadDLCs.Text = "populating normalization" + cmd + "----" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                    DataSet dfs = new DataSet();
                                                    OleDbDataAdapter dbm = new OleDbDataAdapter(cmd, cnn);
                                                    dbm.Fill(dfs, "Main");
                                                    dbm.Dispose();
                                                }
                                            }
                                            catch (System.IO.FileNotFoundException ee)
                                            {
                                                rtxt_StatisticsOnReadDLCs.Text = "FAILED2" + ee.Message + "----" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                                Console.WriteLine(ee.Message);
                                            }

                                            rtxt_StatisticsOnReadDLCs.Text = "done" + "..." + rtxt_StatisticsOnReadDLCs.Text;
                                            pB_ReadDLCs.Increment(1);
                                        }
                                    }
                                }
                            }
                    }
                }
            }
            catch (System.IO.FileNotFoundException ee)
            {
                // To inform the user and continue is
                // sufficient for this demonstration.
                // Your application may require different behavior.
                rtxt_StatisticsOnReadDLCs.Text = "Error when importing..somewhere" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                Console.WriteLine(ee.Message);
                //continue;
            }

            //Cleanup
            if (chbx_Additional_Manipulations.GetItemChecked(24)) //25. Use translation tables for naming standardization
            {
                Translation_And_Correction((chbx_DefaultDB.Checked == true ? MyAppWD : txt_DBFolder.Text));
            }

            if (chbx_Additional_Manipulations.GetItemChecked(42)) //43. Save import Log
            {
                // Write the string to a file.
                var fn = MyAppWD + "\\" + GetTimestamps(DateTime.Now).Replace(":", "_") + ".txt";
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(fn, true))//.ToString()
                {
                    file.WriteLine("Full Log");
                    file.WriteLine(rtxt_StatisticsOnReadDLCs.Text);
                    file.Close();
                }
                //string[] lines = {"Full Log"};//rtxt_StatisticsOnReadDLCs.Text};
                //System.IO.File.WriteAllLines(fn+"2", lines);

                rtxt_StatisticsOnReadDLCs.Text = "Log saved" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
            }

            //Show Intro database window
            MainDB frm = new MainDB((chbx_DefaultDB.Checked == true ? MyAppWD : txt_DBFolder.Text), txt_TempPath.Text, chbx_Additional_Manipulations.GetItemChecked(33), txt_RocksmithDLCPath.Text, chbx_Additional_Manipulations.GetItemChecked(39), chbx_Additional_Manipulations.GetItemChecked(40));
            frm.Show();

            //dataGrid.frmMainForm.ActiveForm.Show();
            //MessageBox.Show("f");
        }
        public static string RemoveDD(string Folder_Name, string Is_Original, string xml, Platform platform, bool superOrg, bool InternalLog)
        {
            var Has_BassDD = "No";

            var jsons = "";
            if (superOrg) //37. Keep the Uncompressed Songs superorganized
                jsons = xml.Replace("EOF", "Toolkit").Replace(".xml", ".json");
            else
                jsons = (xml.Replace(".xml", ".json").Replace("songs\\arr", calc_path(Directory.GetFiles(Folder_Name, "*.json", SearchOption.AllDirectories)[0])));

            //Save a copy
            if (!File.Exists(xml + ".old")) File.Copy(xml, xml + ".old", false);
            else File.Copy(xml, xml + ".old", true);
            var json = jsons;
            if (!File.Exists(json + ".old")) File.Copy(json, json + ".old", false);
            else File.Copy(json + ".old", json, true);

            //bcapirtxt_StatisticsOnReadDLCs.Text = "...."+Path.GetFileNameWithoutExtension(xml)+"...Removing DD using DDC tool" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
            var startInfo = new ProcessStartInfo();

            var r = String.Format(" -m \"{0}\"", Path.GetFullPath("ddc\\ddc_dd_remover.xml"));
            var c = String.Format(" -c \"{0}\"", Path.GetFullPath("ddc\\ddc_default.xml"));
            startInfo.FileName = Path.Combine(AppWD, "ddc", "ddc.exe");
            startInfo.WorkingDirectory = Folder_Name;// +jsons;// "\\EOF\\";// Path.GetDirectoryName();
            startInfo.Arguments = String.Format("\"{0}\" -l {1} -s {2}{3}{4}",//{5}
                                                Path.GetFileName(xml),
                                                40, "N", r,// c,
                                                 " -p Y", " -t N"
            );
            //rtxt_StatisticsOnReadDLCs.Text = "working dir: "+ startInfo.WorkingDirectory + "...\n--"+startInfo.FileName+"..." +startInfo.Arguments + "\n\n" + rtxt_StatisticsOnReadDLCs.Text;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            var DDCExitCode = 5;
            using (var DDC = new Process())
            {
                // rtxt_StatisticsOnReadDLCs.Text = "...1" + "\n" + rtxt_StatisticsOnReadDLCs.Text;

                if (!InternalLog)//32. When removing DD use internal logic not DDC
                {
                    DDC.StartInfo = startInfo;
                    DDC.Start();
                    //consoleOutput = DDC.StandardOutput.ReadToEnd();
                    //consoleOutput += DDC.StandardError.ReadToEnd();
                    DDC.WaitForExit(1000 * 60 * 5); //wait 5 minutes
                    //rtxt_StatisticsOnReadDLCs.Text = "HAS BASS=" + file.Has_BassDD + "...DDEXIT CODE: " + DDC.ExitCode + "----+-" + file.Folder_Name + "++++" + platform.version + "___" + RocksmithToolkitLib.GameVersion.RS2014 + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                    //if (DDC.ExitCode > 0 && Is_Original == "No") rtxt_StatisticsOnReadDLCs.Text = "Issues at CDLC Bass DD removal!" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                }
                else DDCExitCode = 5;

                if (Is_Original == "Yes" || DDCExitCode == 5)
                { //http://code.google.com/p/rocksmith-custom-song-creator/issues/detail?id=60
                    //if (platform.version == RocksmithToolkitLib.GameVersion.RS2014)
                    //{
                    //bcapirtxt_StatisticsOnReadDLCs.Text = "...Removing DD from Original using own logic" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                    // xml = Directory.GetFiles(unpackedDir, String.Format("*{0}.json", Path.GetFileNameWithoutExtension(json)), SearchOption.AllDirectories);
                    if (xml.Length > 0)
                    {
                        platform.version = RocksmithToolkitLib.GameVersion.RS2014;
                        Song2014 xmlContent1 = Song2014.LoadFromFile(xml);
                        var manifestFunctions1 = new ManifestFunctions(platform.version);
                        var j = manifestFunctions1.GetMaxDifficulty(xmlContent1);
                        string textfile = File.ReadAllText(xml);

                        //for each timestamp in the xml file take the highest level entry
                        var fxml = File.OpenText(xml);
                        string tecst = "";
                        string line;
                        var header = "";
                        var footer = "";
                        //Read and Save Header
                        while ((line = fxml.ReadLine()) != null)
                        {
                            header += line + "\n";
                            if (line.Contains("<levels>")) break;
                        }
                        //level the maxdiff overall setting in the xml
                        var m = 1;
                        for (m = 1; m <= j; m++)
                        {
                            header = header.Replace("maxDifficulty=\"" + m + "\"", "maxDifficulty=\"0\"");
                        }

                        //rtxt_StatisticsOnReadDLCs.Text = "head done"+ header.Length + "...\n" + rtxt_StatisticsOnReadDLCs.Text;
                        //fxml.Close();

                        //fxml = File.OpenText(xml);
                        var v = 0; //difficulty level in the parsing
                        var diff = 0;
                        float[] timea = new float[10000]; //keeps the timestamp of each note
                        float[] timeb = new float[10000]; //keeps the timestamp of each anchor
                        string[] notes = new string[10000]; // keeps the full note details
                        string[] anchor = new string[10000]; // keeps the full note details
                        int[] lvla = new int[10000]; //keeps the level of the note&timestamp
                        int[] lvlb = new int[10000]; //keeps the level of the note&timestamp
                        //bool is_header = true; //to know when the header has been read and saved
                        //var l = 0; //storage counter in the array
                        float ts = 0; //timestamp parsed fro the <notes line
                        int ea = 0; //top end of the storage array notes
                        int eb = 0; //top end of the storage array anchor
                        bool UpdateT = false;
                        while ((line = fxml.ReadLine()) != null)
                        {
                            //header
                            //if (is_header) header = line + "\n";
                            if (line.Contains("<level difficulty=\""))
                            {
                                line = line.Replace("<level difficulty=\"", "").TrimStart();
                                line = line.Replace("\">", "");
                                try { diff = line.ToInt32(); }
                                catch
                                {
                                    MessageBox.Show("Errors at DD lvl READ removal"); //rtxt_StatisticsOnReadDLCs.Text = "Errors at DD READ removal" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                }
                                if (line != v.ToString())
                                {
                                    MessageBox.Show("Errors at DD removal");
                                    //rtxt_StatisticsOnReadDLCs.Text = "Errors at DD removal" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                    break;
                                }
                                v++;
                                //  is_header = false;
                                //rtxt_StatisticsOnReadDLCs.Text = "level: " + v + "...\n" + rtxt_StatisticsOnReadDLCs.Text;
                                continue;
                            }

                            //notes
                            if (line.Contains("<note time=\""))
                            {
                                tecst = (line.Replace("<note time=\"", "")).TrimStart();// ((line.Replace("<note time=\"", "")).TrimStart).IndexOf("\"\"")));
                                tecst = tecst.Replace(tecst.Substring(tecst.IndexOf("\"")), "");
                                try { ts = Convert.ToSingle(tecst); }
                                catch
                                {
                                    MessageBox.Show("Errors at DD time notes READ removal"); //rtxt_StatisticsOnReadDLCs.Text = "Errors at DD time removal" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                }
                                //rtxt_StatisticsOnReadDLCs.Text = "timesptamp: " + tecst + "-" + ts + "-" + v + "-" + ea + "...\n" + rtxt_StatisticsOnReadDLCs.Text;
                                UpdateT = false;
                                for (m = 0; m < ea; m++)
                                {
                                    //if (tecst == "12.034") rtxt_StatisticsOnReadDLCs.Text = "time: " + m + "-" + timea[m] + ea + "-" + line + "...\n" + rtxt_StatisticsOnReadDLCs.Text;
                                    if (ts == timea[m])
                                    {
                                        if (v > lvla[m])
                                        {
                                            notes[m] = line;
                                            timea[m] = ts;
                                            lvla[m] = v;
                                            UpdateT = true;
                                        }
                                        break;
                                    }
                                    //else if (time[v]<1) time[v]=
                                }
                                if (!UpdateT) //if TimeStamp has not been found in the storage array then save it
                                {
                                    notes[ea] = line;
                                    timea[ea] = ts;
                                    lvla[ea] = v;
                                    ea++;
                                }
                            }
                            //anchor
                            if (line.Contains("<anchor time=\""))
                            {
                                tecst = (line.Replace("<anchor time=\"", "")).TrimStart();// ((line.Replace("<note time=\"", "")).TrimStart).IndexOf("\"\"")));
                                tecst = tecst.Replace(tecst.Substring(tecst.IndexOf("\"")), "");
                                try { ts = Convert.ToSingle(tecst); }
                                catch
                                {
                                    MessageBox.Show("Errors at DD time anchor READ removal"); //rtxt_StatisticsOnReadDLCs.Text = "Errors at DD anchor removal" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                                }
                                //rtxt_StatisticsOnReadDLCs.Text = "timesptamp: " + tecst + "-" + ts + "-" + v + "-" + ea + "...\n" + rtxt_StatisticsOnReadDLCs.Text;
                                UpdateT = false;
                                for (m = 0; m < eb; m++)
                                {
                                    //rtxt_StatisticsOnReadDLCs.Text = "time: " + m+"-"+time[m] + "...\n" + rtxt_StatisticsOnReadDLCs.Text;
                                    if (ts == timeb[m])
                                    {
                                        if (v > lvlb[m])
                                        {
                                            anchor[m] = line;
                                            timeb[m] = ts;
                                            lvlb[m] = v;
                                            UpdateT = true;
                                        }
                                        break;
                                    }
                                    //else if (time[v]<1) time[v]=
                                }
                                if (!UpdateT) //if TimeStamp has not been found in the storage array then save it
                                {
                                    anchor[eb] = line;
                                    timeb[eb] = ts;
                                    lvlb[eb] = v;
                                    eb++;
                                }
                            }
                            //if () ;
                            //"<note time=\"";
                            if (line.Contains("<notes>")) continue;
                            //anchor

                        }

                        //rtxt_StatisticsOnReadDLCs.Text = "content: " + ea + "-" +eb+"="+ v + "...\n" + rtxt_StatisticsOnReadDLCs.Text;
                        //reorder the storage array
                        var n = 0;
                        string no;
                        int lv;
                        float ti;
                        for (m = 0; m <= ea - 1; m++)
                        {
                            for (n = m + 1; n <= ea; n++)
                            {
                                if (timea[m] > timea[n]) //if TimeStamp is bigger reverse the order
                                {
                                    no = notes[n];
                                    ti = timea[n];
                                    lv = lvla[n];
                                    notes[n] = notes[m];
                                    timea[n] = timea[m];
                                    lvla[n] = lvla[m];
                                    notes[m] = no;
                                    timea[m] = ti;
                                    lvla[m] = lv;
                                }
                            }
                        }
                        //reorder the anchor storage array
                        for (m = 0; m <= eb - 1; m++)
                        {
                            for (n = m + 1; n <= eb; n++)
                            {
                                if (timeb[m] > timeb[n]) //if TimeStamp is bigger reverse the order
                                {
                                    no = anchor[n];
                                    ti = timeb[n];
                                    lv = lvlb[n];
                                    anchor[n] = anchor[m];
                                    timeb[n] = timeb[m];
                                    lvlb[n] = lvlb[m];
                                    anchor[m] = no;
                                    timeb[m] = ti;
                                    lvlb[m] = lv;
                                }
                            }
                        }
                        //add level & notes to the footer
                        footer += "    <level difficulty=\"0\">" + "\n" + "      <notes>" + "\n";
                        for (m = 0; m <= ea; m++)
                        {
                            footer += notes[m] + "\n";
                        }
                        footer += "	  </notes>\n      <chords />\n      <anchors>\n";
                        //add level & notes to the footer
                        for (m = 0; m <= eb; m++)
                        {
                            footer += anchor[m] + "\n";
                        }
                        footer += "      </anchors>" + "\n" + "      <handShapes />" + "\n" + "     </level>" + "\n" + "   </levels>" + "\n" + "</song>";
                        //rtxt_StatisticsOnReadDLCs.Text = "Saving..." + "...\n" + rtxt_StatisticsOnReadDLCs.Text;
                        fxml.Close();
                        File.WriteAllText(xml, header + footer);

                        //textfile = textfile.Replace("<heroLevels>", "");
                        //textfile = textfile.Replace("<heroLevel difficulty=\"0\" hero=\"1\" />", "");
                        //textfile = textfile.Replace("<heroLevel difficulty=\"0\" hero=\"2\" />", "");
                        //textfile = textfile.Replace("<heroLevel difficulty=\"0\" hero=\"3\" />", "");
                        //textfile = textfile.Replace("</heroLevels>", "");
                        //textfile = textfile.Replace("<level difficulty=\""+0+"\">", "<level difficulty = \""+(j+1)+"\">");
                        //textfile = textfile.Replace("<level difficulty=\""+j+"\">", "<level difficulty=\"0\">");

                        //level the json as well
                        //var json = (xml.Replace("EOF", "Toolkit")).Replace(".xml", ".json");
                        textfile = File.ReadAllText(json);
                        n = 0;
                        for (n = 0; n < j; n++)
                        {
                            textfile = textfile.Replace("\"MaxPhraseDifficulty\": " + n + ",", "\"MaxPhraseDifficulty\": 0,");
                        }
                        File.WriteAllText(json, textfile);
                        //rtxt_StatisticsOnReadDLCs.Text = "...DD changes written to file" + "\n" + rtxt_StatisticsOnReadDLCs.Text;
                        //}
                    }
                }
                Has_BassDD = "No";
                //bassRemoved = "Yes";
                //rtxt_StatisticsOnReadDLCs.Text = "something..." + "...\n" + rtxt_StatisticsOnReadDLCs.Text;
            }

            //remove altough original or t0o old dd
            platform.version = RocksmithToolkitLib.GameVersion.RS2014;
            Song2014 xmlContent = Song2014.LoadFromFile(xml);
            var manifestFunctions = new ManifestFunctions(platform.version);
            //manifestFunctions.GetMaxDifficulty(xmlContent) = "0";
            return Has_BassDD;
        }
        public string GenerateManifest(string dlcKey, IList<Arrangement> arrangements, SongInfo songInfo, Platform platform)
        {
            var manifest = Manifest;
            manifest.Entries = new Dictionary<string, Dictionary<string, Attributes>>();
            bool firstarrangset = false;

            Arrangement vocal = null;
            if (arrangements.Any<Arrangement>(a => a.ArrangementType == Sng.ArrangementType.Vocal))
                vocal = arrangements.Single<Arrangement>(a => a.ArrangementType == Sng.ArrangementType.Vocal);

            var manifestFunctions = new ManifestFunctions(platform.version);
            var songPartition = new SongPartition();

            foreach (var x in arrangements)
            {
                var isVocal = x.ArrangementType == Sng.ArrangementType.Vocal;
                var song = (isVocal) ? null : Song.LoadFromFile(x.SongXml.File);

                var attribute = new Attributes();
                attribute.AlbumArt = String.Format("urn:llid:{0}", AggregateGraph.AlbumArt.LLID);
                // TODO: add better AlbumNameSort feature
                attribute.AlbumNameSort = attribute.AlbumName = songInfo.Album;
                attribute.ArrangementName = x.Name.ToString();
                attribute.ArtistName = songInfo.Artist;
                attribute.ArtistNameSort = songInfo.ArtistSort;
                attribute.AssociatedTechniques = new List<string>();
                //Should be 51 for bass, 49 for vocal and guitar
                attribute.BinaryVersion = x.ArrangementType == Sng.ArrangementType.Bass ? 51 : 49;
                attribute.BlockAsset = String.Format("urn:emergent-world:{0}", AggregateGraph.XBlock.Name);
                attribute.ChordTemplates = null;
                attribute.DISC_DLC_OTHER = "Disc";
                attribute.DisplayName = songInfo.SongDisplayName;
                attribute.DLCPreview = false;
                attribute.EffectChainMultiplayerName = string.Empty;
                attribute.EffectChainName = isVocal ? "" : (dlcKey + "_" + x.ToneBase == null ? "Default" : x.ToneBase.Replace(' ', '_'));
                attribute.EventFirstTimeSortOrder = 9999;
                attribute.ExclusiveBuild = new List<object>();
                attribute.FirstArrangementInSong = false;
                if (isVocal && !firstarrangset)
                {
                    firstarrangset = true;
                    attribute.FirstArrangementInSong = true;
                }
                attribute.ForceUseXML = true;
                attribute.Genre = "PLACEHOLDER Genre";
                attribute.InputEvent = isVocal ? "Play_Tone_Standard_Mic" : "Play_Tone_";
                attribute.IsDemoSong = false;
                attribute.IsDLC = true;
                attribute.LastConversionDateTime = "";
                int masterId = isVocal ? 1 : x.MasterId;
                attribute.MasterID_PS3 = masterId;
                attribute.MasterID_Xbox360 = masterId;
                attribute.MaxPhraseDifficulty = 0;
                attribute.PersistentID = x.Id.ToString().Replace("-", "").ToUpper();
                attribute.PhraseIterations = new List<PhraseIteration>();
                attribute.Phrases = new List<Phrase>();
                attribute.PluckedType = x.PluckedType == Sng.PluckedType.Picked ? "Picked" : "Not Picked";
                attribute.RelativeDifficulty = isVocal ? 0 : song.Levels.Length;
                attribute.RepresentativeArrangement = false;
                attribute.Score_MaxNotes = 0;
                attribute.Score_PNV = 0;
                attribute.Sections = new List<Section>();
                attribute.Shipping = true;
                attribute.SongAsset = String.Format("urn:llid:{0}", x.SongFile.LLID);
                attribute.SongEvent = String.Format("Play_{0}", dlcKey);
                attribute.SongKey = dlcKey;
                attribute.SongLength = 0;
                attribute.SongName = songInfo.SongDisplayName;
                attribute.SongNameSort = songInfo.SongDisplayNameSort;
                attribute.SongXml = String.Format("urn:llid:{0}", x.SongXml.LLID);
                attribute.SongYear = songInfo.SongYear;
                attribute.TargetScore = 0;
                attribute.ToneUnlockScore = 0;
                attribute.TwoHandTapping = false;
                attribute.UnlockKey = "";
                attribute.Tuning = x.Tuning;
                attribute.VocalsAssetId = x.ArrangementType == Sng.ArrangementType.Vocal ? "" : (vocal != null) ? String.Format("{0}|GRSong_{1}", vocal.Id, vocal.Name) : "";
                attribute.ChordTemplates = new List<ChordTemplate>();
                manifestFunctions.GenerateDynamicVisualDensity(attribute, song, x, GameVersion.RS2012);

                if (!isVocal)
                {
                    #region "Associated Techniques"

                    attribute.PowerChords = song.HasPowerChords();
                    if (song.HasPowerChords()) AssociateTechniques(x, attribute, "PowerChords");
                    attribute.BarChords = song.HasBarChords();
                    if (song.HasBarChords()) AssociateTechniques(x, attribute, "BarChords");
                    attribute.OpenChords = song.HasOpenChords();
                    if (song.HasOpenChords()) AssociateTechniques(x, attribute, "ChordIntro");
                    attribute.DoubleStops = song.HasDoubleStops();
                    if (song.HasDoubleStops()) AssociateTechniques(x, attribute, "DoubleStops");
                    attribute.Sustain = song.HasSustain();
                    if (song.HasSustain()) AssociateTechniques(x, attribute, "Sustain");
                    attribute.Bends = song.HasBends();
                    if (song.HasBends()) AssociateTechniques(x, attribute, "Bends");
                    attribute.Slides = song.HasSlides();
                    if (song.HasSlides()) AssociateTechniques(x, attribute, "Slides");
                    attribute.Tremolo = song.HasTremolo();
                    if (song.HasTremolo()) AssociateTechniques(x, attribute, "Tremolo");
                    attribute.SlapAndPop = song.HasSlapAndPop();
                    if (song.HasSlapAndPop()) AssociateTechniques(x, attribute, "Slap");
                    attribute.Harmonics = song.HasHarmonics();
                    if (song.HasHarmonics()) AssociateTechniques(x, attribute, "Harmonics");
                    attribute.PalmMutes = song.HasPalmMutes();
                    if (song.HasPalmMutes()) AssociateTechniques(x, attribute, "PalmMutes");
                    attribute.HOPOs = song.HasHOPOs();
                    if (song.HasHOPOs()) AssociateTechniques(x, attribute, "HOPOs");
                    attribute.FretHandMutes = song.HasFretHandMutes();
                    if (song.HasFretHandMutes()) AssociateTechniques(x, attribute, "FretHandMutes");
                    attribute.DropDPowerChords = song.HasDropDPowerChords();
                    if (song.HasDropDPowerChords()) AssociateTechniques(x, attribute, "DropDPowerChords");
                    attribute.Prebends = song.HasPrebends();
                    if (song.HasPrebends()) AssociateTechniques(x, attribute, "Prebends");
                    attribute.Vibrato = song.HasVibrato();
                    if (song.HasVibrato()) AssociateTechniques(x, attribute, "Vibrato");

                    //Bass exclusive
                    attribute.TwoFingerPlucking = song.HasTwoFingerPlucking();
                    if (song.HasTwoFingerPlucking()) AssociateTechniques(x, attribute, "Plucking");
                    attribute.FifthsAndOctaves = song.HasFifthsAndOctaves();
                    if (song.HasFifthsAndOctaves()) AssociateTechniques(x, attribute, "Octave");
                    attribute.Syncopation = song.HasSyncopation();
                    if (song.HasSyncopation()) AssociateTechniques(x, attribute, "Syncopation");

                    #endregion

                    attribute.AverageTempo = songInfo.AverageTempo;
                    attribute.RepresentativeArrangement = true;
                    attribute.SongPartition = songPartition.GetSongPartition(x.Name, x.ArrangementType);
                    attribute.SongLength = (float)Math.Round((decimal)song.SongLength, 3, MidpointRounding.AwayFromZero); //rounded
                    attribute.LastConversionDateTime = song.LastConversionDateTime;
                    attribute.TargetScore = 100000;
                    attribute.ToneUnlockScore = 70000;
                    attribute.SongDifficulty = (float)song.PhraseIterations.Average(it => song.Phrases[it.PhraseId].MaxDifficulty);
                    manifestFunctions.GenerateChordTemplateData(attribute, song);
                    manifestFunctions.GeneratePhraseData(attribute, song);
                    manifestFunctions.GenerateSectionData(attribute, song);
                    manifestFunctions.GeneratePhraseIterationsData(attribute, song, platform.version);
                }
                var attrDict = new Dictionary<string, Attributes> { { "Attributes", attribute } };
                manifest.Entries.Add(attribute.PersistentID, attrDict);
            }
            manifest.ModelName = "GRSong_Asset";
            manifest.IterationVersion = 2;
            return JsonConvert.SerializeObject(manifest, Formatting.Indented);
        }
        private static void UpdateManifest2014(string songDirectory, Platform platform)
        {
            if (platform.version != GameVersion.RS2014)
            {
                return;
            }

            var hsanFiles = Directory.EnumerateFiles(songDirectory, "*.hsan", SearchOption.AllDirectories).ToList();

            if (!hsanFiles.Any())
            {
                throw new DataException("Error: could not find any hsan file");
            }
            if (hsanFiles.Count > 1)
            {
                throw new DataException("Error: there is more than one hsan file");
            }

            var manifestHeader = new ManifestHeader2014 <AttributesHeader2014>(platform);
            var hsanFile       = hsanFiles.First();
            var jsonFiles      = Directory.EnumerateFiles(songDirectory, "*.json", SearchOption.AllDirectories).ToList();
            var xmlFiles       = Directory.EnumerateFiles(songDirectory, "*.xml", SearchOption.AllDirectories).ToList();

            //var songFiles = xmlFiles.Where(x => !x.ToLower().Contains("showlight") && !x.ToLower().Contains("vocal")).ToList();
            //var vocalFiles = xmlFiles.Where(x => x.ToLower().Contains("vocal")).ToList();

            foreach (var xmlFile in xmlFiles)
            {
                var xmlName = Path.GetFileNameWithoutExtension(xmlFile);
                if (xmlName.ToLower().Contains("showlight"))
                {
                    continue;
                }

                var json = jsonFiles.FirstOrDefault(name => Path.GetFileNameWithoutExtension(name) == xmlName);
                if (String.IsNullOrEmpty(json))
                {
                    continue;
                }

                var attr = Manifest2014 <Attributes2014> .LoadFromFile(json).Entries.First().Value.First().Value;

                if (!xmlName.ToLower().Contains("vocal"))
                {
                    var manifestFunctions = new ManifestFunctions(platform.version);
                    var xmlContent        = Song2014.LoadFromFile(xmlFile);

                    attr.PhraseIterations = new List <Manifest.PhraseIteration>();
                    manifestFunctions.GeneratePhraseIterationsData(attr, xmlContent, platform.version);

                    attr.Phrases = new List <Manifest.Phrase>();
                    manifestFunctions.GeneratePhraseData(attr, xmlContent);

                    attr.Sections = new List <Manifest.Section>();
                    manifestFunctions.GenerateSectionData(attr, xmlContent);

                    attr.Tuning = new TuningStrings();
                    manifestFunctions.GenerateTuningData(attr, xmlContent);

                    attr.MaxPhraseDifficulty = manifestFunctions.GetMaxDifficulty(xmlContent);
                }

                // else { // TODO: good place to update vocals }

                // write updated json file
                var attributeDictionary = new Dictionary <string, Attributes2014> {
                    { "Attributes", attr }
                };
                var manifest = new Manifest2014 <Attributes2014>();
                manifest.Entries.Add(attr.PersistentID, attributeDictionary);
                manifest.SaveToFile(json);

                // update manifestHeader (hsan) entry
                var attributeHeaderDictionary = new Dictionary <string, AttributesHeader2014> {
                    { "Attributes", new AttributesHeader2014(attr) }
                };
                if (platform.IsConsole)
                {
                    // One for each arrangements (Xbox360/PS3)
                    manifestHeader = new ManifestHeader2014 <AttributesHeader2014>(platform);
                    manifestHeader.Entries.Add(attr.PersistentID, attributeHeaderDictionary);
                }
                else
                {
                    manifestHeader.Entries.Add(attr.PersistentID, attributeHeaderDictionary);
                }
            }

            // write updated hsan file
            manifestHeader.SaveToFile(hsanFile);
        }
        private static void UpdateManifest2014(string songDirectory, Platform platform)
        {
            if (platform.version != GameVersion.RS2014)
                return;

            var hsanFiles = Directory.EnumerateFiles(songDirectory, "*.hsan", SearchOption.AllDirectories).ToList();
            if (!hsanFiles.Any())
                throw new DataException("Error: could not find any hsan file");
            if (hsanFiles.Count > 1)
                throw new DataException("Error: there is more than one hsan file");

            var manifestHeader = new ManifestHeader2014<AttributesHeader2014>(platform);
            var hsanFile = hsanFiles.First();
            var jsonFiles = Directory.EnumerateFiles(songDirectory, "*.json", SearchOption.AllDirectories).ToList();
            var xmlFiles = Directory.EnumerateFiles(songDirectory, "*.xml", SearchOption.AllDirectories).ToList();
            //var songFiles = xmlFiles.Where(x => !x.ToLower().Contains("showlight") && !x.ToLower().Contains("vocal")).ToList();
            //var vocalFiles = xmlFiles.Where(x => x.ToLower().Contains("vocal")).ToList();

            foreach (var xmlFile in xmlFiles)
            {
                var xmlName = Path.GetFileNameWithoutExtension(xmlFile);
                if (xmlName.ToLower().Contains("showlight"))
                    continue;

                var json = jsonFiles.FirstOrDefault(name => Path.GetFileNameWithoutExtension(name) == xmlName);
                if (String.IsNullOrEmpty(json))
                    continue;

                var attr = Manifest2014<Attributes2014>.LoadFromFile(json).Entries.First().Value.First().Value;

                if (!xmlName.ToLower().Contains("vocal"))
                {
                    var manifestFunctions = new ManifestFunctions(platform.version);
                    var xmlContent = Song2014.LoadFromFile(xmlFile);

                    attr.PhraseIterations = new List<Manifest.PhraseIteration>();
                    manifestFunctions.GeneratePhraseIterationsData(attr, xmlContent, platform.version);

                    attr.Phrases = new List<Manifest.Phrase>();
                    manifestFunctions.GeneratePhraseData(attr, xmlContent);

                    attr.Sections = new List<Manifest.Section>();
                    manifestFunctions.GenerateSectionData(attr, xmlContent);

                    attr.Tuning = new TuningStrings();
                    manifestFunctions.GenerateTuningData(attr, xmlContent);

                    attr.MaxPhraseDifficulty = manifestFunctions.GetMaxDifficulty(xmlContent);
                }

                // else { // TODO: good place to update vocals }

                // write updated json file
                var attributeDictionary = new Dictionary<string, Attributes2014> { { "Attributes", attr } };
                var manifest = new Manifest2014<Attributes2014>();
                manifest.Entries.Add(attr.PersistentID, attributeDictionary);
                manifest.SaveToFile(json);

                // update manifestHeader (hsan) entry
                var attributeHeaderDictionary = new Dictionary<string, AttributesHeader2014> { { "Attributes", new AttributesHeader2014(attr) } };
                if (platform.IsConsole)
                {
                    // One for each arrangements (Xbox360/PS3)
                    manifestHeader = new ManifestHeader2014<AttributesHeader2014>(platform);
                    manifestHeader.Entries.Add(attr.PersistentID, attributeHeaderDictionary);
                }
                else
                    manifestHeader.Entries.Add(attr.PersistentID, attributeHeaderDictionary);
            }

            // write updated hsan file
            manifestHeader.SaveToFile(hsanFile);
        }