public TransparentSocksConnection(Socket client, DebugWriter debug, ConnectionTracker connectionTracker, ConfigureProxySocket configureProxySocket)
 {
     this.client = client;
     this.debug = debug;
     this.connectionTracker = connectionTracker;
     this.configureProxySocket = configureProxySocket;
 }
Example #2
0
        static void Main(string[] args)
        {
            List <IAnnouncer> announcers = new List <IAnnouncer>
            {
                new Book(),
                new Table()
            };

            //IWriter writer = new ConsoleWriter();
            //IAnnouncer book = announcers[0];
            IWriter consoleWriter = new ConsoleWriter();
            IWriter debugWriter   = new DebugWriter();

            announcers[0].AddWriter(consoleWriter);
            announcers[0].AddWriter(debugWriter);

            announcers[1].AddWriter(consoleWriter);
            announcers[1].AddWriter(debugWriter);

            //book.Write();

            foreach (IAnnouncer announcer in announcers)
            {
                //announcer.Write(Console.Out);

                //announcer.Write(writer);

                announcer.Write();
            }

            Console.ReadKey(true);
        }
Example #3
0
        public static void Startup()
        {
            // 自定义日志处理实例
            if (string.IsNullOrEmpty(LogFilePath))
            {
                LogFilePath = GenDefaultLogFilePath();
            }

            try
            {
                s_writer = new DebugWriter(LogFilePath);
            }
            catch (Exception e)
            {
                Debug.LogWarning("文件操作失败 " + e.ToString());
                if (s_writer != null)
                {
                    s_writer.Dispose();
                }
                return;
            }

            Application.logMessageReceived         -= LogCallback;
            Application.logMessageReceived         += LogCallback;
            Application.logMessageReceivedThreaded -= LogCallback;
            Application.logMessageReceivedThreaded += LogCallback;
        }
Example #4
0
        protected string TokenizeToString(string text, ITokenizer <TTokenClass> tokenizer)
        {
            var    tokens = this.Tokenize(text, tokenizer);
            string result = DebugWriter.WriteTokens <TTokenClass, TTokenType>(tokens);

            return(result);
        }
Example #5
0
        void ComponentDispatcher_ThreadPreprocessMessage(ref MSG msg, ref bool handled)
        {
            if (msg.message == Hotkey.WM_HOTKEY)
            {
                try
                {
                    GameManagerAccounts Main = GameManagerAccountHelper.Current;

                    foreach (GameManagerAccounts Acc in GameManager.Instance.Accounts.NotMainAccount())
                    {
                        Point ClientRect = DiabloIII.FromD3toScreenCoords(DiabloIII.Player(Acc.DiabloIII).Point(), Main.Player.Point());

                        //PInvokers.ClientToScreen(Acc.DiabloIII.Process.MainWindowHandle, ref f);

                        if (Config.Get <FKConfig>().General.Macros.UseForceMove)
                        {
                            VirtualInput.KeyClick(Acc.DiabloIII.Process.MainWindowHandle, ClientRect);
                        }
                        else
                        {
                            VirtualInput.LeftClick(Acc.DiabloIII.Process.MainWindowHandle, ClientRect);
                        }
                    }
                }

                catch (Exception e)
                {
                    DebugWriter.Write(e);
                }
            }
        }
 public void Init(HttpApplication context)
 {
     DebugWriter.Write("DebugHttpModule::Init");
     context.BeginRequest += new EventHandler(OnBeginRequest);
     context.EndRequest   += new EventHandler(OnEndRequest);
     context.LogRequest   += new EventHandler(OnLogRequest);
 }
Example #7
0
        public void Load()
        {
#if DEBUG
            DebugWriter.WriteLine("-> LandProvider::Load");
            var timer = new Stopwatch();
            timer.Start();
#endif

            Stream          stream          = File.Open(Config.StoragePath + "/land.bin", FileMode.Open);
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            try
            {
                var land = (Land)binaryFormatter.Deserialize(stream);
                _land.Naam   = land.Naam;
                _land.Id     = land.Id;
                _land.Regios = land.Regios;
            }
            catch (SerializationException)
            {
                throw;
            }
            finally
            {
                stream.Close();
            }

#if DEBUG
            timer.Stop();
            TimeSpan timeTaken = timer.Elapsed;
            DebugWriter.WriteLine("<- LandProvider::Load: " + timeTaken.ToString(@"m\:ss\.fff"));
#endif
        }
