Example #1
0
        public bool ExtractDecryptMogg(string CON_file, bool bypass, NemoTools tools, DTAParser parser)
        {
            Initialize();
            Tools  = tools;
            Parser = parser;
            Tools.ReleaseStreamHandle();
            if (!Parser.ExtractDTA(CON_file))
            {
                ErrorLog.Add("Couldn't extract songs.dta file from that CON file");
                return(false);
            }
            if (!Parser.ReadDTA(Parser.DTA) || !Parser.Songs.Any())
            {
                ErrorLog.Add("Couldn't read that songs.dta file");
                return(false);
            }
            if (Parser.Songs.Count > 1)
            {
                ErrorLog.Add("This feature does not support packs, only single songs\nUse the dePACK feature in C3 CON Tools' Quick Pack Editor to split this pack into single songs and try again");
                return(false);
            }
            var internal_name = Parser.Songs[0].InternalName;
            var xCON          = new STFSPackage(CON_file);

            if (!xCON.ParseSuccess)
            {
                ErrorLog.Add("Couldn't parse that CON file");
                xCON.CloseIO();
                return(false);
            }
            var xMogg = xCON.GetFile("songs/" + internal_name + "/" + internal_name + ".mogg");

            if (xMogg == null)
            {
                ErrorLog.Add("Couldn't find the mogg file inside that CON file");
                xCON.CloseIO();
                return(false);
            }
            var mData = xMogg.Extract();

            xCON.CloseIO();
            if (mData == null || mData.Length == 0)
            {
                ErrorLog.Add("Couldn't extract the mogg file from that CON file");
                return(false);
            }
            LoadLibraries();
            if (Tools.DecM(mData, bypass, false, DecryptMode.ToMemory))
            {
                return(true);
            }
            ErrorLog.Add("Mogg file is encrypted and I could not decrypt it, can't split it");
            return(false);
        }
Example #2
0
        private bool ExtractFile(string extension, bool sublevel, string internalname, string rename, bool keep = false)
        {
            if (xPackage == null || !xPackage.ParseSuccess)
            {
                return(false);
            }

            var outputfolder = txtFolder.Text + "\\" + (organizeFilesByType.Checked ? (extension == "mid" ? "midi" : extension) + "_files\\" : "");
            var ext          = "." + extension;
            var dir          = "songs/" + internalname + (sublevel ? "/gen/" : "/") + internalname;
            var file         = dir + (keep ? "_keep" : "") + ext;

            var xfile = xPackage.GetFile(file);

            if (xfile == null)
            {
                Log("Could not find " + extension.ToUpper() + " file inside " + Path.GetFileName(file));
                return(false);
            }
            try
            {
                var newfile = outputfolder + rename + (keep && !removekeepFromPNGXBOXFiles.Checked ? "_keep" : "") + ext;
                extension = extension.ToLowerInvariant() == "mid" ? "MIDI" : extension.ToUpper();

                Log("Extracting " + extension + " file " + Path.GetFileName(newfile));

                if (!Directory.Exists(outputfolder))
                {
                    Directory.CreateDirectory(outputfolder);
                }

                Tools.DeleteFile(newfile);
                if (xfile.ExtractToFile(newfile))
                {
                    if (Path.GetExtension(newfile) == ".mogg")
                    {
                        Tools.WriteOutData(Tools.ObfM(File.ReadAllBytes(newfile)), newfile);
                    }
                    Log("File " + rename + ext + " extracted successfully");
                }
                else
                {
                    Log("Extracting file " + rename + ext + " failed");
                }
            }
            catch (Exception ex)
            {
                Log("There was an error extracting file " + rename + ext);
                Log("The error says: " + ex.Message);
                return(false);
            }
            return(true);
        }
Example #3
0
        private void UpdateSTFS(STFSPackage package, byte[] kvData)
        {
            if (package != null)
            {
                // Inject the new mmiof.bmf
                X360.STFS.FileEntry file = package.GetFile(_rawFileName);
                file.Inject(_rawPath);

                if (kvData != null)
                {
                    // Resign the package using the KV data
                    DJsIO kvStream = new DJsIO(kvData, true);
                    package.FlushPackage(new X360.STFS.RSAParams(kvStream));
                    kvStream.Close();
                }
            }
        }
Example #4
0
        public void LoadSTFS(STFSPackage package, string rawFileName, string extractDir)
        {
            X360.STFS.FileEntry file = package.GetFile(rawFileName);

            // Create the extraction directory
            Directory.CreateDirectory(extractDir);
            string newRawPath = extractDir + rawFileName;

            // Extract the file and close the package
            if (!file.Extract(newRawPath))
            {
                throw new ArgumentException("Unable to extract " + rawFileName + " to \"" + extractDir + "\". Make sure that your save is not corrupt and that you reached a checkpoint first.");
            }

            // Load the mmiof.bmf file into the _saveData object
            _saveData    = _constructSave(newRawPath);
            _rawPath     = newRawPath;
            _rawFileName = rawFileName;
        }
