using Newtonsoft.Json;
using skyscraper5.Docsis.MacManagement;
using skyscraper5.DsmCc.Descriptors;
using skyscraper5.Dvb.DataBroadcasting.IntModel;
using skyscraper5.Dvb.DataBroadcasting.SkyscraperVfs;
using skyscraper5.Dvb.Descriptors;
using skyscraper5.Dvb.Psi.Model;
using skyscraper5.Dvb.SystemSoftwareUpdate.Model;
using skyscraper5.Dvb.TvAnytime;
using skyscraper5.Mhp.Si;
using skyscraper5.Mhp.Si.Model;
using skyscraper5.Mpeg2.Descriptors;
using skyscraper5.Mpeg2.Psi.Model;
using skyscraper5.Rds.Messages;
using skyscraper5.Scte35;
using skyscraper5.Skyscraper.Gps;
using skyscraper5.Skyscraper.Headless;
using skyscraper5.Skyscraper.IO;
using skyscraper5.Skyscraper.IO.CrazycatStreamReader;
using skyscraper5.Skyscraper.Scraper.Storage.InMemory.Model;
using skyscraper5.Skyscraper.Scraper.Storage.Utilities;
using skyscraper5.src.InteractionChannel.Model;
using skyscraper5.src.InteractionChannel.Model.Descriptors;
using skyscraper5.src.InteractionChannel.Model2;
using skyscraper5.src.Skyscraper.FrequencyListGenerator;
using skyscraper5.src.Skyscraper.Scraper.Dns;
using skyscraper5.src.Skyscraper.Scraper.Storage.InMemory;
using skyscraper5.Teletext;
using skyscraper8.DvbI;
using skyscraper8.DvbNip;
using skyscraper8.Experimentals.NdsSsu;
using skyscraper8.Ietf.FLUTE;
using skyscraper8.InteractionChannel.Model;
using skyscraper8.InteractionChannel.Model2;
using skyscraper8.InteractionChannel.Model2.Descriptors;
using skyscraper8.Ses;
using skyscraper8.SimpleServiceDiscoveryProtocol;
using skyscraper8.Skyscraper.Drawing;
using skyscraper8.Skyscraper.Scraper.Storage;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Text.RegularExpressions;
using Platform = skyscraper5.Dvb.SystemSoftwareUpdate.Model.Platform;

namespace skyscraper5.Skyscraper.Scraper.Storage.Filesystem
{
	public class FilesystemStorage : DataStorage, ObjectStorage
    {
        private readonly DirectoryInfo rootDirectory;
        private readonly string importFilesKnownFilename;
        private readonly JsonSerializerSettings jsonSerializerSettings;

        public FilesystemStorage(DirectoryInfo rootDirectory)
        {
			EnsureDirectoryExists(rootDirectory);
			this.rootDirectory = rootDirectory;
            this.importFilesKnownFilename = Path.Combine(rootDirectory.FullName, "import_files_known.json");
            this.jsonSerializerSettings = new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore,
                Formatting = Formatting.Indented
            };
        }

        public bool TestForNitNetwork(NitNetwork nitNetwork)
        {
            string combine = Path.Combine(rootDirectory.FullName, "NIT", nitNetwork.NetworkId.ToString(), "info.json");
            return File.Exists(combine);
        }

        public void StoreNitNetwork(NitNetwork nitNetwork)
        {
            string combine = Path.Combine(rootDirectory.FullName, "NIT", nitNetwork.NetworkId.ToString(), "info.json");
            FileInfo fi = new FileInfo(combine);
            EnsureDirectoryExists(fi.Directory);
            File.WriteAllText(fi.FullName, JsonConvert.SerializeObject(nitNetwork, Formatting.Indented, jsonSerializerSettings));
        }

        public bool UpdateNitNetwork(NitNetwork nitNetwork)
        {
            string combine = Path.Combine(rootDirectory.FullName, "NIT", nitNetwork.NetworkId.ToString(), "info.json");
            FileInfo fi = new FileInfo(combine);
            NitNetwork stored = JsonConvert.DeserializeObject<NitNetwork>(File.ReadAllText(fi.FullName));
            bool needsUpdate = stored.NeedsUpdate(nitNetwork);
            if (needsUpdate)
                StoreNitNetwork(nitNetwork);
            return needsUpdate;
        }

        public bool TestForNitTransportStream(ushort networkId, NitTransportStream transportStream)
        {
            string combine = Path.Combine(rootDirectory.FullName, "NIT", networkId.ToString(), String.Format("{0}.json", transportStream.TransportStreamId));
            return File.Exists(combine);
        }

        public void StoreNitTransportStream(ushort networkId, NitTransportStream transportStream)
        {
            string combine = Path.Combine(rootDirectory.FullName, "NIT", networkId.ToString(), String.Format("{0}.json", transportStream.TransportStreamId));
            FileInfo fi = new FileInfo(combine);
            EnsureDirectoryExists(fi.Directory);
            File.WriteAllText(fi.FullName, JsonConvert.SerializeObject(transportStream, Formatting.Indented, jsonSerializerSettings));
        }

        public bool UpdateNitTransportStream(ushort networkId, NitTransportStream transportStream)
        {
            string combine = Path.Combine(rootDirectory.FullName, "NIT", networkId.ToString(), String.Format("{0}.json", transportStream.TransportStreamId));
            FileInfo fi = new FileInfo(combine);
            NitTransportStream nitTransportStream = JsonConvert.DeserializeObject<NitTransportStream>(File.ReadAllText(combine));
            if (nitTransportStream.NeedUpdate(nitTransportStream))
            {
                StoreNitTransportStream(networkId, transportStream);
                return true;
            }
            return false;
        }

        public bool StorePatEntry(int currentNetworkId, int currentTransportStreamId, int pmtPid, ushort programId)
        {
            string combine = Path.Combine(rootDirectory.FullName, "PAT", currentNetworkId.ToString(), currentTransportStreamId.ToString(), String.Format("{0}.n", programId));
            FileInfo fi = new FileInfo(combine);
            if (fi.Exists)
                return false;
            EnsureDirectoryExists(fi.Directory);
            File.WriteAllText(fi.FullName, pmtPid.ToString());
            return true;
        }

        public bool TestForPmtEvent(int currentNetworkId, int currentTransportStreamId, ProgramMapping result)
        {
            string combine = Path.Combine(rootDirectory.FullName, "PMT", currentNetworkId.ToString(),
                currentTransportStreamId.ToString(), String.Format("{0}.json", result.ProgramNumber));
            return File.Exists(combine);
        }

        public bool StorePmtEvent(int currentNetworkId, int currentTransportStreamId, ProgramMapping mapping)
        {
            string combine = Path.Combine(rootDirectory.FullName, "PMT", currentNetworkId.ToString(),
                currentTransportStreamId.ToString(), String.Format("{0}.json", mapping.ProgramNumber));
            FileInfo fi = new FileInfo(combine);
            if (fi.Exists)
                return false;
            EnsureDirectoryExists(fi.Directory);
            File.WriteAllText(fi.FullName, JsonConvert.SerializeObject(mapping, Formatting.Indented, jsonSerializerSettings));
            return true;
        }

        public bool StoreTeletextPage(int networkId, int transportStreamId, ushort programNumber, TeletextMagazine magazine, DateTime timestamp)
        {
            ushort pageNo = magazine.HumanReadablePageNumber;
            if (pageNo > 999)
                return false;

            string combine = Path.Combine(rootDirectory.FullName, "Teletext", timestamp.Year.ToString(), timestamp.Month.ToString(), timestamp.Day.ToString(), timestamp.Hour.ToString(), networkId.ToString(), transportStreamId.ToString(), programNumber.ToString(), String.Format("{0}.txt",pageNo));
            FileInfo fi = new FileInfo(combine);
            if (fi.Exists)
                return false;
            EnsureDirectoryExists(fi.Directory);
            FileStream fileStream = fi.OpenWrite();
            magazine.WriteOut(fileStream);
            fileStream.Flush();
            fileStream.Close();
            return true;
        }

        public bool TestForSdtService(ushort transportStreamId, ushort originalNetworkId, SdtService sdtService)
        {
            string combine = Path.Combine(rootDirectory.FullName, "SDT", originalNetworkId.ToString(), transportStreamId.ToString(), String.Format("{0}.json", sdtService.ServiceId.ToString()));
            return File.Exists(combine);
        }

        public bool TestForTeletextPage(int networkId, int transportStreamId, ushort programNumber, TeletextMagazine magazine,
            DateTime timestamp)
        {
            ushort pageNo = magazine.HumanReadablePageNumber;
            if (pageNo > 999)
                return false;

            string combine = Path.Combine(rootDirectory.FullName, "Teletext", timestamp.Year.ToString(), timestamp.Month.ToString(), timestamp.Day.ToString(), timestamp.Hour.ToString(), networkId.ToString(), transportStreamId.ToString(), programNumber.ToString(), String.Format("{0}.txt", pageNo));
            return File.Exists(combine);
        }

        public void MarkTeletextPageAsKnown(int networkId, int transportStreamId, ushort programNumber, TeletextMagazine magazine,
            DateTime timestamp)
        {
            StoreTeletextPage(networkId, transportStreamId, programNumber, magazine, timestamp);
        }

        public bool UpdateSdtService(ushort transportStreamId, ushort originalNetworkId, SdtService sdtService)
        {
            string combine = Path.Combine(rootDirectory.FullName, "SDT", originalNetworkId.ToString(), transportStreamId.ToString(), String.Format("{0}.json", sdtService.ServiceId.ToString()));
            SdtService stored = JsonConvert.DeserializeObject<SdtService>(File.ReadAllText(combine));
            if (stored.NeedsUpdate(sdtService))
            {
                StoreSdtService(transportStreamId, originalNetworkId, sdtService);
                return true;
            }
            return false;
        }