Example #8
0
        private void HaalStratenOp(StratenProvider stratenProvider)
        {
#if DEBUG
            DebugWriter.WriteLine("-> LandProvider::HaalStratenOp");
            var timer = new Stopwatch();
            timer.Start();
#endif
            foreach (var r in _land.Regios.Values)
            {
                foreach (var p in r.Provincies.Values)
                {
                    foreach (var g in p.Gemeenten.Values)
                    {
                        var straten = stratenProvider.GetStraten(g.Id);
                        foreach (var straat in straten)
                        {
                            g.Straten.Add(straat, new Straat
                            {
                                Id       = g.Id,
                                Naam     = straat,
                                Gemeente = g
                            });
                        }
                    }
                }
            }
#if DEBUG
            timer.Stop();
            TimeSpan timeTaken = timer.Elapsed;
            DebugWriter.WriteLine("<- LandProvider::HaalStratenOp: " + timeTaken.ToString(@"m\:ss\.fff"));
#endif
        }
Example #9
0
        public void IUpdate()
        {
            try
            {
                if (!Helpers.UIObjects.GreaterRift.TryGetValue <UXItemsControl>())
                {
                    GameManager.Instance.GManager.GRef.D3OverlayControl.Delete <Templates.Rifts.GreaterRift>();
                    return;
                }

                var Temp = Helpers.UIObjects.GreaterRift.TryGetPoint <UXItemsControl>(Enigma.D3.OffsetConversion.UXControlRect);

                if (!Temp.Equals(_TempPoint))
                {
                    _TempPoint = Temp;
                    UpdateRect();
                }

                SoulsCaptured();
                GetTimeLeft();
            }

            catch (Exception e)
            {
                DebugWriter.Write(e);
            }
        }
 public TransparentSocksConnection(Socket client, DebugWriter debug, ConnectionTracker connectionTracker, ConfigureProxySocket configureProxySocket)
 {
     this.client               = client;
     this.debug                = debug;
     this.connectionTracker    = connectionTracker;
     this.configureProxySocket = configureProxySocket;
 }
Example #11
0
        public void EnumerateMultibox()
        {
            try
            {
                if (!GameManagerAccountHelper.Current.LevelAreaHelper.State())
                {
                    return;
                }

                var ACDContainer = ActorCommonData.Container;
                ACDContainer.TakeSnapshot();

                foreach (var item in ACDContainer.GetBufferDump(ref GameManagerAccountHelper.Current.Gamestate.ACDBuffer))
                {
                    var Actor = item.Create();

                    if (Actor.x000_Id == -1)
                    {
                        continue;
                    }

                    if ((Actor.x184_ActorType == ActorType.Item) && (int)Actor.x114_ItemLocation == -1)     // -1 == Ground items //  && Actor.x090_ActorSnoId != -1 && Actor.x27C_WorldId != 0 && Actor.x0D0_WorldPosX != 0 && (Actor.x0B0_GameBalanceType == GameBalanceType.Items &&
                    {
                        ItemFilter.Enumerate(Actor);
                    }
                }

                ACDContainer.FreeSnapshot();
            }

            catch (Exception e)
            {
                DebugWriter.Write(e);
            }
        }
Example #12
0
        public IActionResult Create([FromBody] HodoorItem hodoorItem)
        {
            if (hodoorItem == null)
            {
                return(BadRequest());
            }

            _debugWriter = new DebugWriter();

            _context.HodoorItems.Add(hodoorItem);
            _context.SaveChanges();

            _debugWriter.Write(string.Format("Created HodoorItem with ID: {0}", hodoorItem.Id));

            try
            {
                _hub.Clients.All.InvokeAsync("UpdateSpecific", "Hodoor", hodoorItem.Command, hodoorItem);
            }
            catch (Exception e)
            {
                _debugWriter.Write(e.Message);
            }

            return(CreatedAtRoute("GetHodoor", new { id = hodoorItem.Id }, hodoorItem));
        }