Example #5
0
        private string ExtractMIDI(string con, bool isUpgrade)
        {
            var midi = "";

            var xPackage = new STFSPackage(con);

            if (!xPackage.ParseSuccess)
            {
                MessageBox.Show("There was an error parsing CON file, can't extract MIDI", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Log("Can't work with this CON file, try again");
                return("");
            }

            try
            {
                var xent = xPackage.GetFolder("songs");
                if (xent == null && !isUpgrade)
                {
                    xent = xPackage.GetFolder("songs_upgrades");
                    MessageBox.Show(xent != null ? "This looks like a pro upgrade, only song files are valid here" :
                                    "I can't find a 'songs' folder in that CON file, make sure sure it's a Rock Band song file",
                                    Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    xPackage.CloseIO();
                    Log("Can't work with this CON file, try again");
                    return("");
                }

                //we can't work with packs or pro upgrades, so check and skip
                xent = xPackage.GetFolder("songs_upgrades");
                if (xent != null && !isUpgrade)
                {
                    xent = xPackage.GetFolder("songs");
                    MessageBox.Show(xent != null ? "It looks like this is a pack, only individual song files are valid here"
                            : "This looks like a pro upgrade, only song files are valid here",
                                    Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    xPackage.CloseIO();
                    Log("Can't work with this CON file, try again");
                    return("");
                }

                var folder  = isUpgrade ? "songs_upgrades/" : "songs/";
                var dtaFile = isUpgrade ? "upgrades.dta" : "songs.dta";
                var dta     = temp_folder + dtaFile;

                if (Parser.ExtractDTA(xPackage, false, isUpgrade))
                {
                    if (Parser.ReadDTA(Parser.DTA) && Parser.Songs.Count > 1)
                    {
                        MessageBox.Show("It looks like this is a pack, only individual song files are valid here",
                                        Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        xPackage.CloseIO();
                        Log("Can't work with this CON file, try again");
                        return("");
                    }
                }

                var xFile = xPackage.GetFile(folder + dtaFile);
                if (xFile == null)
                {
                    MessageBox.Show("Can't find " + dtaFile + " inside this CON file\nI can't work without it", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    xPackage.CloseIO();
                    Log("Can't work with this CON file, try again");
                    return("");
                }

                var fileName = Path.GetFileName(con);
                if (fileName != null)
                {
                    if (!Parser.WriteDTAToFile(dta))
                    {
                        MessageBox.Show("Something went wrong in extracting the " + dtaFile + " file\nI can't work without it", Text,
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                        xPackage.CloseIO();
                        Log("Can't work with this CON file, try again");
                        return("");
                    }
                }

                var artists  = 0;
                var songname = "";

                var sr = new StreamReader(dta, Parser.GetDTAEncoding(Parser.DTA));
                // read one line at a time until the end
                while (sr.Peek() >= 0)
                {
                    var line = sr.ReadLine();
                    if (string.IsNullOrWhiteSpace(line.Trim()))
                    {
                        continue;
                    }

                    if (line.ToLowerInvariant().Contains("artist") && !line.ToLowerInvariant().Contains(";") && !isUpgrade)
                    {
                        artists++;
                    }
                    else if (line.ToLowerInvariant().Contains("songs/") && !line.Contains("midi_file") && !isUpgrade)
                    {
                        songname      = Parser.GetInternalName(line);
                        song_int_name = songname;
                    }
                    else if (line.Contains("song_id"))
                    {
                        if (isUpgrade)
                        {
                            upgradeID = Parser.GetSongID(line);
                        }
                        else
                        {
                            songID = Parser.GetSongID(line);
                            CheckIDMatch();
                        }
                    }
                    else if (line.Contains("midi_file") && isUpgrade)
                    {
                        var midipath = line.Replace("(", "");
                        midipath         = midipath.Replace(")", "");
                        midipath         = midipath.Replace("midi_file", "");
                        midipath         = midipath.Replace("songs_upgrades", "");
                        midipath         = midipath.Replace("\"", "");
                        midipath         = midipath.Replace("/", "");
                        songname         = midipath.Trim();
                        upgrade_int_name = songname.Replace(".mid", "");
                    }
                }
                sr.Dispose();

                if (artists > 1) //if single song, packs will have values > 1
                {
                    MessageBox.Show("It looks like this is a pack, only individual song files are valid here",
                                    Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    xPackage.CloseIO();
                    Log("Can't work with this CON file, try again");
                    return("");
                }

                xFile = xPackage.GetFile(folder + songname + (isUpgrade ? "" : "/" + songname + ".mid"));
                if (xFile != null)
                {
                    midi = temp_folder + songname + (isUpgrade? "" : ".mid");
                    Tools.DeleteFile(midi);
                    if (!xFile.ExtractToFile(midi))
                    {
                        MessageBox.Show("Can't find a MIDI file inside this CON file\nI can't work without it", Text,
                                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        xPackage.CloseIO();
                        Log("Can't work with this CON file, try again");
                        return("");
                    }
                }
                xPackage.CloseIO();

                if (isUpgrade)
                {
                    newupgdta = dta;
                    ReadUpgDTA(newupgdta);
                }
                else
                {
                    orig_dta = dta;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was an error:\n" + ex.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                xPackage.CloseIO();
            }
            return(midi);
        }
Example #6
0
        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            if (!File.Exists(orig_con))
            {
                Log("CON file " + Path.GetFileName(orig_con) + " seems to have been deleted, can't continue without it");
                return;
            }

            var BundleFile = orig_con + " (bundled)";

            Tools.DeleteFile(BundleFile);
            File.Copy(orig_con, BundleFile);


            var xPackage = new STFSPackage(BundleFile);

            if (!xPackage.ParseSuccess)
            {
                Log("There was an error parsing CON file to bundle");
                xPackage.CloseIO();
                return;
            }

            var xent = xPackage.GetFile("/songs/songs.dta");

            if (xent != null)
            {
                if (xent.Replace(newDTA))
                {
                    Log("Bundled DTA file successfully");
                }
            }

            xent = xPackage.GetFile("/songs/" + Path.GetFileNameWithoutExtension(orig_midi) + "/" + Path.GetFileName(orig_midi));
            if (xent != null)
            {
                if (xent.Replace(newMIDI))
                {
                    Log("Bundled MIDI file successfully");
                }
            }

            xPackage.Header.MakeAnonymous();
            xPackage.Header.ThisType = PackageType.SavedGame;

            var success = false;

            try
            {
                Log("Rebuilding CON file ... this might take a little while");
                signature = new RSAParams(Application.StartupPath + "\\bin\\KV.bin");
                if (ChangeGameID.Checked)
                {
                    xPackage.Header.TitleID            = 0x45410914;
                    xPackage.Header.Title_Package      = "Rock Band 3";
                    xPackage.Header.ContentImageBinary = Resources.RB3.ImageToBytes(ImageFormat.Png);
                }
                xPackage.RebuildPackage(signature);
                xPackage.FlushPackage(signature);
                xPackage.CloseIO();
                success = true;
            }
            catch (Exception ex)
            {
                Log("There was an error: " + ex.Message);
                xPackage.CloseIO();
            }

            if (success)
            {
                Log("Trying to unlock CON file");
                if (Tools.UnlockCON(BundleFile))
                {
                    Log("Unlocked CON file successfully");
                }
                else
                {
                    Log("Error unlocking CON file");
                    success = false;
                }
            }

            if (success)
            {
                Log("Trying to sign CON file");
                if (Tools.SignCON(BundleFile))
                {
                    Log("CON file signed successfully");
                }
                else
                {
                    Log("Error signing CON file");
                    success = false;
                }
            }

            Log(success ? "Your files were bundled successfully!" : "Something went wrong along the way, sorry!");

            if (!cleanUpAfterBundlingFiles.Checked)
            {
                return;
            }
            Log("Cleaning up");
            CleanUp();
        }
Example #7
0
        private Util.SaveType loadSaveFile(string stfsPath)
        {
            // lolmultithreading

            _reachTaglists.RemoveMapSpecificTaglists();
            if (_saveManager != null)
            {
                _saveManager.Close();
            }

            STFSPackage package = null;

            try
            {
                // Open the STFS package
                string rawFileName;
                try
                {
                    package = new STFSPackage(stfsPath, null);
                }
                catch (Exception ex)
                {
                    throw new ArgumentException("The selected file is not a valid STFS package.", ex);
                }

                // Before detecting the save's game, check if it's a "Halo 4 Data" package
                // These packages aren't actually saved games, but a lot of users are getting this confused
                if (package.GetFile("data.cache") != null)
                {
                    Action wrongFileAction = new Action(() =>
                    {
                        showMessage("Packages named \"Halo 3 Data\" or \"Halo 4 Data\" aren't actual save files. You need to copy the ~11 MB file named after your gamertag instead. If you don't see anything, make sure to get to a checkpoint first.", "OOPS");
                    }
                                                        );
                    Dispatcher.Invoke(wrongFileAction);
                    return(Util.SaveType.Unknown);
                }

                // Detect the save's game
                _currentGame = detectGame(package, out rawFileName);
                classInfo.storage.settings.applicationSettings.gameIdent.gameID = _currentGame;

                if (_currentGame == Util.SaveType.Unknown)
                {
                    Action notSupportedAction = new Action(() =>
                    {
                        showMessage(package.Header.Title_Display + " saves are not supported yet. Currently, only Halo 3, Halo 3: ODST, Halo: Reach, Halo: CE Anniversary, and Halo 4 saves are supported. Please select a different file.", "GAME NOT SUPPORTED");
                    }
                                                           );
                    Dispatcher.Invoke(notSupportedAction);
                    return(Util.SaveType.Unknown);
                }
                else if (_currentGame == Util.SaveType.SomeGame)
                {
                    Action eggAction = new Action(() =>
                    {
                        eggData.egg3Dialog dialog = new eggData.egg3Dialog();
                        dialog.Owner = this;
                        dialog.ShowDialog();
                    }
                                                  );
                    Dispatcher.Invoke(eggAction);
                    return(Util.SaveType.Unknown);
                }

                _saveManager.LoadSTFS(package, rawFileName, classInfo.extraIO.makeTempSaveDir());
                _packagePath = stfsPath;

                // Update some UI controls with package info
                Dispatcher.Invoke(new Action <string, uint, string, long>(setPackageInfo),
                                  new object[] { package.Header.Title_Package,
                                                 package.Header.TitleID,
                                                 package.Header.Title_Display,
                                                 package.Header.ProfileID });
            }
            catch (ArgumentException ex)
            {
                Dispatcher.Invoke(new Action <string, string>(showMessage), new object[] { ex.Message, "ERROR" });
                return(Util.SaveType.Unknown);
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(new Action <string, bool>(showException), new object[] { ex.ToString(), true });
                return(Util.SaveType.Unknown);
            }
            finally
            {
                if (package != null)
                {
                    package.CloseIO();
                }
            }

            return(_currentGame);
        }
Example #8
0
        private void FileExtractor_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            var dtafolder  = txtFolder.Text + "\\" + (organizeFilesByType.Checked ? "dta_files\\" : "");
            var dtacount   = 0;
            var midicount  = 0;
            var moggcount  = 0;
            var milocount  = 0;
            var pngcount   = 0;
            var thumbcount = 0;
            var hasdta     = false;
            var rename     = "";
            var counter    = 0;

            foreach (var file in inputFiles.Where(File.Exists).TakeWhile(file => !FileExtractor.CancellationPending))
            {
                try
                {
                    if (VariousFunctions.ReadFileType(file) != XboxFileType.STFS)
                    {
                        continue;
                    }
                    if (!Parser.ExtractDTA(file))
                    {
                        Log("Error extracting songs.dta from file: '" + Path.GetFileName(file) + "' ... skipping");
                        continue;
                    }
                    if (!Parser.ReadDTA(Parser.DTA) || !Parser.Songs.Any())
                    {
                        Log("Error reading that songs.dta file ... skipping");
                        continue;
                    }

                    try
                    {
                        xPackage = new STFSPackage(file);
                        if (!xPackage.ParseSuccess)
                        {
                            Log("Error opening file '" + Path.GetFileName(file) + "' ... skipping");
                            xPackage.CloseIO();
                        }
                        else
                        {
                            hasdta = true;

                            Log("CON file '" + Path.GetFileNameWithoutExtension(file) + "' contains " + Parser.Songs.Count + " " + (Parser.Songs.Count == 1 ? "song" : "songs"));
                            for (var i = 0; i < Parser.Songs.Count; i++)
                            {
                                if (FileExtractor.CancellationPending)
                                {
                                    xPackage.CloseIO();
                                    break;
                                }
                                var song = Parser.Songs[i];
                                counter++;
                                Log("Extracting files for song #" + (counter) + ": '" + song.Artist + " - " + song.Name + "'");
                                var songid = song.InternalName;

                                var name   = Tools.CleanString(song.Name, true);
                                var artist = Tools.CleanString(song.Artist, true);
                                songid = Tools.CleanString(songid, true);

                                rename = arrangeName(name, artist, songid).Replace("!", "").Replace("'", "");
                                rename = Tools.CleanString(rename, false);

                                if (chkMIDI.Checked && !FileExtractor.CancellationPending)
                                {
                                    if (ExtractFile("mid", false, songid, rename))
                                    {
                                        midicount++;
                                    }
                                }
                                if (chkMOGG.Checked && !FileExtractor.CancellationPending)
                                {
                                    if (ExtractFile("mogg", false, songid, rename))
                                    {
                                        moggcount++;
                                    }
                                }
                                if (chkPNG.Checked && !FileExtractor.CancellationPending)
                                {
                                    if (ExtractFile("png_xbox", true, songid, rename, true))
                                    {
                                        pngcount++;
                                    }
                                }
                                if (!chkMILO.Checked)
                                {
                                    continue;
                                }
                                if (ExtractFile("milo_xbox", true, songid, rename))
                                {
                                    milocount++;
                                }
                            }

                            if (FileExtractor.CancellationPending)
                            {
                                xPackage.CloseIO();
                                break;
                            }
                            var xUpgrade = xPackage.GetFile("songs_upgrades/upgrades.dta");
                            if (xUpgrade != null)
                            {
                                var temp_upg = Path.GetTempPath() + "upg.dta";
                                Tools.DeleteFile(temp_upg);

                                if (xUpgrade.ExtractToFile(temp_upg))
                                {
                                    var upg_midi = "";
                                    var sr       = new StreamReader(temp_upg);
                                    while (sr.Peek() >= 0)
                                    {
                                        var line = sr.ReadLine();
                                        if (string.IsNullOrWhiteSpace(line))
                                        {
                                            continue;
                                        }

                                        if (line.Contains("midi_file"))
                                        {
                                            upg_midi = line.Replace("midi_file", "").Replace("songs_upgrades", "")
                                                       .Replace("(", "").Replace(")", "").Replace("\"", "")
                                                       .Replace("/", "").Replace("'", "").Trim();
                                        }

                                        if (string.IsNullOrWhiteSpace(upg_midi))
                                        {
                                            continue;
                                        }
                                        if (chkMIDI.Checked)
                                        {
                                            var xmidi = xPackage.GetFile("songs_upgrades/" + upg_midi);
                                            if (xmidi != null)
                                            {
                                                var outputfolder = txtFolder.Text + "\\" + (organizeFilesByType.Checked ? "midi_files\\" : "");
                                                if (!Directory.Exists(outputfolder))
                                                {
                                                    Directory.CreateDirectory(outputfolder);
                                                }
                                                var out_midi = outputfolder + upg_midi;
                                                Log("Extracting MIDI file " + Path.GetFileName(out_midi));
                                                Tools.DeleteFile(out_midi);
                                                if (xmidi.ExtractToFile(out_midi))
                                                {
                                                    Log("Extracted " + Path.GetFileName(out_midi) + " successfully");
                                                    midicount++;
                                                }
                                                else
                                                {
                                                    Log("There was an error extracting upgrade MIDI file " + upg_midi);
                                                }
                                            }
                                            else
                                            {
                                                Log("Could not find upgrade MIDI file " + upg_midi + " in that file");
                                            }
                                        }
                                        upg_midi = "";
                                    }
                                    sr.Dispose();

                                    if (chkDTA.Checked)
                                    {
                                        if (!Directory.Exists(dtafolder))
                                        {
                                            Directory.CreateDirectory(dtafolder);
                                        }
                                        var upgdta = (string.IsNullOrWhiteSpace(xPackage.Header.Title_Display) ? Path.GetFileName(file) : xPackage.Header.Title_Display).Replace("!", "")
                                                     .Replace("'", "").Replace(" ", replaceSpacesWithUnderscores.Checked ? "_" : (removeSpacesFromFileName.Checked ? "" : " "));
                                        var upg_out = dtafolder + "\\" + Tools.CleanString(upgdta, false) + "_upgrade.dta";
                                        Tools.DeleteFile(upg_out);
                                        if (Tools.MoveFile(temp_upg, upg_out))
                                        {
                                            Log("Extracted " + Path.GetFileName(upg_out) + " successfully");
                                            dtacount++;
                                        }
                                        else
                                        {
                                            Log("There was an error extracting the upgrades.dta for " + Path.GetFileName(file));
                                        }
                                    }
                                }
                                else
                                {
                                    Log("There was an error extracting the upgrades.dta for " + Path.GetFileName(file));
                                }
                            }
                            else if (!hasdta)
                            {
                                Log("Could not find songs.dta or upgrades.dta inside '" + Path.GetFileName(file) + "'");
                            }
                        }

                        var packname = (string.IsNullOrWhiteSpace(xPackage.Header.Title_Display) ? Path.GetFileName(file) : xPackage.Header.Title_Display).Replace("!", "")
                                       .Replace("'", "").Replace(" ", replaceSpacesWithUnderscores.Checked ? "_" : (removeSpacesFromFileName.Checked ? "" : " "));
                        packname = Parser.Songs.Count == 1 && !string.IsNullOrWhiteSpace(rename) ? rename : Tools.CleanString(packname, false);

                        if (chkDTA.Checked && hasdta)
                        {
                            try
                            {
                                var newDTA = dtafolder + packname + (appendsongsToFiles.Checked ? "_songs" : "") + ".dta";
                                Log("Extracting DTA file " + Path.GetFileName(newDTA));
                                if (!Directory.Exists(dtafolder))
                                {
                                    Directory.CreateDirectory(dtafolder);
                                }
                                if (Parser.WriteDTAToFile(newDTA))
                                {
                                    Log(Path.GetFileName(newDTA) + " extracted successfully");
                                    dtacount++;
                                }
                                else
                                {
                                    Log("Looks like extracting the DTA file for " + Path.GetFileName(file) + " failed. Sorry.");
                                }
                            }
                            catch (Exception ex)
                            {
                                Log("Error extracting DTA file for " + Path.GetFileName(file));
                                Log("The error says: " + ex.Message);
                            }
                        }

                        if (chkThumbs.Checked && !FileExtractor.CancellationPending)
                        {
                            var thumbfolder = txtFolder.Text + "\\" + (organizeFilesByType.Checked ? "thumbnails\\" : "");
                            var package     = thumbfolder + packname + " Package.png";
                            var content     = thumbfolder + packname + " Content.png";
                            if (!Directory.Exists(thumbfolder))
                            {
                                Directory.CreateDirectory(thumbfolder);
                            }
                            try
                            {
                                Tools.DeleteFile(content);
                                var img = xPackage.Header.ContentImage;
                                img.Save(content, ImageFormat.Png);
                                img.Dispose();
                                thumbcount++;

                                Tools.DeleteFile(package);
                                img = xPackage.Header.PackageImage;
                                img.Save(package, ImageFormat.Png);
                                img.Dispose();
                                thumbcount++;

                                Log("Extracted thumbnails successfully");
                            }
                            catch (Exception ex)
                            {
                                Log("There was an error extracting the thumbnails");
                                Log("The error says: " + ex.Message);
                            }
                        }
                        xPackage.CloseIO();
                    }
                    catch (Exception ex)
                    {
                        Log("Error processing file '" + Path.GetFileName(file) + "'");
                        Log("The error says: " + ex.Message);
                        xPackage.CloseIO();
                    }
                }
                catch (Exception ex)
                {
                    Log("There was a problem accessing that file");
                    Log("The error says: " + ex.Message);
                    xPackage.CloseIO();
                }
            }

            if (dtacount + midicount + moggcount + milocount + pngcount + thumbcount == 0)
            {
                Log("Nothing was extracted ... please see the log for any failure reports");
            }
            else
            {
                if (dtacount > 0)
                {
                    Log("Extracted " + dtacount + " DTA " + (dtacount > 1 ? "files" : "file"));
                }
                if (pngcount > 0)
                {
                    Log("Extracted " + pngcount + " PNG_XBOX " + (pngcount > 1 ? "files" : "file"));
                    btnConverter.Invoke(new MethodInvoker(() => btnConverter.Visible = true));
                }
                if (midicount > 0)
                {
                    Log("Extracted " + midicount + " MIDI " + (midicount > 1 ? "files" : "file"));
                }
                if (moggcount > 0)
                {
                    Log("Extracted " + moggcount + " MOGG " + (moggcount > 1 ? "files" : "file"));
                }
                if (milocount > 0)
                {
                    Log("Extracted " + milocount + " MILO_XBOX " + (milocount > 1 ? "files" : "file"));
                }
                if (thumbcount > 0)
                {
                    Log("Extracted " + thumbcount + " " + (thumbcount > 1 ? "thumbnails" : "thumbnail"));
                }
            }
            xPackage.CloseIO();
        }
Example #9
0
        private void ExtractFromSaveFile(string file)
        {
            ClearAll();
            isWorking(true);
            var savefile = file;
            var isXbox   = Path.GetFileName(file).ToLowerInvariant().Contains("xbox") || Path.GetFileName(file) == "band3";

            isWii = Path.GetFileName(file).ToLowerInvariant().Contains("wii");
            isPS3 = Path.GetFileName(file).ToLowerInvariant().Contains("ps3");
            Tools.CurrentFolder = Path.GetDirectoryName(file);
            UserSaveFile        = file;

            if (VariousFunctions.ReadFileType(file) == XboxFileType.STFS)
            {
                isXbox = true;
                isPS3  = false;
                isWii  = false;

                Log("Received save CON file, extracting save.dat file");
                var package = new STFSPackage(file);
                if (!package.ParseSuccess)
                {
                    isWorking(false);
                    package.CloseIO();
                    Log("Couldn't read that CON file, aborting");
                    Log("Ready");
                    return;
                }
                var xent = package.GetFile("save.dat");
                if (xent == null)
                {
                    isWorking(false);
                    package.CloseIO();
                    Log("Couldn't find save.dat in that CON file, aborting");
                    Log("Ready");
                    return;
                }
                var tempdat = EditorFolder + "\\temp.dat";
                Tools.DeleteFile(tempdat);
                if (!xent.ExtractToFile(tempdat))
                {
                    isWorking(false);
                    package.CloseIO();
                    Log("Couldn't extract save.dat from that CON file, aborting");
                    Log("Ready");
                    return;
                }
                savefile = tempdat;
                package.CloseIO();
            }
            Log("Received save file, extracting images...");

            ImageFolder = EditorFolder + Path.GetFileNameWithoutExtension(file) + "_extracted\\";
            Tools.DeleteFolder(ImageFolder, true);

            var success = false;

            if (isXbox)
            {
                success = Tools.ExtractSaveImages(savefile, EditorFolder + Path.GetFileNameWithoutExtension(file));
            }
            else if (isWii)
            {
                success = Tools.ExtractWiiSaveImages(savefile, EditorFolder + Path.GetFileNameWithoutExtension(file));
            }
            else if (isPS3)
            {
                success = Tools.ExtractSaveImages(savefile, EditorFolder + Path.GetFileNameWithoutExtension(file), true);
            }
            else
            {
                switch (MessageBox.Show("Click Yes if this is a *decrypted* PS3 save file\nClick No if this is a Wii save file\nXbox 360 users must use the 'band3' save file\nPress Cancel to go back",
                                        Text, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
                {
                case DialogResult.Yes:
                    isPS3   = true;
                    isWii   = false;
                    success = Tools.ExtractSaveImages(savefile, EditorFolder + Path.GetFileNameWithoutExtension(file), true);
                    break;

                case DialogResult.No:
                    isWii   = true;
                    isPS3   = false;
                    success = Tools.ExtractWiiSaveImages(savefile, EditorFolder + Path.GetFileNameWithoutExtension(file));
                    break;

                case DialogResult.Cancel:
                    Log("Extracting cancelled by user");
                    isWorking(false);
                    Log("Ready");
                    return;
                }
            }

            if (!success)
            {
                Log("Extracting from save game file failed");
                isWorking(false);
                Log("Ready");
                return;
            }
            Log("Extracted images from save file successfully");

            if (savefile != file) //i.e. extracted from con
            {
                Tools.DeleteFile(savefile);
            }

            lblFileName.Text = Path.GetFileName(file);
            lblConsole.Text  = isPS3 ? "Playstation 3" : (isWii ? "Wii" : "Xbox 360");
            ChangeImagePadding();
            LoadExtractedImages();
            exportAllImagesToolStripMenuItem.Enabled = true;
            closeFileToolStripMenuItem.Enabled       = true;

            txtBand.Enabled  = true;
            txtBand.Text     = !string.IsNullOrWhiteSpace(Tools.SaveFileBandName) ? Tools.SaveFileBandName : "Unknown";
            txtBand.ReadOnly = isWii;

            isWorking(false);
            Log("Ready");
        }
Example #10
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            foreach (var file in FilesToConvert)
            {
                if (backgroundWorker1.CancellationPending)
                {
                    return;
                }
                var replaced = 0;
                try
                {
                    var xFile = new STFSPackage(file);
                    if (!xFile.ParseSuccess)
                    {
                        ProblemFiles.Add(file);
                        continue;
                    }

                    var xent = xFile.GetFile("/songs/songs.dta");
                    if (xent == null)
                    {
                        xFile.CloseIO();
                        ProblemFiles.Add(file);
                        continue;
                    }

                    var dta1 = Application.StartupPath + "\\bin\\dta1.txt";
                    Tools.DeleteFile(dta1);

                    if (!xent.Extract(dta1))
                    {
                        xFile.CloseIO();
                        ProblemFiles.Add(file);
                        continue;
                    }

                    var dta2 = Application.StartupPath + "\\bin\\dta2.txt";
                    Tools.DeleteFile(dta2);

                    var sr = new StreamReader(dta1, Encoding.Default);
                    var sw = new StreamWriter(dta2, false, Encoding.Default);
                    while (sr.Peek() >= 0)
                    {
                        var line = sr.ReadLine();
                        if (string.IsNullOrEmpty(line.Trim()))
                        {
                            continue;
                        }

                        if (line.Contains(";ORIG_ID="))
                        {
                            if (DoReverseBatch)
                            {
                                var id = line.Replace(";", "").Replace("ORIG_ID=", "").Trim();
                                sw.WriteLine("   ('song_id' " + id + ")");
                                sr.ReadLine();//skip the old song_id line
                                line = sr.ReadLine();
                                TotalSongs++;
                                replaced++;
                            }
                            else
                            {
                                sw.WriteLine(line);
                                line = sr.ReadLine();
                                sw.WriteLine(line);
                                line = sr.ReadLine();
                            }
                        }
                        else if (line.Contains("song_id") && !DoReverseBatch)
                        {
                            if (!Parser.IsNumericID(line))
                            {
                                line = ";ORIG_ID=" + Parser.GetSongID(line);
                                sw.WriteLine(line);
                                line = "   ('song_id' " + mMainForm.GetNumericID() + ")";
                                TotalSongs++;
                                replaced++;
                            }
                            else
                            {
                                SkippedFiles.Add(file);
                            }
                        }

                        if (!string.IsNullOrEmpty(line.Trim()))
                        {
                            sw.WriteLine(line);
                        }
                    }
                    sr.Dispose();
                    sw.Dispose();

                    if (replaced == 0) //don't modify this CON file if nothing is edited in this DTA file
                    {
                        if (!SkippedFiles.Contains(file))
                        {
                            SkippedFiles.Add(file);
                        }
                        xFile.CloseIO();
                        continue;
                    }

                    if (backgroundWorker1.CancellationPending)
                    {
                        xFile.CloseIO();
                        return;
                    }
                    if (!xent.Replace(dta2))
                    {
                        xFile.CloseIO();
                        ProblemFiles.Add(file);
                        continue;
                    }

                    Tools.DeleteFile(dta1);
                    Tools.DeleteFile(dta2);

                    xFile.Header.MakeAnonymous();
                    xFile.Header.ThisType = PackageType.SavedGame;
                    var signature = new RSAParams(Application.StartupPath + "\\bin\\KV.bin");
                    xFile.RebuildPackage(signature);
                    xFile.FlushPackage(signature);
                    xFile.CloseIO();
                    Tools.UnlockCON(file);
                    Tools.SignCON(file);
                    xFile.CloseIO();
                }
                catch (Exception)
                {
                    ProblemFiles.Add(file);
                }
            }
        }
Example #11
0
        public void LoadSavesFromDevices()
        {
            // Do Save Selector Code
            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork += (o2, args2) =>
            {
                Dispatcher.Invoke(new Action(delegate
                {
                    // Setup Pending UI stuff
                    progressPendingRefresh.Visibility = System.Windows.Visibility.Visible;

                    // Close Existing Streams
                    foreach (StartPageViewModel.FATXGameSave save in PageViewModel.FATXGameSaves)
                    {
                        save.Stream.Close();
                    }

                    // Clear ObservableCollection
                    PageViewModel.FATXGameSaves.Clear();
                }));

                if (_physDrives != null)
                {
                    foreach (Drive drive in _physDrives)
                    {
                        drive.Close();
                    }
                    _physDrives = null;
                }

                // Get Drives
                _physDrives = StartHere.GetFATXDrives().ToList();

                // Get Saves from said drives
                foreach (Drive drive in _physDrives)
                {
                    Folder xboxContent = drive.FolderFromPath("Data\\Content");

                    foreach (Folder content in xboxContent.Folders())
                    {
                        if (content.Name.StartsWith("E"))
                        {
                            // We're in a profile, lets go right into a game file
                            foreach (Manager.SupportedGames.SupportedGame supportedGame in Manager.SupportedGame.Games)
                            {
                                string filePath = string.Format("{0}\\Content\\{1}\\{2}\\00000001", "Data", content.Name, supportedGame.TitleID.ToString("X"));
                                if (drive.DirectoryExists(filePath))
                                {
                                    Folder profileGamesaveContent = drive.FolderFromPath(filePath);

                                    // Look though the profile folder for a campaign save
                                    foreach (CLKsFATXLib.File gamesaveContent in profileGamesaveContent.Files())
                                    {
                                        if (gamesaveContent.Name.StartsWith(supportedGame.STFSStartsWith))
                                        {
                                            try
                                            {
                                                // Is a campaign save, woop!
                                                // Add to the ObservableCollection and move out!
                                                StartPageViewModel.FATXGameSave fatxGamesave = new StartPageViewModel.FATXGameSave();

                                                fatxGamesave.FATXPath      = gamesaveContent.FullPath;
                                                fatxGamesave.PackageName   = gamesaveContent.Name;
                                                fatxGamesave.GameName      = supportedGame.Name;
                                                fatxGamesave.SafeGameName  = supportedGame.SafeName;
                                                fatxGamesave.SupportedGame = supportedGame;
                                                fatxGamesave.FATXDrive     = drive;

                                                // Check the save isn't already open
                                                string USID = Utilities.CreateUniqueSaveIdentification(gamesaveContent.Name, gamesaveContent.FullPath, true);
                                                if (!Backend.Settings.OpenedSaves.Contains(USID))
                                                {
                                                    // Extract gamestate to get data about the save
                                                    STFSPackage package         = new STFSPackage(new X360.IO.DJsIO(gamesaveContent.GetStream(), true), null);
                                                    FileEntry   gamestateHeader = package.GetFile("gamestate.hdr");
                                                    string      extractionPath  = Backend.VariousFunctions.CreateTemporaryFile(Backend.VariousFunctions.GetTemporaryExtractionLocation());
                                                    gamestateHeader.Extract(extractionPath);

                                                    // Create Stream, lol
                                                    EndianStream endianStream = new EndianStream(new MemoryStream(System.IO.File.ReadAllBytes(extractionPath)), Endian.BigEndian);

                                                    // Get Header Layout
                                                    StructureValueCollection saveHeader = StructureReader.ReadStructure(endianStream, supportedGame.GetLayout("header"));

                                                    fatxGamesave.Stream      = endianStream;
                                                    fatxGamesave.USID        = USID;
                                                    fatxGamesave.MapName     = SaveManager.Utilities.GetFriendlyMissionName(saveHeader.GetString("scenario"), (Utilities.HaloGames)Enum.Parse(typeof(Utilities.HaloGames), supportedGame.SafeName));
                                                    fatxGamesave.MapScenario = saveHeader.GetString("scenario");
                                                    string libertyImagePath = string.Format(@"/Liberty;component/Metro/Images/Games/MapImages/{0}/{1}.jpg", supportedGame.SafeName, saveHeader.GetString("scenario").Substring(saveHeader.GetString("scenario").LastIndexOf('\\') + 1).ToLower());
                                                    fatxGamesave.MapImage   = libertyImagePath;
                                                    fatxGamesave.GamerTag   = saveHeader.GetString("gamer tag");
                                                    fatxGamesave.ServiceTag = saveHeader.GetString("service tag");

                                                    Dispatcher.Invoke(new Action(delegate
                                                    {
                                                        // Add to ObservableCollection, has to be invoked to do this
                                                        PageViewModel.FATXGameSaves.Add(fatxGamesave);
                                                    }));
                                                }
                                            }
                                            catch { }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            };
            bw.RunWorkerCompleted += (o, args) =>
            {
                // Setup Pending UI stuff
                Dispatcher.Invoke(new Action(delegate { progressPendingRefresh.Visibility = System.Windows.Visibility.Collapsed; }));
            };
            bw.RunWorkerAsync();
        }
Example #12
0
        ///////////////////////////////////////////
        //SPITFIRE1337 MODS
        ///////////////////////////////////////////
        public IEnumerable <IResult> WriteSaveXbox()
        {
            if (this.SaveFile == null)
            {
                yield break;
            }

            string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

            File.Delete(path + "/savegame.sav");

            //MessageBox.Show("A save file box will now appear, please select a EXISTING XBOX SAVE to overwrite. I can not emphasize this enough, ALWAYS KEEP A WORKING BACKUP. Once you have a backup press ok to continue");

            var saveFile = this.SaveFile;

            yield return(new DelegateResult(() =>
            {
                Endian endian;
                this.General.ExportData(saveFile.SaveGame, out endian);
                this.CurrencyOnHand.ExportData(saveFile.SaveGame);
                this.Backpack.ExportData(saveFile.SaveGame);
                this.Bank.ExportData(saveFile.SaveGame);


                using (var output = File.Create(path + "/savegame.sav"))
                {
                    saveFile.Endian = endian;
                    saveFile.Serialize(output);
                }
            }).Rescue().Execute(
                             x =>
                             new MyMessageBox("An exception was thrown (press Ctrl+C to copy this text):\n\n" + x.ToString(), "Error")
                             .WithIcon(MessageBoxImage.Error).AsCoroutine()));

            string fileName = null;

            MySaveFileResult ofr;

            ofr = new MySaveFileResult()
                  .PromptForOverwrite()
                  .FilterFiles(
                ffc => ffc.AddFilter("sav", true)
                .WithDescription("Borderlands 2 Save Files")
                .AddAllFilesFilter())
                  .WithFileDo(s => fileName = s);

            if (string.IsNullOrEmpty(this._SavePath) == false &&
                Directory.Exists(this._SavePath) == true)
            {
                ofr = ofr.In(this._SavePath);
            }

            yield return(ofr);

            if (fileName == null)
            {
                yield break;
            }
            if (File.Exists(fileName))
            {
                File.WriteAllBytes(fileName, Properties.Resources.Save0001);
            }
            else
            {
                File.Delete(fileName);
                File.WriteAllBytes(fileName, Properties.Resources.Save0001);
            }
            yield return(new DelegateResult(() =>
            {
                string profileid = this.General.Profileid;
                DJsIO io = new DJsIO(fileName, DJFileMode.Open, true);

                io.Position = 0x371;
                io.WriteHexString(profileid);
                io.Close();
            }).Rescue().Execute(
                             x =>
                             new MyMessageBox("An exception was thrown (press Ctrl+C to copy this text):\n\n" + x.ToString(), "Error")
                             .WithIcon(MessageBoxImage.Error).AsCoroutine()));

            yield return(new DelegateResult(() =>
            {
                STFSPackage stfs = new STFSPackage(fileName, null);
                FileEntry item = stfs.GetFile("savegame.sav"); //Get's the account file



                if (!item.Replace(path + "\\savegame.sav"))
                {
                    //If Not xent.Extract(Application.StartupPath + "\" + "savegame.sav") Then
                    //MessageBoxEx.Show("Extraction Failed!", "Failed!", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                    throw new Exception("Failed to insert save file to xbox save. Please use a program like modio or horizon to insert your save");
                }
                else
                {
                    //MessageBox.Show("File Inserted");

                    //If Not  Then

                    //End If
                    //MessageBoxEx.Show("Extraction Complete!", "Complete!", MessageBoxButtons.OK, MessageBoxIcon.Information)
                }
                if (!File.Exists(path + "/kv.bin"))
                {
                    File.WriteAllBytes(path + "/kv.bin", Properties.Resources.KV);
                }



                stfs.FlushPackage(new RSAParams(path + "/kv.bin"));
                stfs.CloseIO();
            }).Rescue().Execute(
                             x =>
                             new MyMessageBox("An exception was thrown (press Ctrl+C to copy this text):\n\n" + x.ToString(), "Error")
                             .WithIcon(MessageBoxImage.Error).AsCoroutine()));
        }
Example #13
0
        public IEnumerable <IResult> ReadSave()
        {
            string fileName = null;

            MyOpenFileResult ofr;

            ofr = new MyOpenFileResult()
                  .FilterFiles(
                ffc => ffc.AddFilter("sav", true)
                .WithDescription("Borderlands 2 Save Files")
                .AddAllFilesFilter())
                  .WithFileDo(s => fileName = s);

            if (string.IsNullOrEmpty(this._SavePath) == false &&
                Directory.Exists(this._SavePath) == true)
            {
                ofr = ofr.In(this._SavePath);
            }

            yield return(ofr);

            if (fileName == null)
            {
                yield break;
            }

            ///////////////////////////////////////////
            //SPITFIRE1337 MODS
            ///////////////////////////////////////////

            string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

            //using (FileStream fs = File.Create(path)) { }
            File.Delete(path + "/mytempsave.sav");
            File.Delete(path + "/savegame.sav");
            File.Copy(fileName, path + "/mytempsave.sav");
            string profileid = "";
            string deviceid  = "";
            string consoleid = "";


            Stream input1 = new FileStream(fileName, FileMode.Open);

            // Ensure that the target does not exist.



            //Stream input = new Stream(fs);
            var check = input1.ReadValueU32(Endian.Big);

            input1.Close();

            if (check == 0x434F4E20)
            {
                //MessageBox.Show("This is a xbox save");

                yield return(new DelegateResult(() =>
                {
                    DJsIO io = new DJsIO(fileName, DJFileMode.Open, true);

                    io.Position = 0x371;
                    profileid = io.ReadHexString(8); //Profile ID
                    io.Close();
                })
                             .Rescue().Execute(
                                 x =>
                                 new MyMessageBox("An exception was thrown (press Ctrl+C to copy):\n\n" + x.ToString(),
                                                  "Error")
                                 .WithIcon(MessageBoxImage.Error).AsCoroutine()));


                STFSPackage xPackage = new STFSPackage(fileName, null);
                FileEntry   xent     = (FileEntry)xPackage.GetFile("savegame.sav");

                if (!xent.Extract(path + "/savegame.sav"))
                {
                    //MessageBoxEx.Show("Extraction Failed!", "Failed!", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                    //xboxextract.ReportProgress(200, "Extraction Failed");
                    //Thread.Sleep(2000);
                    //Return
                    MessageBox.Show("Could not extract savegame.sav. Please use a program like modio or horizon to extract your savegame.sav");
                }
                else
                {
                    fileName = path + "/savegame.sav";
                    //MessageBox.Show("File extracted");
                    //Thread.Sleep(2000);
                    //MessageBoxEx.Show("Extraction Complete!", "Complete!", MessageBoxButtons.OK, MessageBoxIcon.Information)
                }
            }
            else
            {
                profileid = "0";
                deviceid  = "0";
                consoleid = "0";
            }

            yield return(new DelegateResult(() =>
            {
                FileFormats.SaveFile saveFile;
                using (var input = File.OpenRead(fileName))
                {
                    saveFile = FileFormats.SaveFile.Deserialize(input, FileFormats.SaveFile.DeserializeSettings.None);
                }

                this.SaveFile = saveFile;
                this.General.ImportData(saveFile.SaveGame, saveFile.Endian, profileid, deviceid, consoleid);
                this.CurrencyOnHand.ImportData(saveFile.SaveGame);
                this.Backpack.ImportData(saveFile.SaveGame);
                this.Bank.ImportData(saveFile.SaveGame);
            })
                         .Rescue <DllNotFoundException>().Execute(
                             x => new MyMessageBox("Failed to load save: " + x.Message, "Error")
                             .WithIcon(MessageBoxImage.Error).AsCoroutine())
                         .Rescue <FileFormats.SaveFormatException>().Execute(
                             x => new MyMessageBox("Failed to load save: " + x.Message, "Error")
                             .WithIcon(MessageBoxImage.Error).AsCoroutine())
                         .Rescue <FileFormats.SaveCorruptionException>().Execute(
                             x => new MyMessageBox("Failed to load save: " + x.Message, "Error")
                             .WithIcon(MessageBoxImage.Error).AsCoroutine())
                         .Rescue().Execute(
                             x =>
                             new MyMessageBox("An exception was thrown (press Ctrl+C to copy):\n\n" + x.ToString(),
                                              "Error")
                             .WithIcon(MessageBoxImage.Error).AsCoroutine()));
            ///////////////////////////////////////////
            //END SPITFIRE1337 MODS
            ///////////////////////////////////////////
        }
Example #14
0
        private bool ProcessFiles()
        {
            var counter = 0;
            var success = 0;

            foreach (var file in inputFiles.Where(File.Exists).TakeWhile(file => !backgroundWorker1.CancellationPending))
            {
                try
                {
                    if (VariousFunctions.ReadFileType(file) != XboxFileType.STFS)
                    {
                        continue;
                    }
                    Song.NewSong();
                    Song.ReplaceGenreWithSub = useSubgenreInsteadOfGenreToolStripMenuItem.Checked;

                    try
                    {
                        if (!Directory.Exists(PSFolder))
                        {
                            Directory.CreateDirectory(PSFolder);
                        }
                        counter++;
                        Parser.ExtractDTA(file);
                        Parser.ReadDTA(Parser.DTA);
                        if (Parser.Songs.Count > 1)
                        {
                            Log("File " + Path.GetFileName(file) + " is a pack, try dePACKing first, skipping...");
                            continue;
                        }
                        if (!Parser.Songs.Any())
                        {
                            Log("There was an error processing the songs.dta file");
                            continue;
                        }
                        if (loadDTA())
                        {
                            Log("Loaded and processed songs.dta file for song #" + counter + " successfully");
                            Log("Song #" + counter + " is " + Song.Artist + " - " + Song.Name);
                        }
                        else
                        {
                            return(false);
                        }

                        var songfolder = PSFolder + Tools.CleanString(Song.Artist, false) + " - " + Tools.CleanString(Song.Name, false) + "\\";
                        if (!Directory.Exists(songfolder))
                        {
                            Directory.CreateDirectory(songfolder);
                        }
                        var internal_name = Parser.Songs[0].InternalName;

                        var xPackage = new STFSPackage(file);
                        if (!xPackage.ParseSuccess)
                        {
                            Log("Failed to parse '" + Path.GetFileName(file) + "'");
                            Log("Skipping this file");
                            continue;
                        }
                        var xArt = xPackage.GetFile("songs/" + internal_name + "/gen/" + internal_name + "_keep.png_xbox");
                        if (xArt != null)
                        {
                            var newart = songfolder + "album.png_xbox";
                            if (xArt.ExtractToFile(newart))
                            {
                                Log("Extracted album art file " + internal_name + "_keep.png_xbox successfully");
                                fromXbox(newart);
                            }
                            else
                            {
                                Log("There was a problem extracting the album art file");
                            }
                        }
                        else
                        {
                            Log("WARNING: Did not find album art file in that CON file");
                        }
                        var xMIDI = xPackage.GetFile("songs/" + internal_name + "/" + internal_name + ".mid");
                        if (xMIDI != null)
                        {
                            var newmidi = songfolder + "notes.mid";
                            if (xMIDI.ExtractToFile(newmidi))
                            {
                                Log("Extracted MIDI file " + internal_name + ".mid successfully");
                                ProcessMidi(newmidi);
                            }
                            else
                            {
                                Log("There was a problem extracting the MIDI file");
                                Log("Skipping this song...");
                                xPackage.CloseIO();
                                continue;
                            }
                        }
                        else
                        {
                            Log("ERROR: Did not find a MIDI file in that CON file!");
                            Log("Skipping this song...");
                            xPackage.CloseIO();
                            continue;
                        }
                        var xMOGG = xPackage.GetFile("songs/" + internal_name + "/" + internal_name + ".mogg");
                        if (xMOGG != null)
                        {
                            var newmogg = songfolder + internal_name + ".mogg";
                            if (radioSeparate.Checked)
                            {
                                xPackage.CloseIO();
                                SeparateAudio(file, newmogg, songfolder);
                            }
                            else if (radioDownmix.Checked)
                            {
                                xPackage.CloseIO();
                                DownMixAudio(file, songfolder);
                            }
                            else
                            {
                                var msg = "Extracting audio file " + (radioAudacity.Checked ? "to send to Audacity" : "and leaving it as is");
                                Log(msg);
                                var mData = xMOGG.Extract();
                                if (mData != null && mData.Length > 0)
                                {
                                    Log("Successfully extracted audio file '" + Path.GetFileName(newmogg) + "'");
                                    if (radioAudacity.Checked)
                                    {
                                        Log("Sending audio file to Audacity now");
                                        Tools.DecM(mData, false, false, DecryptMode.ToFile, newmogg);
                                        Log(Tools.SendtoAudacity(newmogg));
                                    }
                                    else
                                    {
                                        Tools.WriteOutData(Tools.ObfM(mData), newmogg);
                                    }
                                }
                                else
                                {
                                    Log("There was a problem extracting the audio file");
                                    Log("Skipping this song...");
                                    xPackage.CloseIO();
                                    continue;
                                }
                            }
                        }
                        else
                        {
                            Log("ERROR: Did not find an audio file in that CON file!");
                            Log("Skipping this song...");
                            xPackage.CloseIO();
                            continue;
                        }
                        xPackage.CloseIO();

                        if (!Directory.Exists(songfolder))
                        {
                            Directory.CreateDirectory(songfolder);
                        }
                        Song.WriteINIFile(songfolder, !chkNoC3.Checked);

                        var banner = Application.StartupPath + "\\res\\phaseshift\\banner.png";
                        if (File.Exists(banner) && !chkNoC3.Checked)
                        {
                            Tools.DeleteFile(songfolder + "banner.png");
                            File.Copy(banner, songfolder + "banner.png");
                        }
                        var icon = Application.StartupPath + "\\res\\phaseshift\\c3.png";
                        if (File.Exists(icon) && !chkNoC3.Checked)
                        {
                            Tools.DeleteFile(songfolder + "ccc.png");
                            File.Copy(icon, songfolder + "ccc.png");
                        }

                        success++;
                        if (!chkRAR.Checked || backgroundWorker1.CancellationPending)
                        {
                            continue;
                        }
                        var archive = Path.GetFileName(file);
                        archive = archive.Replace(" ", "").Replace("-", "_").Replace("\\", "").Replace("'", "").Replace(",", "").Replace("_rb3con", "");
                        archive = Tools.CleanString(archive, false);
                        archive = PSFolder + archive + "_ps.rar";

                        var arg = "a -m5 -ep1 -r \"" + archive + "\" \"" + songfolder.Substring(0, songfolder.Length - 1) + "\"";
                        Log("Creating RAR archive");

                        Log(Tools.CreateRAR(rar, archive, arg)? "Created RAR archive successfully" : "RAR archive creation failed");
                    }
                    catch (Exception ex)
                    {
                        Log("There was an error: " + ex.Message);
                        Log("Attempting to continue with the next file");
                    }
                }
                catch (Exception ex)
                {
                    Log("There was a problem accessing that file");
                    Log("The error says: " + ex.Message);
                }
            }
            Log("Successfully processed " + success + " of " + counter + " files");
            return(true);
        }