        public void StoreSdtService(ushort transportStreamId, ushort originalNetworkId, SdtService sdtService)
        {
            string combine = Path.Combine(rootDirectory.FullName, "SDT", originalNetworkId.ToString(), transportStreamId.ToString(), String.Format("{0}.json", sdtService.ServiceId.ToString()));
            FileInfo fi = new FileInfo(combine);
            EnsureDirectoryExists(fi.Directory);
            File.WriteAllText(combine,JsonConvert.SerializeObject(sdtService, Formatting.Indented, jsonSerializerSettings));
        }

        public bool TestForBatBouquet(BatBouquet batBouquet)
        {
            string combine = Path.Combine(rootDirectory.FullName, "BAT", batBouquet.BouquetId.ToString(), "info.json");
            return File.Exists(combine);
        }

        public bool UpdateBatBouquet(BatBouquet batBouquet)
        {
            if (!TestForBatBouquet(batBouquet))
            {
                StoreBatBouquet(batBouquet);
                return true;
            }
            string combine = Path.Combine(rootDirectory.FullName, "BAT", batBouquet.BouquetId.ToString(), "info.json");
            BatBouquet stored = JsonConvert.DeserializeObject<BatBouquet>(File.ReadAllText(combine));
            if (stored.NeedUpdate(batBouquet))
            {
                StoreBatBouquet(batBouquet);
                return true;
            }
            return false;
        }

        public void StoreBatBouquet(BatBouquet batBouquet)
        {
            string combine = Path.Combine(rootDirectory.FullName, "BAT", batBouquet.BouquetId.ToString(), "info.json");
            FileInfo fi = new FileInfo(combine);
            EnsureDirectoryExists(fi.Directory);
            File.WriteAllText(fi.FullName, JsonConvert.SerializeObject(batBouquet, Formatting.Indented, jsonSerializerSettings));
        }

        public bool TestForBatTransportStream(ushort batBouquetBouquetId, BatTransportStream child)
        {
            string combine = Path.Combine(rootDirectory.FullName, "BAT", batBouquetBouquetId.ToString(), child.OriginalNetworkId.ToString(), String.Format("{0}.json", child.TransportStreamId));
            return File.Exists(combine);
        }

        public bool UpdateBatTransportStream(ushort batBouquetBouquetId, BatTransportStream child)
        {
            string combine = Path.Combine(rootDirectory.FullName, "BAT", batBouquetBouquetId.ToString(), child.OriginalNetworkId.ToString(), String.Format("{0}.json", child.TransportStreamId));
            FileInfo fi = new FileInfo(combine);
            if (!fi.Exists)
            {
                StoreBatTransportStream(batBouquetBouquetId, child);
                return true;
            }
            BatTransportStream stored = JsonConvert.DeserializeObject<BatTransportStream>(File.ReadAllText(combine));
            if (stored.NeedsUpdate(child))
            {
                StoreBatTransportStream(batBouquetBouquetId, child);
                return true;
            }
            return false;
        }

        public void StoreBatTransportStream(ushort batBouquetBouquetId, BatTransportStream child)
        {
            string combine = Path.Combine(rootDirectory.FullName, "BAT", batBouquetBouquetId.ToString(), child.OriginalNetworkId.ToString(), String.Format("{0}.json", child.TransportStreamId));
            FileInfo fi = new FileInfo(combine);
            EnsureDirectoryExists(fi.Directory);
            File.WriteAllText(fi.FullName, JsonConvert.SerializeObject(child, Formatting.Indented, jsonSerializerSettings));
        }

        public bool UpdateTimeOffsetTable(int currentNetworkId, int currentTransportStreamId, DateTime utcTime,
            LocalTimeOffsetDescriptor ltod)
        {
            string combine = Path.Combine(rootDirectory.FullName, "TOT", currentNetworkId.ToString(), String.Format("{0}.n", currentTransportStreamId));
            FileInfo fi = new FileInfo(combine);
            if (fi.Exists)
            {
                long l = long.Parse(File.ReadAllText(fi.FullName));
                DateTime savedDate = new DateTime(l);
                if (utcTime > savedDate)
                {
                    File.WriteAllText(fi.FullName, utcTime.Ticks.ToString());
                    return true;
                }
            }
            else
            {
                EnsureDirectoryExists(fi.Directory);
                File.WriteAllText(fi.FullName, utcTime.Ticks.ToString());
                combine = Path.Combine(rootDirectory.FullName, "TOT", currentNetworkId.ToString(), String.Format("{0}.json", currentTransportStreamId));
                File.WriteAllText(combine, JsonConvert.SerializeObject(ltod, Formatting.Indented, jsonSerializerSettings));
                return true;
            }
            return false;
        }

        public bool UpdateTimeAndDate(int currentNetworkId, int currentTransportStreamId, DateTime utcTime)
        {
            string combine = Path.Combine(rootDirectory.FullName, "TDT", currentNetworkId.ToString(), String.Format("{0}.n", currentTransportStreamId));
            FileInfo fi = new FileInfo(combine);
            if (fi.Exists)
            {
                long l = long.Parse(File.ReadAllText(fi.FullName));
                DateTime savedDate = new DateTime(l);
                if (utcTime > savedDate)
                {
                    File.WriteAllText(fi.FullName, utcTime.Ticks.ToString());
                    return true;
                }
            }
            else
            {
                EnsureDirectoryExists(fi.Directory);
                File.WriteAllText(fi.FullName, utcTime.Ticks.ToString());
                return true;
            }
            return false;
        }

        private void EnsureDirectoryExists(DirectoryInfo di)
        {
            if (di.Exists)
                return;
            EnsureDirectoryExists(di.Parent);
            di.Create();
            di.Refresh();
        }

        public bool StoreEitEvent(EitEvent eitEvent)
        {
            string path = Path.Combine(rootDirectory.FullName, "EIT", eitEvent.StartTime.Year.ToString(),
                eitEvent.StartTime.Month.ToString(), eitEvent.StartTime.Day.ToString(),
                eitEvent.OriginalNetworkId.ToString(), eitEvent.TransportStreamId.ToString(),
                eitEvent.ServiceId.ToString(), String.Format("{0}.json", eitEvent.EventId));
            FileInfo outFileInfo = new FileInfo(path);
            if (outFileInfo.Exists)
                return false;
            EnsureDirectoryExists(outFileInfo.Directory);
            File.WriteAllText(outFileInfo.FullName, JsonConvert.SerializeObject(eitEvent, Formatting.Indented, jsonSerializerSettings));
            return true;
        }

        public bool TestForAitApplication(ApplicationIdentifier aitApplicationApplicationIdentifier)
        {
            string combine = Path.Combine(rootDirectory.FullName, "AIT", aitApplicationApplicationIdentifier.OrganisationId.ToString(), String.Format("{0}.json",aitApplicationApplicationIdentifier.ApplicationId.ToString()));
            return File.Exists(combine);
        }

        public void StoreAitApplication(AitApplication aitApplication)
        {
            string combine = Path.Combine(rootDirectory.FullName, "AIT", aitApplication.ApplicationIdentifier.OrganisationId.ToString(), String.Format("{0}.json", aitApplication.ApplicationIdentifier.ApplicationId));
            FileInfo fi = new FileInfo(combine);
            EnsureDirectoryExists(fi.Directory);
            File.WriteAllText(fi.FullName, JsonConvert.SerializeObject(aitApplication, Formatting.Indented, jsonSerializerSettings));
        }

        public bool ObjectCarouselFileArrival(VfsFile vfsFile, int transportStreamId, int networkId)
        {
            string combine = Path.Combine(rootDirectory.FullName, "DSM-CC_Objects", networkId.ToString(), transportStreamId.ToString(), vfsFile.SourcePid.ToString(), vfsFile.ToString().Substring(1));
            FileInfo fi = new FileInfo(combine);
            if (fi.Exists)
                return false;
            EnsureDirectoryExists(fi.Directory);
            File.WriteAllBytes(fi.FullName,vfsFile.FileContent);
            return true;
        }

        public bool TestForCaSystem(int currentNetworkId, int currentTransportStreamId, int caDescriptorCaPid)
        {
            string combine = Path.Combine(rootDirectory.FullName, "CAT", currentNetworkId.ToString(), currentTransportStreamId.ToString(), String.Format("{0}.json", caDescriptorCaPid));
            return File.Exists(combine);
        }

        public void StoreCaSystem(int currentNetworkId, int currentTransportStreamId, CaDescriptor caDescriptor)
        {
            string combine = Path.Combine(rootDirectory.FullName, "CAT", currentNetworkId.ToString(), currentTransportStreamId.ToString(), String.Format("{0}.json", caDescriptor.CaPid));
            FileInfo fi = new FileInfo(combine);
            EnsureDirectoryExists(fi.Directory);
            File.WriteAllText(fi.FullName, JsonConvert.SerializeObject(caDescriptor, Formatting.Indented, jsonSerializerSettings));
        }

        public void DataCarouselModuleArrival(int currentNetworkId, int currentTransportStreamId, int elementaryPid, ushort moduleId, byte moduleVersion, Stream result)
        {
            string combine = Path.Combine(rootDirectory.FullName, "DSM-CC_Data", currentNetworkId.ToString(), currentTransportStreamId.ToString(), elementaryPid.ToString(), String.Format("{0}_V{1}.bin", moduleId, moduleVersion));
            FileInfo fi = new FileInfo(combine);
            if (!fi.Exists)
            {
                EnsureDirectoryExists(fi.Directory);
                FileStream outputStream = fi.OpenWrite();
                result.CopyTo(outputStream);
                outputStream.Close();
                outputStream.Dispose();
            }
        }