Example #13
0
        /// <summary>
        /// Get the context modification scope for the current process.  This will be 'Process' if changes should
        /// only affect the current PowerShell session, or 'CurrentUser'  if any changes should be global.
        /// </summary>
        /// <param name="writer">A writer to write debug messages</param>
        /// <returns>'Process'  if all changes should only impact the current session, or 'CurrentUser' if
        /// changes should be global.</returns>
        public static ContextModificationScope GetContextModificationScopeForProcess(DebugWriter writer)
        {
            ContextModificationScope scope = AzureSession.Instance.ARMContextSaveMode == ContextSaveMode.Process ? ContextModificationScope.Process : ContextModificationScope.CurrentUser;

            try
            {
                writer(Resources.AutosaveSettingFromSession, scope);
                var  autoSaveSetting = Environment.GetEnvironmentVariable(AzureRmProfileConstants.ProfileAutoSaveVariable);
                bool autoSaveEnabled = false;
                if (autoSaveSetting != null && bool.TryParse(autoSaveSetting, out autoSaveEnabled))
                {
                    scope = autoSaveEnabled ? ContextModificationScope.CurrentUser : ContextModificationScope.Process;
                    writer(Resources.AutosaveSettingFromEnvironment, AzureRmProfileConstants.ProfileAutoSaveVariable, autoSaveSetting);
                }
                else
                {
                    writer(Resources.CouldNotRetrieveAutosaveSetting, AzureRmProfileConstants.ProfileAutoSaveVariable);
                }
            }
            catch (Exception exception)
            {
                writer(Resources.ErrorRetrievingAutosaveSetting, AzureRmProfileConstants.ProfileAutoSaveVariable, exception);
            }

            return(scope);
        }
Example #14
0
        public Dictionary <int, Gemeente> GetGemeenten()
        {
#if DEBUG
            DebugWriter.WriteLine("-> GemeentenProvider::GetGemeenten");
            var timer = new Stopwatch();
            timer.Start();
#endif
            Dictionary <int, Gemeente> gemeenten = new Dictionary <int, Gemeente>();

            using GenericParser gemeentenReader = new GenericParser(Config.Path + "/" + Config.Gemeentenamen)
                  {
                      ColumnDelimiter   = ';',
                      FirstRowHasHeader = true,
                      MaxBufferSize     = 4096
                  };
            while (gemeentenReader.Read())
            {
                if (gemeentenReader[2].Trim() != _taalCode)
                {
                    continue;
                }
                gemeenten.Add(int.Parse(gemeentenReader[1].Trim()), new Gemeente {
                    NaamId = int.Parse(gemeentenReader[0].Trim()), Id = int.Parse(gemeentenReader[1].Trim()), TaalCode = gemeentenReader[2].Trim(), Naam = gemeentenReader[3].Trim()
                });
            }
            DebugWriter.WriteLine("Gemeenten: " + gemeenten.Values.Count);

#if DEBUG
            timer.Stop();
            TimeSpan timeTaken = timer.Elapsed;
            DebugWriter.WriteLine("<- GemeentenProvider::GetGemeenten: " + timeTaken.ToString(@"m\:ss\.fff"));
#endif
            return(gemeenten);
        }
Example #15
0
        private static void TokenizeFileImplementation <TToken, TTokenType, TTokenizer>(DeployFilesFixture fixture, string name, string language)
            where TTokenizer : ITokenizer <TToken>, new() where TToken : IToken <TTokenType>
        {
            string testFile     = fixture.GetDestinationPath(name);
            string baselineFile = testFile + ".tokens";

            string        text         = fixture.LoadDestinationFile(name);
            ITextProvider textProvider = new TextStream(text);
            var           tokenizer    = new TTokenizer();

            var    tokens = tokenizer.Tokenize(textProvider, 0, textProvider.Length);
            string actual = DebugWriter.WriteTokens <TToken, TTokenType>(tokens);

            if (_regenerateBaselineFiles)
            {
                // Update this to your actual enlistment if you need to update baseline
                string enlistmentPath = @"F:\RTVS\src\R\Support\Test\" + language + @"\Files\Tokenization";
                baselineFile = Path.Combine(enlistmentPath, Path.GetFileName(testFile)) + ".tokens";

                TestFiles.UpdateBaseline(baselineFile, actual);
            }
            else
            {
                TestFiles.CompareToBaseLine(baselineFile, actual);
            }
        }