        public bool TestForKnownRdsData(int currentNetworkId, int currentTransportStreamId, int programNumber)
        {
            string combine = Path.Combine(rootDirectory.FullName, "RDS", currentNetworkId.ToString(), currentTransportStreamId.ToString(), programNumber.ToString(), "marker.bin");
            return File.Exists(combine);
        }

        public void EnableRdsCollection(int currentNetworkId, int currentTransportStreamId, int programNumber)
        {
            string combine = Path.Combine(rootDirectory.FullName, "RDS", currentNetworkId.ToString(), currentTransportStreamId.ToString(), programNumber.ToString(), "marker.bin");
            FileInfo fi = new FileInfo(combine);
            if (!fi.Exists)
            {
                EnsureDirectoryExists(fi.Directory);
                FileStream fileStream = fi.Open(FileMode.CreateNew);
                fileStream.Flush(true);
                fileStream.Close();
            }
        }

        public bool UpdateRdsProgrammeServiceName(int currentNetworkId, int currentTransportStreamId, int programNumber,
            string programmeService2)
        {
            string combine = Path.Combine(rootDirectory.FullName, "RDS", currentNetworkId.ToString(), currentTransportStreamId.ToString(), programNumber.ToString(), "ps.txt");
            FileInfo fi = new FileInfo(combine);
            string alreadyKnown = "";
            if (fi.Exists)
            {
                alreadyKnown = File.ReadAllText(combine);
            }

            if (!alreadyKnown.Equals(programmeService2))
            {
                File.WriteAllText(combine, programmeService2);
                return true;
            }
            return false;
        }

        public bool UpdateRdsRadioText(int currentNetworkId, int currentTransportStreamId, int programNumber, string text)
        {
            string combine = Path.Combine(rootDirectory.FullName, "RDS", currentNetworkId.ToString(), currentTransportStreamId.ToString(), programNumber.ToString(), "rt.txt");
            FileInfo fi = new FileInfo(combine);
            string alreadyKnown = "";
            if (fi.Exists)
            {
                alreadyKnown = File.ReadAllText(combine);
            }

            if (!alreadyKnown.Equals(text))
            {
                File.WriteAllText(combine, text);
                return true;
            }
            return false;
        }

        public bool UpdateRdsPty(int currentNetworkId, int currentTransportStreamId, int programNumber, PTY.ProgrammeTypeCodes pty)
        {
            string combine = Path.Combine(rootDirectory.FullName, "RDS", currentNetworkId.ToString(), currentTransportStreamId.ToString(), programNumber.ToString(), "pty.bin");
            FileInfo fi = new FileInfo(combine);
            if (fi.Exists)
            {
                byte[] readAllBytes = File.ReadAllBytes(combine);
                if (readAllBytes[0] != (byte)pty)
                {
                    byte[] tmp = new byte[] { (byte)pty };
                    File.WriteAllBytes(combine, tmp);
                    return true;
                }
                return false;
            }
            else
            {
                byte[] tmp = new byte[] { (byte)pty };
                File.WriteAllBytes(combine, tmp);
                return true;
            }
        }

        public bool MarkAsRdsTrafficInformationProgramme(int currentNetworkId, int currentTransportStreamId, int programNumber)
        {
            string combine = Path.Combine(rootDirectory.FullName, "RDS", currentNetworkId.ToString(), currentTransportStreamId.ToString(), programNumber.ToString(), "ti.bin");
            FileInfo fi = new FileInfo(combine);
            if (!fi.Exists)
            {
                FileStream fileStream = fi.OpenWrite();
                fileStream.Flush(true);
                fileStream.Close();
                return true;
            }
            return false;
        }

        public bool TestForScte35SpliceInsert(int currentNetworkId, int currentTransportStreamId, ushort programNumber, SpliceInsert spliceInsert)
        {
            string path = Path.Combine(rootDirectory.FullName, "SCTE-35",currentNetworkId.ToString(), currentTransportStreamId.ToString(), programNumber.ToString(), String.Format("{0}.json", spliceInsert.SpliceEventId));
            return File.Exists(path);
        }

        public void StoreScte35SpliceInsert(int currentNetworkId, int currentTransportStreamId, ushort programNumber, SpliceInsert spliceInsert)
        {
            string path = Path.Combine(rootDirectory.FullName, "SCTE-35", currentNetworkId.ToString(), currentTransportStreamId.ToString(), programNumber.ToString(), String.Format("{0}.json", spliceInsert.SpliceEventId));
            FileInfo fi = new FileInfo(path);
            if (!fi.Exists)
            {
                EnsureDirectoryExists(fi.Directory);
                File.WriteAllText(fi.FullName, JsonConvert.SerializeObject(spliceInsert, Formatting.Indented, jsonSerializerSettings));
            }
        }

        public bool IsCompliant(int currentNetworkId, int currentTransportStreamId, string compliance)
        {
            string path = Path.Combine(rootDirectory.FullName, "TSDT", currentNetworkId.ToString(), currentTransportStreamId.ToString(), String.Format("{0}.5ds",compliance));
            return File.Exists(path);
        }

        public void MarkAsCompliant(int currentNetworkId, int currentTransportStreamId, string compliance)
        {
            string path = Path.Combine(rootDirectory.FullName, "TSDT", currentNetworkId.ToString(), currentTransportStreamId.ToString(), String.Format("{0}.5ds", compliance));
            FileInfo fi = new FileInfo(path);
            if (!fi.Exists)
            {
                EnsureDirectoryExists(fi.Directory);
                fi.Create().Close();
            }
        }

        public bool SetStationIdentification(int currentNetworkId, int currentTransportStreamId, string stationIdentification)
        {
            string path = Path.Combine(rootDirectory.FullName, "TSDT", currentNetworkId.ToString(), String.Format("{0}.999", currentTransportStreamId));
            FileInfo fi = new FileInfo(path);
            if (fi.Exists)
            {
                string text = File.ReadAllText(fi.FullName);
                if (text.Equals(stationIdentification))
                    return false;
            }
            else
            {
                EnsureDirectoryExists(fi.Directory);
            }

            File.WriteAllText(fi.FullName, stationIdentification);
            return true;
        }
        

        public bool IsDsmCcModuleWanted(int currentNetworkId, int currentTransportStreamId, int elementaryPid, ushort moduleId,
            byte moduleVersion)
        {
            string combine = Path.Combine(rootDirectory.FullName, "DSM-CC_Data", currentNetworkId.ToString(), currentTransportStreamId.ToString(), elementaryPid.ToString(), String.Format("{0}_V{1}.bin", moduleId, moduleVersion));
            return !File.Exists(combine);
        }

        public void StoreDsmCcDoItNowEvent(DateTime timestamp, int currentNetworkId, int currentTransportStreamId, int programNumber, StreamEventDescriptor descriptorListStreamEventDescriptor, int pid)
        {
            string combine = Path.Combine(rootDirectory.FullName, "DSM-CC_Events", currentNetworkId.ToString(), currentTransportStreamId.ToString(), pid.ToString(), String.Format("event{0}_{1}.bin", descriptorListStreamEventDescriptor.EventId, timestamp.ToUnixTime()));
            FileInfo fi = new FileInfo(combine);
            if (!fi.Exists)
            {
                EnsureDirectoryExists(fi.Directory);
                File.WriteAllBytes(combine, descriptorListStreamEventDescriptor.PrivateData);
            }
        }

        public bool StoreRunningStatus(uint transportStreamId, uint originalNetworkId, uint serviceId, uint eventId,
            RunningStatus runningStatus, DateTime currentTime)
        {
            string combine = Path.Combine(rootDirectory.FullName, "RST", originalNetworkId.ToString(), transportStreamId.ToString(), serviceId.ToString(), eventId.ToString(), String.Format("{0}.999", runningStatus.ToString()));
            FileInfo fi = new FileInfo(combine);
            if (fi.Exists)
                return false;

            EnsureDirectoryExists(fi.Directory);
            File.WriteAllText(fi.FullName, currentTime.ToUnixTime().ToString());
            return true;
        }



        public void SetScte35TimeSignal(int currentNetworkId, int currentTransportStreamId, DateTime currentTime, ushort programNumber, TimeSignal timeSignal)
        {
            string path = Path.Combine(rootDirectory.FullName, "SCTE-35", currentNetworkId.ToString(), currentTransportStreamId.ToString(), programNumber.ToString(), String.Format("TimeSignal_{0}.json", currentTime.ToUnixTime()));
            FileInfo fi = new FileInfo(path);
            if (fi.Exists)
                return;
            fi.Directory.EnsureExists();
            File.WriteAllText(fi.FullName, JsonConvert.SerializeObject(timeSignal, Formatting.Indented, jsonSerializerSettings));
        }

        public bool TestForFramegrab(int currentNetworkId, int transportStreamId, ushort mappingProgramNumber, int mappingStreamElementaryPid)
        {
            string path = Path.Combine(rootDirectory.FullName, "0-Framegrabs", currentNetworkId.ToString(), transportStreamId.ToString(), String.Format("{0}.jpg", mappingProgramNumber));
            return File.Exists(path);
        }
        

        public void StoreFramegrab(int currentNetworkId, int transportStreamId, ushort mappingProgramNumber, ushort pid, byte[] imageData)
        {
            string path = Path.Combine(rootDirectory.FullName, "0-Framegrabs", currentNetworkId.ToString(), transportStreamId.ToString(), String.Format("{0}.jpg", mappingProgramNumber));
            FileInfo fi = new FileInfo(path);
            fi.Directory.EnsureExists();
            File.WriteAllBytes(path, imageData);
        }

        public bool TestForDocsisUpstreamChannel(PhysicalAddress mmmSource, uint mmmFrequency, int locationId)
        {
            string path = Path.Combine(rootDirectory.FullName, "DOCSIS", "UpstreamChannels", String.Format("Location_{0}", locationId), mmmSource.ToString(), mmmFrequency.ToString() + ".json");
            return File.Exists(path);
        }

        public void StoreDocsisUpstreamChannel(UpstreamChannelDescriptor mmm, int locationId)
        {
            string fname = Path.Combine(rootDirectory.FullName, "DOCSIS", "UpstreamChannels", String.Format("Location_{0}", locationId), mmm.Source.ToString(), mmm.Frequency.ToString() + ".json");
            FileInfo fi = new FileInfo(fname);
            fi.Directory.EnsureExists();
            File.WriteAllText(fi.FullName, JsonConvert.SerializeObject(mmm, Formatting.Indented, jsonSerializerSettings));
        }

        public bool TestForDocsisDownstreamChannel(PhysicalAddress physicalAddress, MacDomainDescriptor.DownstreamActiveChannel downstreamActiveChannel, int locationId)
        {
            string fname = Path.Combine(rootDirectory.FullName, "DOCSIS", "DownstreamChannels", String.Format("Location_{0}", locationId), physicalAddress.ToString(), downstreamActiveChannel.Frequency.Value.ToString() + ".json");
            return File.Exists(fname);
        }

        public void StoreDocsisDownstreamChannel(PhysicalAddress physicalAddress, MacDomainDescriptor.DownstreamActiveChannel downstreamActiveChannel, int locationId)
        {
            string fname = Path.Combine(rootDirectory.FullName, "DOCSIS", "DownstreamChannels", String.Format("Location_{0}",locationId), physicalAddress.ToString(), downstreamActiveChannel.Frequency.Value.ToString() + ".json");
            FileInfo fi = new FileInfo(fname);
            fi.Directory.EnsureExists();
            File.WriteAllText(fi.FullName, JsonConvert.SerializeObject(downstreamActiveChannel, Formatting.Indented, jsonSerializerSettings));
        }

        public bool SetCmtsIp(PhysicalAddress physicalAddress, IPAddress ip)
        {
            string fname = Path.Combine(rootDirectory.FullName, "DOCSIS", "CMTS_IP", physicalAddress.ToString() + ".txt");
            FileInfo fi = new FileInfo(fname);
            IPAddress ondisk = IPAddress.None;
            if (fi.Exists)
            {
                ondisk = new IPAddress(File.ReadAllBytes(fname));
            }

            if (!ondisk.Equals(ip))
            {
                fi.Directory.EnsureExists();
                File.WriteAllBytes(fi.FullName, ip.GetAddressBytes());
                return true;
            }

            return false;
        }

        private DsmCcModuleBlacklist dsmCcBlacklist;
        public bool IsDsmCcModuleBlacklisted(int currentNetworkId, int currentTransportStreamId, int elementaryPid, ushort moduleId, byte moduleVersion)
        {
            if (dsmCcBlacklist == null)
            {
                string fname = Path.Combine(rootDirectory.FullName, "dsmcc_blacklist.csv");
                FileInfo fi = new FileInfo(fname);
                dsmCcBlacklist = new DsmCcModuleBlacklist(fi);
            }

            return dsmCcBlacklist.IsBlacklisted(currentNetworkId, currentTransportStreamId, elementaryPid, moduleId, moduleVersion);
        }

        public int? GetCurrentLocationId()
        {
            string fname = Path.Combine(rootDirectory.FullName, "docsis_location.txt");
            FileInfo fi = new FileInfo(fname);
            if (fi.Exists)
            {
                string readAllText = File.ReadAllText(fi.FullName);
                return Int32.Parse(readAllText);
            }

            return null;
        }

        public void StoreDocsisParticipant(PhysicalAddress pa, int currentLocation)
        {
            string fname = Path.Combine(rootDirectory.FullName, "DOCSIS", "Participants", String.Format("Location_{0}", currentLocation), pa.ToString() + ".tmp");
            FileInfo fi = new FileInfo(fname);
            if (!fi.Exists)
            {
                EnsureDirectoryExists(fi.Directory);
                fi.Create().Close();
            }
        }
        
        public bool TestForIpMacNotification(IpMacNotification notification)
        {
            string path = Path.Combine(rootDirectory.FullName, "INT", String.Format("{0}_{1}.json", notification.Platform.PlatformId, notification.Target.GenerateId()));
            return File.Exists(path);
        }

        public void StoreIpMacNotification(IpMacNotification notification)
        {
            string path = Path.Combine(rootDirectory.FullName, "INT", String.Format("{0}_{1}.json", notification.Platform.PlatformId, notification.Target.GenerateId()));
			FileInfo fi = new FileInfo(path);
            EnsureDirectoryExists(fi.Directory);
            File.WriteAllText(fi.FullName, JsonConvert.SerializeObject(notification, Formatting.Indented, jsonSerializerSettings));
        }

        private KnownTsMemory knownTss;
        private List<string> importFilesKnown;

        public bool ImportFileKnown(FileInfo fi)
        {
			if (knownTss == null)
				knownTss = new KnownTsMemory(importFilesKnownFilename);
            return knownTss.ImportFileKnown(fi);
        }

        public void ImportMarkFileAsKnown(FileInfo fi, TimeSpan ts, int tstype)
        {
			if (knownTss == null)
				knownTss = new KnownTsMemory(importFilesKnownFilename);
            knownTss.ImportMarkFileAsKnown(fi, ts, tstype);
        }

        public DateTime T2MiGetTimestamp(int currentNetworkId, int currentTransportStreamId, int pid)
        {
            string path = Path.Combine(rootDirectory.FullName, "T2-MI", currentNetworkId.ToString(), currentTransportStreamId.ToString(),String.Format("{0}.timestamp", pid));
            if (!File.Exists(path))
            {
                return DateTime.MinValue;
            }

            string readAllText = File.ReadAllText(path);
            long l = long.Parse(readAllText);
            DateTime result = new DateTime(l);
            return result;
        }

        public void T2MiSetTimestamp(int currentNetworkId, int currentTransportStreamId, int pid, DateTime resolveTime)
        {
            string path = Path.Combine(rootDirectory.FullName, "T2-MI", currentNetworkId.ToString(), currentTransportStreamId.ToString(), String.Format("{0}.timestamp", pid));
            FileInfo fi = new FileInfo(path);
            EnsureDirectoryExists(fi.Directory);
            File.WriteAllText(fi.FullName, resolveTime.Ticks.ToString());
        }

        private string BuildRctIdentifier(RctLinkInfo rctLinkInfo)
        {
            char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
            StringBuilder sb = new StringBuilder();
            if (rctLinkInfo.LinkType == RctLinkInfo.LinkTypeValue.Uri)
            {
                sb.Append("A_");
                char[] charArray = rctLinkInfo.MediaUri.ToCharArray();
                foreach (char c in charArray)
                {
                    if (!invalidFileNameChars.Contains(c))
                        sb.Append(c);
                    else
                        sb.Append('_');
                }
            }
            else
            {
                throw new NotImplementedException(rctLinkInfo.LinkType.ToString());
            }

            sb.Append(".json");
            return sb.ToString();
        }

        public bool TestForRelatedContent(EitEvent lEvent, RctLinkInfo rctLinkInfo)
        {
            string path = Path.Combine(rootDirectory.FullName, "RCT", lEvent.StartTime.Year.ToString(), lEvent.StartTime.Month.ToString(),
                lEvent.StartTime.Day.ToString(), lEvent.OriginalNetworkId.ToString(), lEvent.TransportStreamId.ToString(), lEvent.ServiceId.ToString(),
                lEvent.EventId.ToString(), BuildRctIdentifier(rctLinkInfo));
            return File.Exists(path);
        }

        public void SetRelatedContent(EitEvent lEvent, RctLinkInfo rctLinkInfo)
        {
            string path = Path.Combine(rootDirectory.FullName, "RCT", lEvent.StartTime.Year.ToString(), lEvent.StartTime.Month.ToString(),
                lEvent.StartTime.Day.ToString(), lEvent.OriginalNetworkId.ToString(), lEvent.TransportStreamId.ToString(), lEvent.ServiceId.ToString(),
                lEvent.EventId.ToString(), BuildRctIdentifier(rctLinkInfo));
            FileInfo fi = new FileInfo(path);
            if (!fi.Exists)
            {
                EnsureDirectoryExists(fi.Directory);
                File.WriteAllText(fi.FullName, JsonConvert.SerializeObject(rctLinkInfo, Formatting.Indented));
            }
        }

        public bool UiTunerTestFor(TunerMetadata tuner)
        {
            string fname = BitConverter.ToString(tuner.MacAddress.GetAddressBytes());
            string path = Path.Combine(rootDirectory.FullName, "0-UI", "Tuners", fname + ".json");
            return File.Exists(path);
        }

        public void UiTunerUpdate(TunerMetadata tuner)
        {
            string fname = BitConverter.ToString(tuner.MacAddress.GetAddressBytes());
            string path = Path.Combine(rootDirectory.FullName, "0-UI", "Tuners", fname + ".json");
            File.WriteAllText(path, JsonConvert.SerializeObject(tuner, Formatting.Indented));
        }

        public void UiTunerInsert(TunerMetadata tuner)
        {
            string fname = BitConverter.ToString(tuner.MacAddress.GetAddressBytes());
            string path = Path.Combine(rootDirectory.FullName, "0-UI", "Tuners", fname + ".json");
            FileInfo fi = new FileInfo(path);
            EnsureDirectoryExists(fi.Directory);
            File.WriteAllText(fi.FullName, JsonConvert.SerializeObject(tuner, Formatting.Indented));
        }