Example #16
0
        public static void SetConsoleOutputToTestLog(bool reset = false)
        {
            if (reset)
            {
                _outputSet = false;
            }

            if (!_outputSet)
            {
                lock (_outputLock) {
                    if (!_outputSet)
                    {
                        _outputSet = true;
                        string logPath = VsOutLogPath;

                        DebugWriter.SetConsoleOut(
                            writeToOrigConsoleOutStill: true,
                            writeToLogFilePath: logPath,
                            deleteLogFileContentsFirst: true);

                        $@"{nameof(XUnitTestBase)}.{nameof(SetConsoleOutputToTestLog)} called at '{DateTime.Now}'

Log path: ""{logPath}""

".Print();
                    }
                }
            }
        }
Example #17
0
        public void Export(string gemeente)
        {
#if DEBUG
            DebugWriter.WriteLine("-> ConsoleExporter::Export");
            var timer = new Stopwatch();
            timer.Start();
#endif
            foreach (var r in _land.Regios.Values)
            {
                foreach (var p in r.Provincies.Values)
                {
                    foreach (var g in p.Gemeenten.Values)
                    {
                        if (g.Naam == gemeente)
                        {
                            var currentDirName = Directory.GetCurrentDirectory();
                            var dirName        = "./" + _land.Naam + "/" + r.Naam + "/" + p.Naam + "/" + g.Naam;
                            foreach (var s in g.Straten)
                            {
                                Console.WriteLine(dirName + "/" + s.Value.Naam);
                            }
                        }
                    }
                }
            }
#if DEBUG
            timer.Stop();
            TimeSpan timeTaken = timer.Elapsed;
            DebugWriter.WriteLine("<- ConsoleExporter::Export: " + timeTaken.ToString(@"m\:ss\.fff"));
#endif
        }
Example #18
0
        public void Read()
        {
            // Precompiler: in Debug mode is code aanwezig, anders niet
#if DEBUG
            DebugWriter.WriteLine("-> LandProvider::Read");
            var timer = new Stopwatch();
            timer.Start();
#endif
            _regiosProvider = new RegiosProvider(_land);
            _regiosProvider.Get();

            /*
             * foreach (var regio in _land.Regios.Values)
             * {
             *  regio.Read(_land);
             * }
             */
            _stratenProvider = new StratenProvider();
            HaalStratenOp(_stratenProvider);

#if DEBUG
            timer.Stop();
            TimeSpan timeTaken = timer.Elapsed;
            DebugWriter.WriteLine("<- LandProvider::Read: " + timeTaken.ToString(@"m\:ss\.fff"));
#endif
        }
Example #19
0
        public void CloseRift()
        {
            CurrentRift  = null;
            RiftIsActive = false;
            StopTimer();

            try
            {
                foreach (var x in GameManager.Instance.Accounts)
                {
                    foreach (int Key in RiftLevels)
                    {
                        if (x.GameData().AreaLevels.ContainsKey(Key))
                        {
                            x.GameData().AreaLevels.Remove(Key);
                        }
                    }

                    //  x.LevelAreaContainer. Check if Area == Rift.Level
                }
            }

            catch (Exception e)
            {
                DebugWriter.Write(e);
            }
        }
Example #20
0
            public static void UIThread(Action action, bool Invoke = true)
            {
                try
                {
                    var dispatcher = Application.Current.Dispatcher;
                    if (dispatcher.CheckAccess())
                    {
                        action.Invoke();
                    }
                    else
                    {
                        if (!Invoke)
                        {
                            dispatcher.BeginInvoke(action);
                        }
                        else
                        {
                            dispatcher.Invoke(action);
                        }
                    }
                }

                catch (Exception e)
                {
                    DebugWriter.Write(e);
                }
            }
Example #21
0
        public void Persist()
        {
#if DEBUG
            DebugWriter.WriteLine("-> LandExporter::Persist");
            var timer = new Stopwatch();
            timer.Start();
#endif

            Stream          stream          = File.Open(Config.StoragePath + "/land.bin", FileMode.Create);
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            try
            {
                binaryFormatter.Serialize(stream, _land);
            }
            catch (SerializationException)
            {
                throw;
            }
            finally
            {
                stream.Close();
            }

#if DEBUG
            timer.Stop();
            TimeSpan timeTaken = timer.Elapsed;
            DebugWriter.WriteLine("<- LandExporter::Persist: " + timeTaken.ToString(@"m\:ss\.fff"));
#endif
        }