        public void UiTunerGetConfiguration(TunerMetadata foundTuner)
        {
            string fname = BitConverter.ToString(foundTuner.MacAddress.GetAddressBytes());
            string path = Path.Combine(rootDirectory.FullName, "0-UI", "Tuners", fname + ".json");
            TunerMetadata copy = JsonConvert.DeserializeObject<TunerMetadata>(File.ReadAllText(path));
            foundTuner.DiseqcType = copy.DiseqcType;
            foundTuner.Satellites = new int[4];
            foundTuner.Satellites[0] = copy.Satellites[0];
            foundTuner.Satellites[1] = copy.Satellites[1];
            foundTuner.Satellites[2] = copy.Satellites[2];
            foundTuner.Satellites[3] = copy.Satellites[3];
            foundTuner.Lnbs = new int[4];
            foundTuner.Lnbs[0] = copy.Lnbs[0];
            foundTuner.Lnbs[1] = copy.Lnbs[1];
            foundTuner.Lnbs[2] = copy.Lnbs[2];
            foundTuner.Lnbs[3] = copy.Lnbs[3];
        }

        public HeadlessJob GetQueuedJob()
        {
            throw new NotImplementedException();
        }

        public void SetQueuedJobComplete(HeadlessJob headlessJob)
        {
            throw new NotImplementedException();
        }

        public void WaitForCompletion()
        {
        }

        private int uiVersion;
        public void UiSetVersion(int version)
        {
	        this.uiVersion = version;
        }

        public bool T2MiTestForTransmitter(int? currentNetworkId, int? currentTransportStreamId, int relatedPid, ushort txIdentifier)
        {
            if (!currentNetworkId.HasValue)
                return true;
            if (!currentTransportStreamId.HasValue)
                return true;

            string txName = String.Format("{0}_TX{1}", relatedPid, txIdentifier);

            string path = Path.Combine(rootDirectory.FullName, "T2-MI", currentNetworkId.ToString(), currentTransportStreamId.ToString(), txName, "test.bin");
            return File.Exists(path);
        }

        public void T2MiRememberTransmitter(int? currentNetworkId, int? currentTransportStreamId, int relatedPid, ushort txIdentifier)
        {
            if (!currentNetworkId.HasValue)
                return;
            if (!currentTransportStreamId.HasValue)
                return;

            string txName = String.Format("{0}_TX{1}", relatedPid, txIdentifier);

            string path = Path.Combine(rootDirectory.FullName, "T2-MI", currentNetworkId.ToString(), currentTransportStreamId.ToString(), txName, "test.bin");
            FileInfo fi = new FileInfo(path);
            EnsureDirectoryExists(fi.Directory);
            fi.OpenWrite().Close();
        }

        public void T2MiSetTransmitterTimeOffset(int? currentNetworkId, int? currentTransportStreamId, int relatedPid, ushort txIdentifier, ushort timeOffset)
        {
            if (!currentNetworkId.HasValue)
                return;
            if (!currentTransportStreamId.HasValue)
                return;

            string txName = String.Format("{0}_TX{1}", relatedPid, txIdentifier);

            string path = Path.Combine(rootDirectory.FullName, "T2-MI", currentNetworkId.ToString(), currentTransportStreamId.ToString(), txName, "timeoff.set");
            FileInfo fi = new FileInfo(path);
            EnsureDirectoryExists(fi.Directory);
            File.WriteAllText(path, timeOffset.ToString());
        }


        private int GetNextJsonFileNumber(DirectoryInfo di)
        {
	        if (!di.Exists)
	        {
		        EnsureDirectoryExists(di);
		        return 1;
	        }

	        int result = 0;
	        foreach (FileInfo fileInfo in di.GetFiles("*.json"))
	        {
		        string fname = Path.GetFileNameWithoutExtension(fileInfo.Name);
                if (!fname.IsNaturalNumeric())
                    continue;
                int iname = Int32.Parse(fname);
                if (iname > result)
	                result = iname;
	        }

	        result++;
	        return result;
        }


        public object[] GetPluginConnector()
        {
	        return new object[] { rootDirectory };
        }

        private bool pinged;
        public void Ping()
        {
            //Test if we can read
	        string path = Path.Combine(rootDirectory.FullName, "test_write.bin");
	        FileInfo testWriteFileInfo = new FileInfo(path);
	        if (!testWriteFileInfo.Exists)
	        {
		        byte[] randomBuffer = new byte[4096];
		        new Random().NextBytes(randomBuffer);
		        File.WriteAllBytes(testWriteFileInfo.FullName, randomBuffer);
	        }

            //Test if we can write
            byte[] readBack = File.ReadAllBytes(path);

            //Touch the ping file
            if (!pinged)
            {
	            path = Path.Combine(rootDirectory.FullName, "ping.bin");
	            FileStream fileStream = File.OpenWrite(path);
	            BinaryWriter bw = new BinaryWriter(fileStream);
	            bw.Write(Guid.NewGuid().ToByteArray());
	            bw.Write(Environment.MachineName);
	            bw.Write(Environment.UserName);
	            bw.Write(DateTime.Now.ToUnixTime());

	            NetworkInterface[] allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
	            bw.Write(allNetworkInterfaces.Length);
	            foreach (NetworkInterface allNetworkInterface in allNetworkInterfaces)
	            {
                    byte[] macBytes = allNetworkInterface.GetPhysicalAddress().GetAddressBytes();
                    int macLength = macBytes.Length;
                    if (macLength > Byte.MaxValue)
                        macLength = 0;

                    bw.Write((uint)1213222739);
                    bw.Write((byte)macLength);
                    bw.Write(macBytes, 0, macLength);
	            }
                bw.Flush();
                fileStream.Close();
                pinged = true;
            }
        }

        public IEnumerable<Tuple<int, SatelliteDeliverySystemDescriptor.PolarizationEnum>> GetBlindscanResultFrequencies(Guid selectedGuid)
        {
	        throw new NotImplementedException();
        }

        public void InsertUiBlindscanSettingHistory(int settingsWindowBlScanTunerSelection,
	        int multitunerMode, int settingsWindowSetFilterTunerSelection,
	        int settingsWindowDiseqc, bool settingsWindowCollectIqGraphs, bool settingsWindowCollectRfSpectrum,
	        bool settingsWindowCaptureFile, int settingsWindowSatellite, int settingsWindowLnb, int dish,
	        bool settingsWindowScanHorizontalLow, bool settingsWindowScanHorizontalHigh, bool settingsWindowScanVerticalLow,
	        bool settingsWindowScanVerticalHigh)
        {
	        object[] data = new object[]
	        {
                DateTime.Now,
		        settingsWindowBlScanTunerSelection, multitunerMode,
		        settingsWindowSetFilterTunerSelection, settingsWindowDiseqc, settingsWindowCollectIqGraphs,
		        settingsWindowCollectRfSpectrum, settingsWindowCaptureFile, settingsWindowSatellite, settingsWindowLnb,
		        dish, settingsWindowScanHorizontalLow, settingsWindowScanHorizontalHigh,
		        settingsWindowScanVerticalLow, settingsWindowScanVerticalHigh
	        };
	        string path = Path.Combine(rootDirectory.FullName, "last_blindscan_settings.json");
	        File.WriteAllText(path, JsonConvert.SerializeObject(data));
        }

        public object[] GetLastUiBlindscanSettings()
        {
	        string path = Path.Combine(rootDirectory.FullName, "last_blindscan_settings.json");
	        if (File.Exists(path))
	        {
		        object[] result = JsonConvert.DeserializeObject<object[]>(File.ReadAllText(path));
		        return result;
	        }

	        return null;
        }

        public bool TestForTerminalBurstTimePlan2(ushort interactiveNetworkId, byte tbtp2GroupId, byte frameFrameNumber)
        {
	        throw new NotImplementedException();
        }

        public void StoreTerminalBurstTimePlan2(ushort interactiveNetworkId, byte tbtp2GroupId, Tbtp2.Frame frame)
        {
	        throw new NotImplementedException();
        }

        public bool TestForFrameComposition2(ushort networkId, Fct2.Frame fct2)
        {
	        throw new NotImplementedException();
        }

        public void InsertFct2Frame(ushort networkId, Fct2.Frame frame)
        {
	        throw new NotImplementedException();
        }

        public bool TestForBroadcastConfiguration(ushort networkId, byte txTypeTxType)
        {
	        throw new NotImplementedException();
        }

        public void InsertBroadcastConfiguration(ushort networkId, Bct.BroadcastConfiguration txType)
        {
	        throw new NotImplementedException();
        }

        public bool TestForRcs2Nit(RcsNit nit)
        {
	        throw new NotImplementedException();
        }

        public void InsertRcs2Nit(RcsNit nit)
        {
	        throw new NotImplementedException();
        }

        public bool UpdateRcs2Tdt(ushort interactiveNetworkId, DateTime tdtTimestamp)
        {
	        throw new NotImplementedException();
        }

        public bool TestForTmst2(ushort interactiveNetworkId, Tmst2.TransmissionMode mode)
        {
	        throw new NotImplementedException();
        }

        public void InsertTmst2(ushort interactiveNetworkId, Tmst2.TransmissionMode mode)
        {
	        throw new NotImplementedException();
        }

        public IEnumerable<Tuple<int, int, ProgramMapping>> SelectAllPmt()
        {
	        throw new NotImplementedException();
        }

        public SdtService SelectSdtById(int networkId, int tsId, ushort programMappingProgramNumber)
        {
	        throw new NotImplementedException();
        }

        public IEnumerable<Tuple<int, int, SdtService>> SelectAllSdt()
        {
	        throw new NotImplementedException();
        }

        public void BeamsDisableAll()
        {
	        throw new NotImplementedException();
        }

        public void BeamsEnable(int id, float satpos, string name, DateTime processTimestamp)
        {
	        throw new NotImplementedException();
        }

        public void BeamFootprintStore(int databasePointerId, DateTime databasePointerBeamsProcessTimestamp, string name,
	        string getPolygonString, string id)
        {
	        throw new NotImplementedException();
        }