Example #22
0
        public void AddTask()
        {
            if (MainBar != null)
            {
                return;
            }

            MainBar     = Add <MainBar>("MainBar");
            ItemOverlay = Add <ItemOverlaySimple>("ItemOverlaySimple");
            Information = Add <Information>("Information");

            try
            {
                //if (Config.Get<FKConfig>().General.MiniMapSettings.Enabled)
                //AddWPF<MinimapNotify>("Minimap");
                // if (Config.Get<FKConfig>().General.MiniMapSettings.LargeMap)
                //    AddWPF<LargeMapNotify>("LargeMap");
                if (Config.Get <FKConfig>().General.Misc.Inventory)
                {
                    Add <Templates.Inventory.Inventory>("Inventory");
                }

                // AddWPF<Templates.ActorHelper.ActorHelperObserver>("ActorHelper");
            }

            catch (Exception e)
            {
                DebugWriter.Write(e);
            }

            //Add<FindersKeepers.Templates.ActorHelperDebug>("Debug");

            Add <FindersKeepers.Templates.Debug>("Debug");
            //Add<Templates.Rifts.GemUpgrade>("GemUpgrade");
        }
Example #23
0
        public virtual void TryUpdate()
        {
            foreach (FKControl c in FKControls)
            {
                try
                {
                    c.UpdateControl();
                }

                catch (Exception e)
                {
                    DebugWriter.Write(e);
                }
            }

            if (ItemsToAdd.Count != 0)
            {
                Extensions.Execute.UIThread(() => ItemsToAdd.ForEach(x => { FKControls.Add(x); ActiveControls.Add(x.Name); }));
                ItemsToAdd.Clear();
            }

            if (ItemsToRemove.Count != 0)
            {
                Extensions.Execute.UIThread(() => ItemsToRemove.ForEach(x => { FKControls.Remove(x); ActiveControls.Remove(x.Name); }));
                ItemsToRemove.Clear();
            }
        }
        public void IncrementalParse_Whitespace()
        {
            CssTree     doc    = new CssTree(null);
            DebugWriter writer = new DebugWriter();

            // Start with some rules
            doc.TextProvider = new StringTextProvider("a { } b { }");
            Assert.AreEqual(2, doc.StyleSheet.Children.Count);
            string origTree = writer.Serialize(doc.TextProvider, doc.StyleSheet);

            // Add space between them
            doc.OnTextChange(new StringTextProvider("a { } \r\n b { }"), 6, 0, 3);
            Assert.AreEqual(2, doc.StyleSheet.Children.Count);
            Assert.AreEqual(origTree, writer.Serialize(doc.TextProvider, doc.StyleSheet));

            // Delete spaces between them
            doc.OnTextChange(new StringTextProvider("a { } b { }"), 6, 3, 0);
            Assert.AreEqual(2, doc.StyleSheet.Children.Count);
            Assert.AreEqual(origTree, writer.Serialize(doc.TextProvider, doc.StyleSheet));

            // Change all the text, but only really add one more space
            doc.OnTextChange(new StringTextProvider("a { } b {  }"), 0, 11, 12);
            Assert.AreEqual(2, doc.StyleSheet.Children.Count);
            Assert.AreEqual(origTree, writer.Serialize(doc.TextProvider, doc.StyleSheet));
        }
Example #25
0
 public LogConnection(TcpClient client, DebugWriter debug, ConnectionTracker connectionTracker, Natter natter)
 {
     this.client            = client;
     this.debug             = debug;
     this.connectionTracker = connectionTracker;
     this.natter            = natter;
     stream = client.GetStream();
 }
Example #26
0
        protected AbstractLogEvent(string source, DebugWriter method)
        {
            Contract.Requires(!string.IsNullOrEmpty(source));
            Contract.Requires(method != null);

            Source       = source;
            WriterMethod = method;
        }
Example #27
0
        public TransparentSocksServer(DebugWriter debug, IDictionary<string, IService> services)
        {
            this.debug = debug;
            this.services = services;

            transparentSocksServer = new TcpListener(IPAddress.Any, Settings.Default.SocksPort);
            transparentSocksServer.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
        }
Example #28
0
        public TransparentSocksServer(DebugWriter debug, IDictionary <string, IService> services)
        {
            this.debug    = debug;
            this.services = services;

            transparentSocksServer = new TcpListener(IPAddress.Any, Settings.Default.SocksPort);
            transparentSocksServer.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
        }
Example #29
0
 public LogConnection(TcpClient client, DebugWriter debug, ConnectionTracker connectionTracker, Natter natter)
 {
     this.client = client;
     this.debug = debug;
     this.connectionTracker = connectionTracker;
     this.natter = natter;
     stream = client.GetStream();
 }
Example #30
0
        public Natter(DebugWriter debug, IDictionary <string, IService> services)
        {
            this.debug    = debug;
            this.services = services;

            tunTapDevice = new TunTapDevice(Settings.Default.TunTapDevice);
            tap          = tunTapDevice.Stream;
        }
Example #31
0
        public override async Task Invoke(IOwinContext context)
        {
            DebugWriter.Write("OwinMiddleware:: Incoming");

            await _next.Invoke(context);

            DebugWriter.Write("OwinMiddleware:: Outgoing");
        }
Example #32
0
        public LogServer(DebugWriter debug, IDictionary<string, IService> services)
        {
            this.debug = debug;
            this.services = services;

            logServer = new TcpListener(IPAddress.Loopback, Settings.Default.LogPort);
            logServer.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
        }
Example #33
0
        public void Configuration(IAppBuilder app)
        {
            DebugWriter.Write("OwinStartup::Configuration");

            app.Use <DebugOwinMiddleware>();

            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
        }
Example #34
0
        public TransparentUdpServer(DebugWriter debug, IDictionary <string, IService> services)
        {
            this.debug    = debug;
            this.services = services;

            transparentSocksServer = new UdpClient(new IPEndPoint(IPAddress.Any, Settings.Default.SocksPort));
            transparentSocksServer.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
        }
Example #35
0
        public static void Write(string name, object value)
        {
            if (StringEx.IsNullOrWhiteSpace(name))
                throw new ArgumentNullException("name");

            using (var writer = new DebugWriter())
            {
                Write(name, value, writer);
            }
        }
Example #36
0
 public void SetUp()
 {
     _customer = new Customer("123", new PersonName("Samuel"), "021");
     _writer = new DebugWriter();
 }