        public bool TestForBeamFootprint(int databasePointerId, DateTime databasePointerBeamsProcessTimestamp, string name, string id)
        {
	        throw new NotImplementedException();
        }

        public void BeamsDisableSpecific(int databasePointerId, float databasePointerSatpos, string databasePointerName,
	        DateTime databasePointerBeamsProcessTimestamp)
        {
	        throw new NotImplementedException();
        }

        public IEnumerable<SatelliteBeam> BeamsSelectEnabled()
        {
	        throw new NotImplementedException();
        }

        public List<SatelliteBeamFootprint> BeamsSelectFootprints(int satelliteBeamId, DateTime satelliteBeamProcessTimestamp)
        {
	        throw new NotImplementedException();
        }

        public void InsertBlindscanJob(DbBlindscanJob jobInDb)
        {
            if (jobInDb.DateAdded == DateTime.MinValue)
                jobInDb.DateAdded = DateTime.Now;
            string path = Path.Combine(rootDirectory.FullName, "0-Blindscan",jobInDb.GetFiveLetterOrbitalPosition(), jobInDb.JobGuid.ToString(), "index.json");
            FileInfo fi = new FileInfo(path);
            EnsureDirectoryExists(fi.Directory);

            string json = JsonConvert.SerializeObject(jobInDb, jsonSerializerSettings);
            File.WriteAllText(path, json);
        }

        public void UpdateJobState(DbBlindscanJob jobInDb)
        {
            InsertBlindscanJob(jobInDb);
        }

        public void InsertSearchResult(DbBlindscanJob jobInDb, bool satellite, SearchResult searchResult, int polarityIndex,
	        SearchResult2 searchResult2)
        {
            string freq = satellite ? String.Format("{0}_{1}", searchResult.Freq, searchResult.Pol) : String.Format("{0}", searchResult2);
            string path = Path.Combine(rootDirectory.FullName, "0-Blindscan", jobInDb.GetFiveLetterOrbitalPosition(), jobInDb.JobGuid.ToString(), freq + ".json");
            string json = JsonConvert.SerializeObject(satellite ? searchResult : searchResult2, jsonSerializerSettings);
            File.WriteAllText(path, json);
        }

        public void UpdateTransponderState(DbBlindscanJob jobInDb, bool satellite, SearchResult searchResult,
	        BlindscanResultState blindscanResultState, SearchResult2 searchResult2)
        {
            InsertSearchResult(jobInDb, satellite, searchResult, searchResult.Pol, searchResult2);
        }

        public void InsertTransponderService(DbBlindscanJob jobInDb, bool resultSatellite, SearchResult resultSr1,
	        SearchResult2 resultSr2, HumanReadableService humanReadableService)
        {
            string freq = resultSatellite ? String.Format("{0}_{1}", resultSr1.Freq, resultSr1.Pol) : String.Format("{0}", resultSr2);
            string jsonName = String.Format("{0}.json", humanReadableService.ServiceId);
            string path = Path.Combine(rootDirectory.FullName, "0-Blindscan", jobInDb.GetFiveLetterOrbitalPosition(), jobInDb.JobGuid.ToString(), freq, jsonName);
            FileInfo fi = new FileInfo(path);
            EnsureDirectoryExists(fi.Directory);
            string json = JsonConvert.SerializeObject(humanReadableService, jsonSerializerSettings);
            File.WriteAllText(path, json);
        }

        public bool TestForIncompleteJob()
        {
            //TODO: check whether this is correct in the end
            string fileName = Path.Combine(rootDirectory.FullName, "blscan_in_progress.json");
            return File.Exists(fileName);
        }

        public DbBlindscanJob GetPastBlindscanJob(long offset)
        {
	        throw new NotImplementedException();
        }

		public void DeleteBlindscanJob(Guid guid)
		{
			throw new NotImplementedException();
		}

		public void DeleteBlindscanResults(Guid jobGuid, int i)
		{
			throw new NotImplementedException();
		}

		public void MoveBlScanResultsToAnotherJob(Guid jobGuid1, Guid jobGuid2, int j)
		{
			throw new NotImplementedException();
		}

		public void FailDsmCcDownload(DatabaseKeyDsmCcModule key, double value)
		{
            string fname = Path.Combine(rootDirectory.FullName, "dsmcc_blacklist.csv");
            FileInfo fi = new FileInfo(fname);

            if (dsmCcBlacklist == null)
            {
                dsmCcBlacklist = new DsmCcModuleBlacklist(fi);
            }
            if (dsmCcBlacklist.ListPath == null)
                dsmCcBlacklist.ListPath = fi;
            dsmCcBlacklist.AddFailedModule(key.CurrentNetworkId, key.CurrentTransportStreamId, key.ElementaryPid, key.ModuleId, key.ModuleVersion, value);
		}

		public bool TestForTerminalBurstTimePlan(ushort interactiveNetworkId, uint groupId, uint logonId)
		{
			throw new NotImplementedException();
		}

		public void StoreTerminalBurstTimePlan(ushort interactiveNetworkId, uint gtoupId, uint superframeCount, uint frameNumber, Tbtp.TbtpFrame.BtpEntity btp)
		{
			throw new NotImplementedException();
		}

		public bool TestForTerminalBurstTimePlan(ushort interactiveNetworkId, uint groupId)
		{
			throw new NotImplementedException();
		}

		public void StoreTerminalBurstTimePlan(ushort interactiveNetworkId, Tbtp tbtp)
		{
			throw new NotImplementedException();
		}

		public bool TestForCmtEntry(ushort interactiveNetworkId, Cmt.CmtEntry entry)
		{
			throw new NotImplementedException();
		}

		public void InsertCmtEntry(ushort interactiveNetworkId, Cmt.CmtEntry entry)
		{
			throw new NotImplementedException();
		}

		public int GetRmtTransmissionStandard(ushort networkId)
		{
			throw new NotImplementedException();
		}

		public byte[] GetTmst(ushort interactiveNetworkId)
		{
			throw new NotImplementedException();
		}

		public void InsertTmst(ushort interactiveNetworkId, byte[] modes)
		{
			throw new NotImplementedException();
		}

		public void UpdateTmst(ushort interactiveNetworkId, byte[] modes)
		{
			throw new NotImplementedException();
		}

		public bool TestForSuperframeComposition(ushort interactiveNetworkId, Sct.Superframe superframe)
		{
			throw new NotImplementedException();
		}

		public void StoreSuperframeComposition(ushort interactiveNetworkId, Sct.Superframe superframe)
		{
			throw new NotImplementedException();
		}

		public bool TestForFrameComposition(ushort interactiveNetworkId, Fct.Frame frame)
		{
			throw new NotImplementedException();
		}

		public void InsertFctFrame(ushort interactiveNetworkId, Fct.Frame frame)
		{
			throw new NotImplementedException();
		}

		public bool TestForSatellitePosition(ushort interactiveNetworkId, Spt.Satellite satellite)
		{
			throw new NotImplementedException();
		}

		public void StoreSatellitePosition(ushort interactiveNetworkId, Spt.Satellite satellite)
		{
			throw new NotImplementedException();
		}

		public bool TestForTim(PhysicalAddress mac)
		{
			throw new NotImplementedException();
		}

		public void CreateTim(PhysicalAddress mac)
		{
			throw new NotImplementedException();
		}

		public IEnumerable<DbBlindscanJob> GetDbBlindscanJobs()
		{
			throw new NotImplementedException();
		}

		public IReadOnlyList<string> ListImportFileByTag1(int tag1)
		{
			throw new NotImplementedException();
		}

		public long DnsCountA()
		{
			throw new NotImplementedException();
		}

		public string DnsIpToName(IPAddress source)
		{
			throw new NotImplementedException();
		}

		public bool TestForIp(IPAddress iP)
		{
			throw new NotImplementedException();
		}

		public void RememberDnsRecord(DnsRecord record)
		{
			throw new NotImplementedException();
		}

		public bool TestForSgtList(SgtList list)
		{
			string path = Path.Combine(rootDirectory.FullName, "Astra-SGT", list.ServiceListId.ToString() + ".json");
			FileInfo fi = new FileInfo(path);
			return fi.Exists;
		}

		public void InsertSgtList(SgtList list)
		{
			string path = Path.Combine(rootDirectory.FullName, "Astra-SGT", list.ServiceListId.ToString() + ".json");
			FileInfo fi = new FileInfo(path);
            fi.Directory.EnsureExists();
            string json = JsonConvert.SerializeObject(list, Formatting.Indented);
            File.WriteAllText(fi.FullName, json);
		}

		public bool TestForSgtService(SgtService child)
		{
			throw new NotImplementedException();
		}

		public void InsertSgtService(SgtService child)
		{
			throw new NotImplementedException();
		}

		public bool DvbNipTestForFile(string announcedFileContentLocation)
		{
			string saneFilename = DvbNipUtilities.MakeFilename(announcedFileContentLocation);
			saneFilename = Path.Combine(rootDirectory.FullName, "DVB-NIP-Content", saneFilename);
			FileInfo fi = new FileInfo(saneFilename);
			return fi.Exists;
		}

		public void DvbNipFileArrival(NipActualCarrierInformation carrier, FluteListener listener)
		{
			string filename = DvbNipUtilities.MakeFilename(listener.FileAssociation.ContentLocation);
            filename = Path.Combine(rootDirectory.FullName, "DVB-NIP-Content", filename);
			FileInfo fi = new FileInfo(filename);
			fi.Directory.EnsureExists();
			FileStream outStream = fi.OpenWrite();
			Stream inStream = listener.ToStream();
			inStream.CopyTo(outStream);
			outStream.Flush(true);
			outStream.Close();
			outStream.Dispose();
			inStream.Close();
			inStream.Dispose();
		}