Example #37
0
        /// <summary>
        /// Decodes a stream of Ogg Vorbis data into wav file format.
        /// </summary>
        /// <returns>
        /// A MemoryStream with the entire decoded stream.
        /// </returns>
        /// <param name='input'>
        /// Ogg Vorbis data to be decoded
        /// </param>
        /// <param name='output'>
        /// <para>Stream to write wav data.</para>
        /// <para>If writeWavHeader is true then this stream must be seekable.</para>
        /// </param>
        /// <param name='writeWavHeader'>
        /// Write wav header in the beginning of the returned stream.
        /// </param>
        public static void DecodeStream(Stream input, Stream output, bool writeWavHeader)
        {
            int convsize = 4096 * 2;
            byte[] convbuffer = new byte[convsize]; // take 8k out of the data segment, not the stack
            long start = output.Position;

            DebugWriter s_err = new DebugWriter();

            if (writeWavHeader && !output.CanSeek)
                throw new ArgumentException("To write wav header, the output stream must be seekable.", "output");

            if (writeWavHeader)
                output.Seek(HEADER_SIZE, SeekOrigin.Current); // reserve place for WAV header

            SyncState oy = new SyncState(); // sync and verify incoming physical bitstream
            StreamState os = new StreamState(); // take physical pages, weld into a logical stream of packets
            Page og = new Page(); // one Ogg bitstream page.  Vorbis packets are inside
            Packet op = new Packet(); // one raw packet of data for decode

            Info vi = new Info();  // struct that stores all the static vorbis bitstream settings
            Comment vc = new Comment(); // struct that stores all the bitstream user comments
            DspState vd = new DspState(); // central working state for the packet->PCM decoder
            Block vb = new Block(vd); // local working space for packet->PCM decode

            int bytes = 0;

            // Decode setup
            oy.init(); // Now we can read pages

            // we repeat if the bitstream is chained
            while (true)
            {
                int eos = 0;

                // grab some data at the head of the stream.  We want the first page
                // (which is guaranteed to be small and only contain the Vorbis
                // stream initial header) We need the first page to get the stream
                // serialno.

                // submit a 4k block to libvorbis' Ogg layer
                int index = oy.buffer(4096);
                bytes = input.Read(oy.data, index, 4096);
                oy.wrote(bytes);

                // Get the first page.
                if (oy.pageout(og) != 1)
                {
                    // have we simply run out of data?  If so, we're done.
                    if (bytes < 4096)
                        break;

                    // error case.  Must not be Vorbis data
                    s_err.WriteLine("Input does not appear to be an Ogg bitstream.");
                }

                // Get the serial number and set up the rest of decode.
                // serialno first; use it to set up a logical stream
                os.init(og.serialno());

                // extract the initial header from the first page and verify that the
                // Ogg bitstream is in fact Vorbis data

                // I handle the initial header first instead of just having the code
                // read all three Vorbis headers at once because reading the initial
                // header is an easy way to identify a Vorbis bitstream and it's
                // useful to see that functionality seperated out.

                vi.init();
                vc.init();
                if (os.pagein(og) < 0)
                {
                    // error; stream version mismatch perhaps
                    s_err.WriteLine("Error reading first page of Ogg bitstream data.");
                }

                if (os.packetout(op) != 1)
                {
                    // no page? must not be vorbis
                    s_err.WriteLine("Error reading initial header packet.");
                }

                if (vi.synthesis_headerin(vc, op) < 0)
                {
                    // error case; not a vorbis header
                    s_err.WriteLine("This Ogg bitstream does not contain Vorbis audio data.");
                }

                // At this point, we're sure we're Vorbis.  We've set up the logical
                // (Ogg) bitstream decoder.  Get the comment and codebook headers and
                // set up the Vorbis decoder

                // The next two packets in order are the comment and codebook headers.
                // They're likely large and may span multiple pages.  Thus we reead
                // and submit data until we get our two pacakets, watching that no
                // pages are missing.  If a page is missing, error out; losing a
                // header page is the only place where missing data is fatal. */

                int i = 0;

                while (i < 2)
                {
                    while (i < 2)
                    {

                        int result = oy.pageout(og);
                        if (result == 0)
                            break; // Need more data
                        // Don't complain about missing or corrupt data yet.  We'll
                        // catch it at the packet output phase

                        if (result == 1)
                        {
                            os.pagein(og); // we can ignore any errors here
                            // as they'll also become apparent
                            // at packetout
                            while (i < 2)
                            {
                                result = os.packetout(op);
                                if (result == 0)
                                    break;
                                if (result == -1)
                                {
                                    // Uh oh; data at some point was corrupted or missing!
                                    // We can't tolerate that in a header.  Die.
                                    s_err.WriteLine("Corrupt secondary header.  Exiting.");
                                }
                                vi.synthesis_headerin(vc, op);
                                i++;
                            }
                        }
                    }
                    // no harm in not checking before adding more
                    index = oy.buffer(4096);
                    bytes = input.Read(oy.data, index, 4096);
                    if (bytes == 0 && i < 2)
                    {
                        s_err.WriteLine("End of file before finding all Vorbis headers!");
                    }
                    oy.wrote(bytes);
                }

                // Throw the comments plus a few lines about the bitstream we're
                // decoding
                {
                    byte[][] ptr = vc.user_comments;
                    for (int j = 0; j < vc.user_comments.Length; j++)
                    {
                        if (ptr [j] == null)
                            break;
                        s_err.WriteLine(vc.getComment(j));
                    }
                    s_err.WriteLine("\nBitstream is " + vi.channels + " channel, " + vi.rate + "Hz");
                    s_err.WriteLine("Encoded by: " + vc.getVendor() + "\n");
                }

                convsize = 4096 / vi.channels;

                // OK, got and parsed all three headers. Initialize the Vorbis
                //  packet->PCM decoder.
                vd.synthesis_init(vi); // central decode state
                vb.init(vd);           // local state for most of the decode

                // so multiple block decodes can
                // proceed in parallel.  We could init
                // multiple vorbis_block structures
                // for vd here

                float[][][] _pcm = new float[1][][];
                int[] _index = new int[vi.channels];
                // The rest is just a straight decode loop until end of stream
                while (eos == 0)
                {
                    while (eos == 0)
                    {

                        int result = oy.pageout(og);
                        if (result == 0)
                            break; // need more data
                        if (result == -1)
                        {
                            // missing or corrupt data at this page position
                            s_err.WriteLine("Corrupt or missing data in bitstream; continuing...");
                        } else
                        {
                            os.pagein(og); // can safely ignore errors at
                            // this point
                            while (true)
                            {
                                result = os.packetout(op);

                                if (result == 0)
                                    break; // need more data
                                if (result == -1)
                                { // missing or corrupt data at this page position
                                    // no reason to complain; already complained above
                                } else
                                {
                                    // we have a packet.  Decode it
                                    int samples;
                                    if (vb.synthesis(op) == 0)
                                    { // test for success!
                                        vd.synthesis_blockin(vb);
                                    }

                                    // **pcm is a multichannel float vector.  In stereo, for
                                    // example, pcm[0] is left, and pcm[1] is right.  samples is
                                    // the size of each channel.  Convert the float values
                                    // (-1.<=range<=1.) to whatever PCM format and write it out

                                    while ((samples = vd.synthesis_pcmout(_pcm, _index)) > 0)
                                    {
                                        float[][] pcm = _pcm [0];
                                        bool clipflag = false;
                                        int bout = (samples < convsize ? samples : convsize);

                                        // convert floats to 16 bit signed ints (host order) and
                                        // interleave
                                        for (i = 0; i < vi.channels; i++)
                                        {
                                            int ptr = i * 2;
                                            //int ptr=i;
                                            int mono = _index [i];
                                            for (int j = 0; j < bout; j++)
                                            {
                                                int val = (int)(pcm [i] [mono + j] * 32767.0);
                                                //        short val=(short)(pcm[i][mono+j]*32767.);
                                                //        int val=(int)Math.round(pcm[i][mono+j]*32767.);
                                                // might as well guard against clipping
                                                if (val > 32767)
                                                {
                                                    val = 32767;
                                                    clipflag = true;
                                                }
                                                if (val < -32768)
                                                {
                                                    val = -32768;
                                                    clipflag = true;
                                                }
                                                if (val < 0)
                                                    val = val | 0x8000;
                                                convbuffer [ptr] = (byte)(val);
                                                convbuffer [ptr + 1] = (byte)((uint)val >> 8);
                                                ptr += 2 * (vi.channels);
                                            }
                                        }

                                        if (clipflag)
                                        {
                                            //s_err.WriteLine("Clipping in frame "+vd.sequence);
                                        }

                                        output.Write(convbuffer, 0, 2 * vi.channels * bout);

                                        vd.synthesis_read(bout); // tell libvorbis how
                                        // many samples we
                                        // actually consumed
                                    }
                                }
                            }
                            if (og.eos() != 0)
                                eos = 1;
                        }
                    }
                    if (eos == 0)
                    {
                        index = oy.buffer(4096);
                        bytes = input.Read(oy.data, index, 4096);
                        oy.wrote(bytes);
                        if (bytes == 0)
                            eos = 1;
                    }
                }

                // clean up this logical bitstream; before exit we see if we're
                // followed by another [chained]

                os.clear();

                // ogg_page and ogg_packet structs always point to storage in
                // libvorbis.  They're never freed or manipulated directly

                vb.clear();
                vd.clear();
                vi.clear();  // must be called last
            }

            // OK, clean up the framer
            oy.clear();
            s_err.WriteLine("Done.");

            if (writeWavHeader)
            {
                long end = output.Position;
                int length = (int)(end - (start + HEADER_SIZE));

                output.Seek(start, SeekOrigin.Begin);
                WriteHeader(output, length, vi.rate, (ushort)16, (ushort)vi.channels);
                output.Seek(end, SeekOrigin.Begin);
            }
        }