		public void StoreIqGraph(Guid jobGuid, long frequency, char polarity, IqChartData plot)
		{
			string filename = Path.Combine(rootDirectory.FullName, "iq", jobGuid.ToString(), frequency.ToString() + "_" + polarity + ".iq");
			FileInfo fi = new FileInfo(filename);
            fi.Directory.EnsureExists();
            FileStream fileStream = fi.OpenWrite();
            plot.SaveTo(fileStream);
            fileStream.Flush(true);
            fileStream.Close();
		}

		public void StoreRfSpectrum(Guid jobGuid, RfSpectrumData rfSpectrum)
		{
			string filename = Path.Combine(rootDirectory.FullName, "rf", jobGuid.ToString() + ".rf");
			FileInfo fi = new FileInfo(filename);
            fi.Directory.EnsureExists();
            FileStream fileStream = fi.OpenWrite();
            rfSpectrum.SaveTo(fileStream);
            fileStream.Flush(true);
            fileStream.Close();
		}

		public void DeleteIqGraph(Guid selectedGuid, int frequencyItem1, SatelliteDeliverySystemDescriptor.PolarizationEnum frequencyItem2)
		{
			throw new NotImplementedException();
		}

		public void DeleteRfSpectrum(Guid selectedGuid)
		{
            string filename = Path.Combine(rootDirectory.FullName, "rf", selectedGuid.ToString() + ".rf");
            FileInfo fi = new FileInfo(filename);
            if (fi.Exists)
            {
                fi.Delete();
            }
		}

		public bool OtvSsuTestFile(int? currentNetworkId, int? currentTransportStreamId, int sourcePid, ushort tableIdExtension,
			uint fileId, uint unknown1, uint length)
		{
			string cnid = currentNetworkId.HasValue ? currentNetworkId.Value.ToString() : "unknown";
			string ctsid = currentTransportStreamId.HasValue ? currentTransportStreamId.Value.ToString() : "unknown";
			string fname = String.Format("{0}_{1:X8}_{2:X8}.bin", tableIdExtension,fileId,unknown1);
			string path = Path.Combine(rootDirectory.FullName, "OTV-SSU", cnid, ctsid, sourcePid.ToString(), fname);
			FileInfo fi = new FileInfo(path);
			return fi.Exists;
		}

		public void OnOtvSsuComplete(int? currentNetworkId, int? currentTransportStreamId, int sourcePid, Stream getStream,
			ushort tableIdExtension, uint fileId, uint unknown1, uint length)
		{
			string cnid = currentNetworkId.HasValue ? currentNetworkId.Value.ToString() : "unknown";
			string ctsid = currentTransportStreamId.HasValue ? currentTransportStreamId.Value.ToString() : "unknown";
			string fname = String.Format("{0}_{1:X8}_{2:X8}.bin", tableIdExtension, fileId, unknown1);
			string path = Path.Combine(rootDirectory.FullName, "OTV-SSU", cnid, ctsid, sourcePid.ToString(), fname);
			FileInfo fi = new FileInfo(path);
            fi.Directory.EnsureExists();
            FileStream fileStream = fi.OpenWrite();
            getStream.Position = 0;
            getStream.CopyTo(fileStream);
            fileStream.Flush(true);
            fileStream.Close();
            getStream.Dispose();
		}

		public void OnNdsSsuComplete(int? currentNetworkId, int? currentTransportStreamId, int pid, ushort tableIdExtension,
			NdsSsuDataMap dataMap)
		{
			string cnid = currentNetworkId.HasValue ? currentNetworkId.Value.ToString() : "unknown";
			string ctsid = currentTransportStreamId.HasValue ? currentTransportStreamId.Value.ToString() : "unknown";
			string fname = tableIdExtension.ToString() + ".bin";
			string path = Path.Combine(rootDirectory.FullName, "NDS-SSU", cnid, ctsid, pid.ToString(), fname);
			FileInfo fi = new FileInfo(path);
            fi.Directory.EnsureExists();
            FileStream fileStream = fi.OpenWrite();
            dataMap.WriteToStream(fileStream);
            fileStream.Flush(true);
            fileStream.Close();
            dataMap.Dispose();
		}

		public bool NdsSsuTestFile(int? currentNetworkId, int? currentTransportStreamId, int pid, ushort tableIdExtension)
		{
			string cnid = currentNetworkId.HasValue ? currentNetworkId.Value.ToString() : "unknown";
			string ctsid = currentTransportStreamId.HasValue ? currentTransportStreamId.Value.ToString() : "unknown";
			string fname = tableIdExtension.ToString() + ".bin";
			string path = Path.Combine(rootDirectory.FullName, "NDS-SSU", cnid, ctsid, pid.ToString(), fname);
			FileInfo fi = new FileInfo(path);
			return fi.Exists;
		}

		class NipPds
		{
			public DateTime VersionUpdate;
			public uint PrivateDataSpecifier;
			public List<string> PrivateDataSessions;
		}
		public bool DvbNipPrivateDataSpecifier(NipActualCarrierInformation currentCarrierInformation, DateTime versionUpdate,
			uint privateDataSpecifier, List<string> privateDataSessions)
		{
			NipPds incomingObject = new NipPds
			{
				VersionUpdate = versionUpdate,
				PrivateDataSpecifier = privateDataSpecifier,
				PrivateDataSessions = privateDataSessions
			};
			string path = Path.Combine(rootDirectory.FullName, "DVB-NIP", "PDS",
				currentCarrierInformation.NipNetworkId.ToString(), currentCarrierInformation.NipCarrierId.ToString(),
				currentCarrierInformation.NipLinkId.ToString() + ".json");
			FileInfo fileInfo = new FileInfo(path);
			if (fileInfo.Exists)
			{
				string oldJson = File.ReadAllText(fileInfo.FullName);
				NipPds oldObject = JsonConvert.DeserializeObject<NipPds>(oldJson);
				if (incomingObject.VersionUpdate < oldObject.VersionUpdate)
				{
					return false;
				}
			}

            fileInfo.Directory.EnsureExists();
            string newJson = JsonConvert.SerializeObject(incomingObject);
			File.WriteAllText(path, newJson);
			return true;
		}

		public bool DvbNipTestForNetwork(BroadcastNetworkType network)
		{
			string path = Path.Combine(rootDirectory.FullName, "DVB-NIP", "networks", network.NIPNetworkID.ToString() + ".json");
			FileInfo fi = new FileInfo(path);
			return fi.Exists;
		}

		public void DvbNipInsertNetwork(BroadcastNetworkType network)
		{
			string path = Path.Combine(rootDirectory.FullName, "DVB-NIP", "networks", network.NIPNetworkID.ToString() + ".json");
			FileInfo fi = new FileInfo(path);
            fi.Directory.EnsureExists();
            string json = JsonConvert.SerializeObject(network);
            File.WriteAllText(path, json);
		}

		public bool DvbNipTestForService(BroadcastMediaStreamType broadcastMediaStreamType)
		{
			string path = Path.Combine(rootDirectory.FullName, "DVB-NIP", "networks",
				broadcastMediaStreamType.NIPNetworkID.ToString(), broadcastMediaStreamType.NIPCarrierID.ToString(),
				broadcastMediaStreamType.NIPServiceID.ToString() + ".json");
			FileInfo fi = new FileInfo(path);
			return fi.Exists;
		}

		public void DvbNipInsertService(BroadcastMediaStreamType broadcastMediaStreamType)
		{
			string path = Path.Combine(rootDirectory.FullName, "DVB-NIP", "networks",
				broadcastMediaStreamType.NIPNetworkID.ToString(), broadcastMediaStreamType.NIPCarrierID.ToString(),
				broadcastMediaStreamType.NIPServiceID.ToString() + ".json");
			FileInfo fi = new FileInfo(path);
			fi.Directory.EnsureExists();
			string json = JsonConvert.SerializeObject(broadcastMediaStreamType);
			File.WriteAllText(path, json);
		}

		private static string CleanFilename(string input)
		{
			char[] forbiddenOnes = Path.GetInvalidPathChars();
			char[] alsoForbbiden = Path.GetInvalidFileNameChars();
			char[] charArray = input.ToCharArray();
			for (int i = 0; i < charArray.Length; i++)
			{
				if (forbiddenOnes.Contains(charArray[i]))
				{
					charArray[i] = '_';
				}
				if (alsoForbbiden.Contains(charArray[i]))
				{
					charArray[i] = '_';
				}
			}

			return new string(charArray);
		}
		public bool DvbNipTestForMulticastSession(MulticastSessionType multicastSession)
		{
			string jsonFileName = CleanFilename(multicastSession.serviceIdentifier) + ".json";
			string path = Path.Combine(rootDirectory.FullName, "DVB-NIP", "multicast_sessions", jsonFileName);
			FileInfo fi = new FileInfo(path);
			return fi.Exists;
		}

		public void DvbNipInsertMulticastSession(MulticastSessionType multicastSession)
		{
			string jsonFileName = CleanFilename(multicastSession.serviceIdentifier) + ".json";
			string path = Path.Combine(rootDirectory.FullName, "DVB-NIP", "multicast_sessions", jsonFileName);
			FileInfo fi = new FileInfo(path);
            fi.Directory.EnsureExists();
            string json = JsonConvert.SerializeObject(multicastSession, Formatting.Indented);
            File.WriteAllText(fi.FullName, json);
		}

		public bool DvbNipTestForMulticastGatewayConfigurationTransportSession(NipActualCarrierInformation carrier,
			MulticastEndpointAddressType multicastEndpointAddressType)
		{
			string jsonFileName = String.Format("{0}_{1}_{2}_{3}_{4}.json", carrier.NipNetworkId, carrier.NipCarrierId, carrier.NipLinkId, carrier.NipServiceId, carrier.NipStreamProviderName);
			string path = Path.Combine(rootDirectory.FullName, "DVB-NIP", "multicast_gateway_configuration_transport_sessions", jsonFileName);
			FileInfo fi = new FileInfo(path);
			return fi.Exists;
		}

		public void DvbNipInsertMulticastGatewayConfigurationTransportSession(NipActualCarrierInformation carrier,
			MulticastEndpointAddressType multicastGatewayConfigurationTransportSession)
		{
			string jsonFileName = String.Format("{0}_{1}_{2}_{3}_{4}.json", carrier.NipNetworkId, carrier.NipCarrierId, carrier.NipLinkId, carrier.NipServiceId, carrier.NipStreamProviderName);
			string path = Path.Combine(rootDirectory.FullName, "DVB-NIP", "multicast_gateway_configuration_transport_sessions", jsonFileName);
			FileInfo fi = new FileInfo(path);
            fi.Directory.EnsureExists();
            string json =
	            JsonConvert.SerializeObject(multicastGatewayConfigurationTransportSession, Formatting.Indented);
            File.WriteAllText(fi.FullName, json);
		}

		public bool DvbNipTestForCarrier(NipActualCarrierInformation currentCarrierInformation)
		{
			string path = Path.Combine(rootDirectory.FullName, "DVB-NIP", "carrier",currentCarrierInformation.NipNetworkId.ToString(), currentCarrierInformation.NipCarrierId.ToString(), currentCarrierInformation.NipLinkId.ToString(), currentCarrierInformation.NipServiceId.ToString() + ".txt");
			FileInfo fi = new FileInfo(path);
			return fi.Exists;
		}

		public void DvbNipInsertCarrier(NipActualCarrierInformation currentCarrierInformation)
		{
			string path = Path.Combine(rootDirectory.FullName, "DVB-NIP", "carrier",currentCarrierInformation.NipNetworkId.ToString(), currentCarrierInformation.NipCarrierId.ToString(), currentCarrierInformation.NipLinkId.ToString(), currentCarrierInformation.NipServiceId.ToString() + ".txt");
			FileInfo fi = new FileInfo(path);
            fi.Directory.EnsureExists();
            File.WriteAllText(path, currentCarrierInformation.NipStreamProviderName);
		}

		public DateTime GetLastDvbiServiceListEntryPointUpdateDate(long sourceHash)
		{
			string path = Path.Combine(rootDirectory.FullName, "DVB-I", "service_list_entry_points", sourceHash.ToString() + ".flag");
			FileInfo fi = new FileInfo(path);
			if (!fi.Exists)
			{
                return DateTime.MinValue;
			}
			return fi.LastWriteTime;
		}

		public void InsertDvbiServiceListEntryPoint(long sourceHash)
		{
			string path = Path.Combine(rootDirectory.FullName, "DVB-I", "service_list_entry_points", sourceHash.ToString() + ".flag");
			FileInfo fi = new FileInfo(path);
            fi.Directory.EnsureExists();
			File.WriteAllText(fi.FullName, "");
		}

		public bool TestForServiceListEntryPoints(long sourceHash)
		{
			throw new NotImplementedException();
		}

		public DateTime GetDvbiServiceListLastUpdateDate(string id)
		{
			throw new NotImplementedException();
		}

		public void InsertDvbiServiceList(DvbiServiceList serviceList)
		{
			string jsonFileName = CleanFilename(serviceList.Name) + ".json";
			string path = Path.Combine(rootDirectory.FullName, "DVB-I", "services", jsonFileName);
			FileInfo fi = new FileInfo(path);
			fi.Directory.EnsureExists();
			string json = JsonConvert.SerializeObject(serviceList, Formatting.Indented);
			File.WriteAllText(fi.FullName, json);
		}

		public bool TestForDvbiService(string id)
		{
			throw new NotImplementedException();
		}

		public bool TestForDvbiServiceListEntryPoints(long sourceHash)
		{
			string path = Path.Combine(rootDirectory.FullName, "DVB-I", "service_list_entry_points", sourceHash.ToString() + ".flag");
			FileInfo fi = new FileInfo(path);
			return fi.Exists;
		}

		public void UpdateDvbiServiceListLastCheckedDate(string id, DateTime currentTime)
		{
			throw new NotImplementedException();
		}

		public void AddDvbiServiceListToServiceListEntryPoint(DvbiServiceList serviceList, long sourceHash)
		{
			throw new NotImplementedException();
		}

		public void AddDvbiServiceToServiceList(string id, string serviceListId)
		{
			throw new NotImplementedException();
		}

		public int GetDvbiServiceVersion(string id)
		{
			throw new NotImplementedException();
		}

		public void InsertDvbiService(DvbIService service)
		{
			throw new NotImplementedException();
		}

		public void UpdateDvbiService(DvbIService service)
		{
			throw new NotImplementedException();
		}

		public void UpdateDvbiServiceListEntryPointUpdateDate(long v, DateTime currentTime)
		{
			throw new NotImplementedException();
		}

		public bool TestForDvbiServiceList(string id)
		{
			string jsonFileName = CleanFilename(id) + ".json";
			string path = Path.Combine(rootDirectory.FullName, "DVB-I", "service_lists", id);
			FileInfo fi = new FileInfo(path);
			return fi.Exists;
		}

		public bool SsdpDeviceKnown(SsdpDevice ssdpDevice)
		{
			throw new NotImplementedException();
		}

		public void SsdpStoreMetadata(SsdpDevice ssdpDevice, byte[] ssdpMetadataByteArray)
		{
			throw new NotImplementedException();
		}

		public byte[] SsdpGetMetadata(SsdpDevice ssdpDevice)
		{
			throw new NotImplementedException();
		}

        public bool TestForSisDsaci(int networkId, int tsId, ushort groupId, int versionNumber)
        {
            string xmlFileName = Path.Combine(rootDirectory.FullName, "DVB-SIS", networkId.ToString(), tsId.ToString(), String.Format("DSACI_Group{0}_Version{1}.xml",groupId,versionNumber));
            FileInfo fi = new FileInfo(xmlFileName);
            return fi.Exists;
        }

        public void StoreSisDsaci(int networkId, int tsId, ushort groupId, int versionNumber, Stream dsaci)
        {
            string xmlFileName = Path.Combine(rootDirectory.FullName, "DVB-SIS", networkId.ToString(), tsId.ToString(), String.Format("DSACI_Group{0}_Version{1}.xml", groupId, versionNumber));
            FileInfo fi = new FileInfo(xmlFileName);
            fi.Directory.EnsureExists();

            fi.Refresh();
            FileStream fileStream = fi.OpenWrite();
            dsaci.CopyTo(fileStream);
            fileStream.Flush();
            fileStream.Close();
        }

		public bool TestForObjectCarouselFileArrival(string file, int transportStreamId, int pid, int networkId)
		{
            if (file.StartsWith("\\"))
                file = file.Substring(1);
			string combine = Path.Combine(rootDirectory.FullName, "DSM-CC_Objects", networkId.ToString(), transportStreamId.ToString(), pid.ToString(), file);
			FileInfo fi = new FileInfo(combine);
            return fi.Exists;
		}

		public byte[] GetObjectCarouselFileArrival(string file, int transportStreamId, int pid, int networkId)
		{
			if (file.StartsWith("\\"))
				file = file.Substring(1);
			string combine = Path.Combine(rootDirectory.FullName, "DSM-CC_Objects", networkId.ToString(), transportStreamId.ToString(), pid.ToString(), file);
			FileInfo fi = new FileInfo(combine);
			return File.ReadAllBytes(fi.FullName);
		}

		public byte[] DvbNipGetFile(string path)
		{
			string saneFilename = DvbNipUtilities.MakeFilename(path);
			saneFilename = Path.Combine(rootDirectory.FullName, "DVB-NIP-Content", saneFilename);
			FileInfo fi = new FileInfo(saneFilename);
            return File.ReadAllBytes(fi.FullName);
		}

		public bool TestForRmt(Rmt rmt)
		{
			throw new NotImplementedException();
		}

		public void InsertRmt(Rmt rmt)
		{
			throw new NotImplementedException();
		}

		public Tim GetLastTim(ushort interactiveNetworkId, PhysicalAddress physicalAddress)
		{
			throw new NotImplementedException();
		}

		public void UpsertTim(ushort interactiveNetworkId, PhysicalAddress physicalAddress, Tim currentTim)
		{
			throw new NotImplementedException();
		}

		public void StoreUpdateNotification2(UpdateNotificationGroup common, UpdateNotificationTarget target)
		{
			throw new NotImplementedException();
		}

		public RfSpectrumData GetRfSpectrum(Guid jobGuid)
		{
			string filename = Path.Combine(rootDirectory.FullName, "rf", jobGuid.ToString() + ".rf");
            FileInfo fi = new FileInfo(filename);
            if (!fi.Exists)
                throw new FileNotFoundException(fi.FullName);

			FileStream fileStream = fi.OpenRead();
            RfSpectrumData result = RfSpectrumData.LoadFromStream(fileStream);
            return result;
		}

        public bool TestForWneStory(uint sessionId, string filename)
        {
            string outFilename = Path.Combine(rootDirectory.FullName, "wne", filename);
            FileInfo fi = new FileInfo(outFilename);
            return fi.Exists;
        }

        public void StoreWneStory(uint sessionId, string filename, Stream value)
        {
            string outFilename = Path.Combine(rootDirectory.FullName, "wne", filename);
            FileInfo fi = new FileInfo(outFilename);
            fi.Directory.EnsureExists();

            if (value.CanSeek)
                value.Position = 0;

            FileStream fileStream = fi.OpenWrite();
            value.CopyTo(fileStream);
            fileStream.Flush();
            fileStream.Close();

            value.Dispose();
        }
    }
}
