Advertisement
Guest User

Untitled

a guest
Jan 17th, 2017
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Imports System.Configuration   '<- Check if this import is needed
  2. Imports System.Linq
  3. Imports System.IO
  4. Imports System.IO.Compression
  5.  
  6. Public Class frmMain
  7.  
  8.     ' Allows Folder Monitor to set the visibility
  9.    Private isVisible As Boolean = False
  10.     Public isHidden As Boolean = False
  11.     Public isIgnoreCommandArguments As Boolean = False
  12.  
  13.     'Notifiy SEDBE File Monitor
  14.    Public Event ConversionCompleted(pct As Integer, timeLeft As String, isBusy As Boolean, filename As String) 'pct between 0 and 100, timeLeft in seconds
  15.    Public Event ErrorReport(message As String)
  16.  
  17.     Private Enum enmTasks
  18.         DoNothing
  19.         ProcessDragAndDropFiles
  20.         ProcessFolderfile
  21.     End Enum
  22.  
  23.     Private Enum enmThresholdType
  24.         CPFA
  25.         SNR
  26.     End Enum
  27.     Private Enum enmWindow
  28.         Rectangular
  29.         Hann
  30.         Blackman
  31.         FlatTop
  32.     End Enum
  33.  
  34.     Private Enum enmFrame_Avg
  35.         PERIODIGRAM
  36.         POLYPHASE
  37.         OVERLAP50%
  38.     End Enum
  39.  
  40.     Private Structure udtHeader
  41.         Public VERSION As Single
  42.         Public SENSOR_ROLE As String
  43.         Public SENSOR_OUTPUT As String
  44.         Public SENSOR_HOST_ID As String
  45.         Public SENSOR_TECHNOLOGY As String
  46.         Public SENSOR_HW_ID As String
  47.         Public TASK_MISSION As String
  48.         Public StartDateTime As DateTime
  49.         Public StopDateTime As DateTime
  50.         Public TimeZoneOffset As TimeSpan
  51.         Public TimeZoneCorrection As Boolean
  52.         Public FREQ_RANGE() As Double
  53.         Public LOCATION As String
  54.     End Structure
  55.  
  56.     Private MyHeader As udtHeader
  57.  
  58.     Private Structure udtLocationBox
  59.         Public LatMax As Double
  60.         Public LatMin As Double
  61.         Public LonMax As Double
  62.         Public LonMin As Double
  63.         Public AltMax As Double
  64.         Public AltMin As Double
  65.     End Structure
  66.  
  67.     Private MyBox As udtLocationBox
  68.     Private MyGlobalBox As udtLocationBox
  69.  
  70.     Private Structure udtSubHeader
  71.         Public REVISIT_TIME_s As Double
  72.         Public RESOLUTION_BW_Hz As Double
  73.         Public THRESHOLD_TYPE As enmThresholdType
  74.         Public THRESHOLD As Double
  75.         Public BW_ESTIMATION_RATIO As Double
  76.         Public FFT_WINDOW As enmWindow
  77.         Public FRAME_AVG As enmFrame_Avg
  78.         Public FRAME_NB As Integer
  79.         Public ISDF As Boolean
  80.         Public ANALYSIS_DURATION_MIN As Double
  81.         Public MEASUREMENTFILE As String
  82.     End Structure
  83.  
  84.     Private MySubHeader As udtSubHeader
  85.     Private MyPeriod As Integer
  86.  
  87.     Private Structure udtRange
  88.         Public Offset As Integer
  89.         Public RangeStart As Integer
  90.         Public RangeStop As Integer
  91.     End Structure
  92.  
  93.     Private Structure Histos
  94.         Public Power_dBmHisto() As Integer
  95.         Public SNR_dBHisto() As Integer
  96.         Public BandwidthPercentRangeHisto() As Integer
  97.         Public CORangePercentHisto() As Integer
  98.         Public BurstOn_dBmsHisto() As Integer
  99.         Public BurstOff_dBmsHisto() As Integer
  100.     End Structure
  101.     Private MyHisto() As Histos
  102.  
  103.     Private Structure Channels
  104.         Public BW() As Double
  105.         Public Carrier() As Double
  106.         Public Count() As Integer
  107.         Public ID() As Integer
  108.         Public BurstStateCurrent() As Boolean
  109.         Public BurstStatePrevious() As Boolean
  110.         Public BurstTime() As DateTime
  111.         Public IndexCurrentlyOn() As Integer
  112.         Public IndexPreviouslyOn() As Integer
  113.     End Structure
  114.  
  115.     Private Structure MeasurementData
  116.         Public FixedDate As String
  117.         Public Latitude As Double
  118.         Public Longitude As Double
  119.         Public Altitude As Double
  120.         Public Status As Integer
  121.         Public MovementStatus As Integer
  122.         Public GroundSpeed As Double
  123.         Public GroundAcceleration As Double
  124.         Public TrackMadeGood As Double
  125.         Public TrueHeading As Double
  126.         Public ChannelNum As Integer
  127.         Public Power As Double
  128.         Public SNR As Double
  129.         Public Freq As Double
  130.         Public BW As Double
  131.         Public Dir As Double
  132.         Public DirQuality As Double
  133.     End Structure
  134.     Private MyChannels As Channels
  135.  
  136.     Private Power_dBmRange As udtRange
  137.     Private SNR_dBRange As udtRange
  138.     Private BandwidthPercentRange As udtRange
  139.     Private CORangePercentRange As udtRange
  140.     Private Burst_dBmsRange As udtRange
  141.  
  142.     Private AverageRevisitCount As Integer
  143.     Private IsPointAllowed As Boolean = False
  144.     Private TOTAL_FREQUENCIES As Integer
  145.     Private Description As String
  146.  
  147.     Private MyTitle As String
  148.     Private isClosing As Boolean
  149.     Private isCanceled As Boolean
  150.     Private MyTimerTask As enmTasks
  151.     Private MyDragAndDropFiles As String()
  152.     Private folderpath As String
  153.  
  154.     Public Sub New()
  155.  
  156.         ' This call is required by the Windows Form Designer.
  157.        InitializeComponent()
  158.  
  159.         ' Add any initialization after the InitializeComponent() call.
  160.        Me.AllowDrop = True  ' Enable drag-and-drop operations.
  161.  
  162.         ' Hide the form by default
  163.        Me.ShowInTaskbar = False
  164.         Me.WindowState = FormWindowState.Minimized
  165.  
  166.     End Sub
  167.  
  168.     Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  169.  
  170.         'Default values
  171.        MyTitle = My.Application.Info.Title()
  172.         Me.Text = MyTitle
  173.         dlgOpenFile.SelectedPath = ""
  174.         btnCancel.Enabled = False
  175.         lblVersion.Text = MyTitle & " " & My.Application.Info.Version.ToString
  176.         lblCopyright.Text = "Copyright © 2008-2016 Communications Research Centre Canada"
  177.         Dim listFile As New List(Of String)
  178.         Dim MyDragAndDropFiles(0 To 0) As String
  179.  
  180.         'Process command line arguments if provided
  181.        'And then quit
  182.        If isIgnoreCommandArguments = False Then
  183.             If My.Application.CommandLineArgs.Count > 0 Then
  184.                 'Arguments supported:
  185.                '- Invisible                                 /hide
  186.                '- One or more filename with double quotes   "c:\temp\mylogfile0.txt" "c:\temp\mylogfile1.txt" "c:\temp\mylogfile2.txt" "c:\temp\mylogfile3.txt"
  187.                For Each argument As String In My.Application.CommandLineArgs
  188.                     Select Case argument
  189.                         Case "/?"
  190.                             DisplayHelpFile()
  191.                             Me.Close()
  192.                         Case "/hide"
  193.                             isHidden = True
  194.                         Case Else
  195.                             'This must be a file to convert
  196.                            'Remove double quotes and add to a list of files to be converted
  197.                            argument = Replace(argument, """", "")
  198.                             If argument.Length > 0 Then
  199.                                 listFile.Add(argument)
  200.                             End If
  201.                     End Select
  202.                 Next
  203.             End If
  204.         End If
  205.  
  206.         'Show the main window if it's not being forced to hide with /hide argument
  207.        If isHidden = False Then
  208.             isVisible = True
  209.             Me.Show()
  210.             Me.ShowInTaskbar = True
  211.             Me.WindowState = FormWindowState.Normal
  212.         End If
  213.  
  214.         ' Load settings
  215.        cmbPeriod.SelectedIndex = My.Settings.Periode
  216.         txtSite.Text = My.Settings.SiteName
  217.         txtHW.Text = My.Settings.HWName
  218.         ckbHisto.Checked = My.Settings.Histo
  219.         ckbMeasurement.Checked = My.Settings.Measurement
  220.         txtNbFrames.Text = My.Settings.NbFrames
  221.         txtBWRatio.Text = My.Settings.BWRatio
  222.         txtTimezoneOffset.Text = My.Settings.TimeZone
  223.         ckbCorrectForUTC.Checked = My.Settings.TimeZoneCorrection
  224.  
  225.         ' Start the file conversion
  226.        ' if hidden, start right away
  227.        ' if visible, use a seperate thread (e.g. a timer's threaded event)
  228.        For Each fn As String In listFile
  229.             ConvertFile(fn)
  230.         Next
  231.  
  232.         'Close the application once it's done processing command arguments
  233.        'as part of a batch file script
  234.        If isHidden = True Then
  235.             Me.Close()
  236.         End If
  237.  
  238.     End Sub
  239.  
  240.     Private Sub frmMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
  241.  
  242.         'Inform any running algorithm of the application shutdown
  243.        isClosing = True
  244.  
  245.         ' Save settings
  246.        My.Settings.Periode = cmbPeriod.SelectedIndex
  247.         My.Settings.SiteName = txtSite.Text
  248.         My.Settings.HWName = txtHW.Text
  249.         My.Settings.Histo = ckbHisto.Checked
  250.         My.Settings.Measurement = ckbMeasurement.Checked
  251.         My.Settings.NbFrames = txtNbFrames.Text
  252.         My.Settings.BWRatio = txtBWRatio.Text
  253.         My.Settings.TimeZone = txtTimezoneOffset.Text
  254.         My.Settings.TimeZoneCorrection = ckbCorrectForUTC.Checked
  255.         My.Settings.Save()
  256.  
  257.     End Sub
  258.  
  259.     Private Sub frmMain_VisibleChanged(sender As Object, e As EventArgs) Handles Me.VisibleChanged
  260.         'DirectCast(sender, Form).Visible = isVisible
  261.        If isVisible Then
  262.             Me.ShowInTaskbar = True
  263.             Me.WindowState = FormWindowState.Normal
  264.         Else
  265.             Me.ShowInTaskbar = False
  266.             Me.WindowState = FormWindowState.Minimized
  267.         End If
  268.     End Sub
  269.  
  270.     Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
  271.  
  272.         'Inform any running algorithm of the user's intervention
  273.        isCanceled = True
  274.         btnCancel.Enabled = False
  275.  
  276.     End Sub
  277.  
  278.     Private Sub btnOpenFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenFile.Click
  279.  
  280.         'Offer the user the choice to pick a file
  281.        If dlgOpenFile.ShowDialog() = Windows.Forms.DialogResult.OK Then
  282.             folderpath = dlgOpenFile.SelectedPath
  283.             MyTimerTask = enmTasks.ProcessFolderfile
  284.             tmrTimer.Enabled = True
  285.         End If
  286.  
  287.     End Sub
  288.  
  289.     Private Sub frmMain_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Me.DragEnter
  290.  
  291.         ' If the data is a file, display the copy cursor.
  292.        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
  293.             e.Effect = DragDropEffects.Copy
  294.         Else
  295.             e.Effect = DragDropEffects.None
  296.         End If
  297.  
  298.     End Sub
  299.  
  300.     Private Sub frmMain_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop
  301.  
  302.         'Convert a file given through drag-and-drop
  303.        Try
  304.             Dim Files As String()
  305.             Files = CType(e.Data.GetData(DataFormats.FileDrop), String())
  306.             If Files.Length > 0 Then
  307.                 MyDragAndDropFiles = Files
  308.                 MyTimerTask = enmTasks.ProcessDragAndDropFiles
  309.                 tmrTimer.Enabled = True
  310.             End If
  311.         Catch ex As Exception
  312.  
  313.         End Try
  314.  
  315.     End Sub
  316.  
  317.     Private Function UnzipDirectory(ByVal SourceFilename As String, ByVal Path As String, ByVal IsHisto As Boolean, ByVal IsMeasurement As Boolean) As Boolean
  318.         '"Path" should contain path of folder
  319.        Dim isSuccess As Boolean = True
  320.         Dim dInfo As New DirectoryInfo(SourceFilename)
  321.         Dim OutputFiles As String = Path + "\Output_Files"
  322.         My.Computer.FileSystem.CreateDirectory(OutputFiles)
  323.  
  324.         'Walk through the folder and parse each individual file, only looking for .zips
  325.        For Each File In dInfo.GetFiles()
  326.             Dim FileValue As String = SourceFilename + "\" + File.Name
  327.             If InStr(FileValue, ".zip") > 0 Then
  328.                 isSuccess = Consolidate(FileValue, SourceFilename, OutputFiles, IsHisto, IsMeasurement)
  329.             End If
  330.             If Not isSuccess Then
  331.                 Exit For
  332.             End If
  333.         Next
  334.         Return isSuccess
  335.     End Function
  336.  
  337.     Private Function Consolidate(ByVal SourceFilename As String, ByVal Path As String, ByVal DestinationPath As String, ByVal IsHisto As Boolean, ByVal IsMeasurement As Boolean) As Boolean
  338.  
  339.         Dim FailedOutputFilename As String
  340.         Dim OutputFilename As String
  341.         Dim Result As Boolean
  342.  
  343.         'Protect the function
  344.        If SourceFilename.Length <= 0 Then
  345.             Return False
  346.         End If
  347.         'Unzip file
  348.        Dim extractPath As String = Path + "\extract"
  349.  
  350.         My.Computer.FileSystem.CreateDirectory(extractPath)
  351.         Console.Write("Extracting    ")
  352.         Console.WriteLine(SourceFilename)
  353.         ZipFile.ExtractToDirectory(SourceFilename, extractPath)
  354.  
  355.         'Get the largest file - this will be the new source file.
  356.        Dim files() As String = Directory.GetFiles(extractPath)
  357.         Dim sorted() As String = files.OrderByDescending(
  358.             New Func(Of String, Integer)(Function(fn As String)
  359.                                              Return New FileInfo(fn).Length
  360.                                          End Function)).ToArray
  361.         Dim UnzippedSourceFilename As String = sorted(0)
  362.  
  363.  
  364.  
  365.         'Lock the GUI
  366.        btnOpenFile.Enabled = False
  367.         lblStatus.ForeColor = Color.Black
  368.         lblSource.Text = UnzippedSourceFilename
  369.         OutputFilename = Replace(UnzippedSourceFilename, ".txt", ".histo")
  370.         FailedOutputFilename = Replace(UnzippedSourceFilename, ".txt", ".fail")
  371.         lblDestination.Text = OutputFilename
  372.         lblStatus.Text = "Consolidation in progress..."
  373.         pgbStatus.Value = 0
  374.         Me.Text = "0" & "% - " & OutputFilename
  375.         btnCancel.Enabled = True
  376.         MyPeriod = CInt(cmbPeriod.Text)
  377.  
  378.  
  379.         RaiseEvent ConversionCompleted(pgbStatus.Value, "Estimating", True, OutputFilename) 'Notifiy SEDBE File Monitor
  380.        ConversionCompletedToStdOutput(pgbStatus.Value, "Estimating", True, UnzippedSourceFilename, OutputFilename)
  381.  
  382.  
  383.         'Delete any previously failed conversions
  384.        Try
  385.             If System.IO.File.Exists(FailedOutputFilename) Then
  386.                 Kill(FailedOutputFilename)
  387.             End If
  388.             If System.IO.File.Exists(OutputFilename) Then
  389.                 Kill(OutputFilename)
  390.             End If
  391.         Catch ex As Exception
  392.             'Ignore errors
  393.        End Try
  394.  
  395.  
  396.         'Request an MDB conversion
  397.        If IsHisto Then
  398.             Result = ConvertToHisto(UnzippedSourceFilename, OutputFilename, Path, DestinationPath)
  399.         End If
  400.         If IsMeasurement Then
  401.             Result = ConvertToMeasurement(UnzippedSourceFilename, OutputFilename, Path, DestinationPath)
  402.         End If
  403.         'Delete extraneous directories
  404.        My.Computer.FileSystem.DeleteDirectory(extractPath, FileIO.DeleteDirectoryOption.DeleteAllContents)
  405.  
  406.         If Result Then
  407.             lblStatus.Text = "Consolidation successful!"
  408.             lblStatus.ForeColor = Color.Green
  409.             pgbStatus.Value = 100
  410.             RaiseEvent ConversionCompleted(pgbStatus.Value, lblStatus.Text, False, OutputFilename) 'Notifiy SEDBE File Monitor
  411.            ConversionCompletedToStdOutput(pgbStatus.Value, lblStatus.Text, False, SourceFilename, OutputFilename)
  412.         Else
  413.             lblStatus.Text = "Consolidation failed."
  414.             lblStatus.ForeColor = Color.Red
  415.             RaiseEvent ConversionCompleted(pgbStatus.Value, lblStatus.Text, False, OutputFilename) 'Notifiy SEDBE File Monitor
  416.            ConversionCompletedToStdOutput(pgbStatus.Value, lblStatus.Text, False, SourceFilename, OutputFilename)
  417.             Try
  418.                 ' Leave an indiator of failure for the next time to delete failed files
  419.                Dim FailedFileStreamWriter = System.IO.File.CreateText(FailedOutputFilename)
  420.                 FailedFileStreamWriter.Close()
  421.             Catch ex As Exception
  422.                 ' Ignore errors
  423.            End Try
  424.         End If
  425.  
  426.         'Unlock the GUI
  427.        btnOpenFile.Enabled = True
  428.         Me.Text = MyTitle
  429.         btnCancel.Enabled = False
  430.         isCanceled = False
  431.  
  432.         Return Result
  433.  
  434.     End Function
  435.  
  436.     Private Function ConvertToHisto(ByVal SourceFilename As String, ByVal DestinationFilename As String, ByVal Pathname As String, ByVal DestinationPath As String) As Boolean
  437.  
  438.         Dim SourceStreamReader As System.IO.StreamReader
  439.         Dim SourceLine As String
  440.         Dim SourceLine2 As String = ""
  441.         Dim DestinationLine As String
  442.         Dim DestinationStreamWriter As System.IO.StreamWriter
  443.         Dim DestinationChannelMeasurement As Long = 1
  444.         Dim NewProgressValue As Integer
  445.  
  446.         Dim EndMin As Integer
  447.  
  448.         '---------------------------------------------------------------------------------------
  449.        'Function input validation
  450.  
  451.         'Make sure the source file exists
  452.        If System.IO.File.Exists(SourceFilename) = False Then
  453.             Return False
  454.         End If
  455.  
  456.         'Make sure the destination file is not equal to the source file, because it will get deleted
  457.        If SourceFilename = DestinationFilename Then
  458.             LogError("Source file can't equal destination file.")
  459.             Return False
  460.         End If
  461.  
  462.         'Make sure the destination doesn't exist
  463.        If System.IO.File.Exists(DestinationFilename) Then
  464.             Try
  465.                 Kill(DestinationFilename)
  466.             Catch ex As Exception
  467.                 LogError(ex.Message)
  468.                 Return False
  469.             End Try
  470.         End If
  471.  
  472.         '---------------------------------------------------------------------------------------
  473.        'Open source and destination files
  474.  
  475.         'Open the source file (CRC SE Wideband Scanner *.txt)
  476.        Try
  477.             SourceStreamReader = System.IO.File.OpenText(SourceFilename)
  478.         Catch ex As Exception
  479.             LogError(ex.Message)
  480.             Return False
  481.         End Try
  482.  
  483.         'Create destination file (Consolidation *.asc)
  484.        Try
  485.             DestinationStreamWriter = System.IO.File.CreateText(DestinationFilename)
  486.             MySubHeader.MEASUREMENTFILE = SourceFilename
  487.         Catch ex As Exception
  488.             LogError(ex.Message)
  489.             SourceStreamReader.Close()
  490.             Return False
  491.         End Try
  492.  
  493.         Try
  494.             '---------------------------------------------------------------------------------------
  495.            'Transfer data from the source file to the destination file
  496.  
  497.             'Initialize data related to the Time Left estimation
  498.            Dim PastTime As Date = Now
  499.             Dim NowTime As Date = Now
  500.             Dim Duration As TimeSpan
  501.             Dim PastPosition As Long = 0
  502.             Dim NowPosition As Long = 0
  503.             Dim DataCovered As Long = 0
  504.             Dim CoverageRate As Double = 0
  505.             Dim TimeLeftSeconds As Double = 0
  506.             Dim TimeLeftsSeconds As New Queue(Of Double)
  507.             Dim TimeLeftSecondsSum As Double = 0
  508.             Dim TimeLeftSecondsAvg As Double = 0
  509.             Dim PastRefresh As Date = Now
  510.             Dim DurationRefresh As TimeSpan
  511.             Dim ChannelID As New Dictionary(Of String, String)
  512.  
  513.             Dim IsHeader As Boolean = True
  514.             Dim IsFirstScan As Boolean = True
  515.  
  516.             Dim ScanDate As System.DateTime
  517.             Dim PeriodSpan As TimeSpan
  518.             Dim MyPeriodStopDateTime As DateTime
  519.             Dim MyPeriodStartDateTime As DateTime
  520.             Dim Index As Integer
  521.             Dim IntValue As Integer
  522.             Dim NbLinesPreviousScan As Long = 0
  523.             Dim ActiveChannelCount As Integer
  524.             Dim NbRevisit As Integer = 0
  525.  
  526.             ' Set headers & ranges
  527.            Power_dBmRange.Offset = 120
  528.             Power_dBmRange.RangeStart = -120
  529.             Power_dBmRange.RangeStop = -20
  530.             SNR_dBRange.Offset = 0
  531.             SNR_dBRange.RangeStart = 0
  532.             SNR_dBRange.RangeStop = 80
  533.             Burst_dBmsRange.Offset = 30
  534.             Burst_dBmsRange.RangeStart = -30
  535.             Burst_dBmsRange.RangeStop = 70
  536.             ResetBox(MyBox)
  537.             ResetBox(MyGlobalBox)
  538.  
  539.             'Transfer data from the log file to mdb
  540.            SourceLine = SourceStreamReader.ReadLine()
  541.             While Not SourceStreamReader.EndOfStream
  542.  
  543.                 'Read a new line from the source file
  544.                '                SourceLine = SourceStreamReader.ReadLine()
  545.  
  546.                 'Update the progress bar
  547.                NowTime = Now
  548.                 NowPosition = SourceStreamReader.BaseStream.Position
  549.                 NewProgressValue = NowPosition / SourceStreamReader.BaseStream.Length * 99
  550.                 If pgbStatus.Value <> NewProgressValue Then
  551.                     pgbStatus.Value = NewProgressValue
  552.                     Me.Text = pgbStatus.Value & "% - " & DestinationFilename
  553.                     Me.Refresh()
  554.                 End If
  555.  
  556.                 'Read the description of the file to fill the headers
  557.                If IsHeader Then
  558.                     If SourceLine.Contains("Start Date ") Then
  559.                         'Set Date & Time
  560.                        Dim Moment As String
  561.  
  562.                         Dim Item() As String = Split(SourceLine, ",")
  563.                         Moment = Item(1).ToCharArray
  564.                         SourceLine = SourceStreamReader.ReadLine()
  565.                         Item = Split(SourceLine, ",")
  566.                         Moment = Moment + " " + Item(1)
  567.  
  568.                         ' Header
  569.                        MyHeader.VERSION = 2.0
  570.                         MyHeader.SENSOR_ROLE = "SCANNER"
  571.                         MyHeader.SENSOR_OUTPUT = "SPECTRUM_CONSOLIDATED"
  572.                         MyHeader.TASK_MISSION = "0-0"
  573.                         MyHeader.SENSOR_TECHNOLOGY = "CRC_SPECTRUM_EXPLORER"
  574.                         MyHeader.TimeZoneOffset = TimeSpan.FromHours(CDbl(txtTimezoneOffset.Text))
  575.                         ReDim MyHeader.FREQ_RANGE(0 To 1)
  576.                         MyHeader.FREQ_RANGE(0) = Double.MaxValue
  577.                         MyHeader.SENSOR_HOST_ID = txtSite.Text
  578.                         MyHeader.SENSOR_HW_ID = txtHW.Text
  579.  
  580.                         ' Sub-Header
  581.                        ' Validate My.Settings.BWRatio
  582.                        If My.Settings.BWRatio <= 0 Then
  583.                             ' It is possible that My.Settings.BWRatio = 0 if the user ran a previous version of the application,
  584.                            ' that didn't have that particular setting in the user.config file located in
  585.                            ' C:\Users\[user]\AppData\Local\Communications_Research_C\SEConsolidation[...]\1.0.0.0\user.config
  586.                            Dim newBWRatio = CInt(InputBox("Please provide a Bandwidth Ratio." & vbCrLf & "Current value: " & My.Settings.BWRatio & vbCrLf & "Suggested Value: 3", "Bandwidth Ratio Error", "3"))
  587.                             If newBWRatio <= 0 Then newBWRatio = 3
  588.                             My.Settings.BWRatio = newBWRatio
  589.                         End If
  590.                         BandwidthPercentRange.Offset = 1
  591.                         BandwidthPercentRange.RangeStart = 1
  592.                         BandwidthPercentRange.RangeStop = My.Settings.BWRatio * 100
  593.                         CORangePercentRange.Offset = My.Settings.BWRatio / 2 * 100
  594.                         CORangePercentRange.RangeStart = -My.Settings.BWRatio / 2 * 100
  595.                         CORangePercentRange.RangeStop = My.Settings.BWRatio / 2 * 100
  596.  
  597.                     End If 'StartDateTime
  598.  
  599.                     ' Sub Header
  600.                    If SourceLine.Contains("Resolution (Hz) ") Then
  601.                         Dim Item() As String = Split(SourceLine, ",",)
  602.                         MySubHeader.RESOLUTION_BW_Hz = Convert.ToDouble(Item(1), Globalization.CultureInfo.InvariantCulture)
  603.                     End If
  604.                     If SourceLine.Contains("Th. Type ...... ") Then
  605.                         Dim Item() As String = Split(SourceLine, ",")
  606.                         If Item(1).Contains("False") Then
  607.                             MySubHeader.THRESHOLD_TYPE = enmThresholdType.CPFA
  608.                         Else
  609.                             MySubHeader.THRESHOLD_TYPE = enmThresholdType.SNR
  610.                             SourceLine = SourceStreamReader.ReadLine()
  611.                             Item = Split(SourceLine, ",")
  612.                             MySubHeader.THRESHOLD = Convert.ToDouble(Item(1), Globalization.CultureInfo.InvariantCulture)
  613.                         End If
  614.                     End If
  615.  
  616.                     If SourceLine.Contains("Pro. False Alarm ") Then
  617.                         Dim Item() As String = Split(SourceLine, ",")
  618.                         MySubHeader.THRESHOLD = Convert.ToDouble(Item(1), Globalization.CultureInfo.InvariantCulture)
  619.                     End If
  620.  
  621.                     If SourceLine.Contains("FFT Window  ") Then
  622.                         Dim Item = Split(SourceLine, ",")
  623.                         If Item(1).Contains("Blackman") Then
  624.                             MySubHeader.FFT_WINDOW = enmWindow.Blackman
  625.                         ElseIf Item(1).Contains("Hann") Then
  626.                             MySubHeader.FFT_WINDOW = enmWindow.Hann
  627.                         ElseIf Item(1).Contains("Flat") Then
  628.                             MySubHeader.FFT_WINDOW = enmWindow.FlatTop
  629.                         Else
  630.                             MySubHeader.FFT_WINDOW = enmWindow.Rectangular
  631.                         End If
  632.                         MySubHeader.FRAME_NB = CInt(txtNbFrames.Text)
  633.                         MySubHeader.FRAME_AVG = enmFrame_Avg.PERIODIGRAM
  634.                         MySubHeader.BW_ESTIMATION_RATIO = CDbl(txtBWRatio.Text)
  635.                         MySubHeader.ANALYSIS_DURATION_MIN = MyPeriod
  636.                         MySubHeader.ISDF = False
  637.                     End If
  638.  
  639.                     'Read the description of the Channels
  640.                    If SourceLine.Contains("Total Frequencies: ") Then
  641.  
  642.                         'Read number of frequencies covered
  643.                        Dim Item() As String = Split(SourceLine, ",")
  644.                         TOTAL_FREQUENCIES = Item(1)
  645.                         ReDim MyChannels.BW(0 To TOTAL_FREQUENCIES - 1)
  646.                         ReDim MyChannels.Carrier(0 To TOTAL_FREQUENCIES - 1)
  647.                         ReDim MyChannels.Count(0 To TOTAL_FREQUENCIES - 1)
  648.                         ReDim MyChannels.ID(0 To TOTAL_FREQUENCIES - 1)
  649.                         ReDim MyChannels.BurstStateCurrent(0 To TOTAL_FREQUENCIES - 1)
  650.                         ReDim MyChannels.BurstStatePrevious(0 To TOTAL_FREQUENCIES - 1)
  651.                         ReDim MyChannels.BurstTime(0 To TOTAL_FREQUENCIES - 1)
  652.                         ReDim MyChannels.IndexCurrentlyOn(0 To TOTAL_FREQUENCIES - 1)
  653.                         ReDim MyChannels.IndexPreviouslyOn(0 To TOTAL_FREQUENCIES - 1)
  654.  
  655.                         'v. 2.2 - "Channel Number","Frequency Center (MHz)","Bandwidth (Hz)","Number of FFT Points","Channel ID"
  656.                        If TOTAL_FREQUENCIES > 0 Then
  657.                             'Skip 2 lines of header
  658.                            If Not SourceStreamReader.EndOfStream Then SourceStreamReader.ReadLine()
  659.                             If Not SourceStreamReader.EndOfStream Then SourceStreamReader.ReadLine()
  660.                             'Read subsequent channel values & Write to file
  661.                            DestinationLine = "DATA_LABELS: ChannelNb,Frequency(MHz),Bandwidth(Hz),NbFFTBins,ChannelID"
  662.                             DestinationStreamWriter.WriteLine(DestinationLine)
  663.  
  664.                             SourceLine = SourceStreamReader.ReadLine()
  665.                             Do Until SourceLine.Contains("Total Frequency Bands: ") ' Initiase the channels
  666.                                DestinationStreamWriter.WriteLine(SourceLine)
  667.                                 Item = Split(SourceLine, ",")
  668.                                 Index = CInt(Item(0)) - 1
  669.                                 MyChannels.ID(Index) = Item(4)
  670.                                 MyChannels.BW(Index) = Convert.ToDouble(Item(2), Globalization.CultureInfo.InvariantCulture)
  671.                                 MyChannels.Carrier(Index) = Convert.ToDouble(Item(1), Globalization.CultureInfo.InvariantCulture)
  672.                                 SourceLine = SourceStreamReader.ReadLine()
  673.                             Loop
  674.                             SourceLine = "---"
  675.                             DestinationStreamWriter.WriteLine(SourceLine)
  676.                         End If
  677.  
  678.                         ' Set Histogrammes
  679.                        ReDim MyHisto(0 To TOTAL_FREQUENCIES - 1)
  680.  
  681.                         For k = 0 To TOTAL_FREQUENCIES - 1
  682.                             With MyHisto(k)
  683.                                 ReDim .Power_dBmHisto(0 To Power_dBmRange.RangeStop - Power_dBmRange.RangeStart)
  684.                                 ReDim .SNR_dBHisto(0 To SNR_dBRange.RangeStop - SNR_dBRange.RangeStart)
  685.                                 ReDim .BandwidthPercentRangeHisto(0 To BandwidthPercentRange.RangeStop - BandwidthPercentRange.RangeStart)
  686.                                 ReDim .CORangePercentHisto(0 To CORangePercentRange.RangeStop - CORangePercentRange.RangeStart)
  687.                                 ReDim .BurstOn_dBmsHisto(0 To Burst_dBmsRange.RangeStop - Burst_dBmsRange.RangeStart)
  688.                                 ReDim .BurstOff_dBmsHisto(0 To Burst_dBmsRange.RangeStop - Burst_dBmsRange.RangeStart)
  689.                             End With
  690.                         Next
  691.                         IsHeader = False
  692.                     End If 'Channel List
  693.  
  694.                     'Read a new line from the source file
  695.                    SourceLine = SourceStreamReader.ReadLine()
  696.  
  697.                 ElseIf SourceLine.Contains("Scan:") Then
  698.                     'Read scans
  699.                    '"Elapsed Time (ms)","Number of GPS Data Lines","Number of Channels","Number of Signal Detections","Number of Messages in Alarm","Number of noise level measurements","Number of Occupancy bins"
  700.                    'Read number of data lines
  701.                    Dim Item() As String = Split(SourceLine, ",")
  702.                     Dim TimeMilliseconds As Long = Item(1)
  703.                     Dim LinesChannels As Long = Item(3)
  704.                     Dim LinesDetections As Long = Item(4)
  705.                     Dim LinesAlarm As Long = Item(5)
  706.                     Dim NbLinesCurrentScan As Long = LinesChannels
  707.                     Dim BurstSpan As TimeSpan
  708.  
  709.                     'Read GPS
  710.                    'v.2.1  "GPS scan date and time","Latitude","Longitude","Elevation"
  711.                    'v.2.3  "GPS scan date and time","Latitude","Longitude","Elevation","GridID","Status (0=No GPS,1=Fixed Position,2=GPS Locked,3=GPS Unlocked,4=GPS Error)"
  712.                    'v.2.33 "GPS scan date and time","Latitude","Longitude","Elevation","GridID","Status (0=No GPS,1=Fixed Position,2=GPS Locked,3=GPS Unlocked,4=GPS Error)",
  713.                    '       "Movement Status (0=Not Ready, 1 = Ready)","Ground Speed (m/sec)","Ground Acceleration (m/sec2)","Track Made Good (Degre relative to true north)",
  714.                    '       "True Heading (Degre relative to true north)"
  715.                    '                    Dim MovementStatus As Integer, GroundSpeed As Double, GroundAcceleration As Double, TrackMadeGood As Double, TrueHeading As Double
  716.  
  717.                     If SourceLine2.Length = 0 Then
  718.                         SourceLine = SourceStreamReader.ReadLine()
  719.                     Else
  720.                         SourceLine = SourceLine2
  721.                     End If
  722.  
  723.                     Item = Split(SourceLine, ",")
  724.                     ScanDate = GetDate(Item(0))
  725.                     Index = Item(0).IndexOf(".") + 1
  726.                     ScanDate = ScanDate.AddMilliseconds(Item(0).Substring(Index, 3))
  727.  
  728.                     EndMin = Math.Ceiling(ScanDate.Minute / MyPeriod + ScanDate.Second / 60.0 / MyPeriod + (ScanDate.Millisecond + 1) / 1000.0 / 60.0 / MyPeriod) * MyPeriod ' Add 1 ms to avoid case where hour is bang on
  729.                    MyPeriodStartDateTime = DateTime.SpecifyKind(ScanDate, DateTimeKind.Utc)
  730.                     MyPeriodStopDateTime = New DateTime(ScanDate.Year, ScanDate.Month, ScanDate.Day, ScanDate.Hour, 0, 0, DateTimeKind.Utc)
  731.                     MyPeriodStopDateTime = MyPeriodStopDateTime.AddMinutes(EndMin)
  732.                     PeriodSpan = MyPeriodStopDateTime - ScanDate
  733.  
  734.                     If IsFirstScan Then
  735.                         ' Set all channel burst times
  736.                        For k = 0 To TOTAL_FREQUENCIES - 1
  737.                             MyChannels.BurstTime(k) = ScanDate
  738.                         Next
  739.                     End If
  740.  
  741.                     'Get Channel Measurements for the period
  742.                    While PeriodSpan.TotalSeconds > 0 And Not SourceStreamReader.EndOfStream ' Does the period
  743.                        NbRevisit += 1
  744.  
  745.                         ' Location
  746.                        MyBox.LatMin = Math.Min(MyBox.LatMin, Convert.ToDouble(Item(1), Globalization.CultureInfo.InvariantCulture))
  747.                         MyBox.LatMax = Math.Max(MyBox.LatMax, Convert.ToDouble(Item(1), Globalization.CultureInfo.InvariantCulture))
  748.                         MyBox.LonMin = Math.Min(MyBox.LonMin, Convert.ToDouble(Item(2), Globalization.CultureInfo.InvariantCulture))
  749.                         MyBox.LonMax = Math.Max(MyBox.LonMax, Convert.ToDouble(Item(2), Globalization.CultureInfo.InvariantCulture))
  750.                         MyBox.AltMin = Math.Min(MyBox.AltMin, Convert.ToDouble(Item(3), Globalization.CultureInfo.InvariantCulture))
  751.                         MyBox.AltMax = Math.Max(MyBox.AltMax, Convert.ToDouble(Item(3), Globalization.CultureInfo.InvariantCulture))
  752.  
  753.                         Dim MovementStatus As Integer, GroundSpeed As Double, GroundAcceleration As Double, TrackMadeGood As Double, TrueHeading As Double
  754.                         If Item.Length > 6 Then
  755.                             MovementStatus = Item(6)
  756.                             GroundSpeed = Item(7)
  757.                             GroundAcceleration = Item(8)
  758.                             TrackMadeGood = Item(9)
  759.                             TrueHeading = Item(10)
  760.                         Else
  761.                             MovementStatus = 0      'Default value, "Not Ready"
  762.                            GroundSpeed = 0         'Default value, "No Movement"
  763.                            GroundAcceleration = 0  'Default value, "No Movement"
  764.                            TrackMadeGood = -1      'Default value, Negative value is considered invalid. Valid values cover [0 to 360[
  765.                            TrueHeading = -1        'Default value, Negative value is considered invalid. Valid values cover [0 to 360[
  766.                        End If
  767.  
  768.  
  769.                         'Read Channel Measures for scan
  770.                        '"Channel Number","Power (dBm)","C/N (dB)","Frequency Center Deviation (Hz)","Bandwidth (Hz)","Direction (deg)","Direction Quality (deg)","Status","RF Switch Port Number"
  771.                        Do Until SourceStreamReader.EndOfStream Or LinesChannels <= 0 'Does one scan
  772.                            LinesChannels -= 1
  773.                             SourceLine = SourceStreamReader.ReadLine()
  774.                             Item = Split(SourceLine, ",")
  775.                             Index = CInt(Item(0)) - 1
  776.                             MyChannels.Count(Index) += 1
  777.                             If MyChannels.Carrier(Index) < MyHeader.FREQ_RANGE(0) Then
  778.                                 MyHeader.FREQ_RANGE(0) = MyChannels.Carrier(Index)
  779.                             End If
  780.                             If MyChannels.Carrier(Index) > MyHeader.FREQ_RANGE(1) Then
  781.                                 MyHeader.FREQ_RANGE(1) = MyChannels.Carrier(Index)
  782.                             End If
  783.  
  784.                             With MyHisto(Index)
  785.                                 ' Power
  786.                                IntValue = Math.Round(Convert.ToDouble(Item(1), Globalization.CultureInfo.InvariantCulture)) + Power_dBmRange.Offset
  787.                                 IntValue = Math.Max(IntValue, 0)
  788.                                 IntValue = Math.Min(IntValue, .Power_dBmHisto.Length - 1)
  789.                                 .Power_dBmHisto(IntValue) += 1
  790.  
  791.                                 ' SNR
  792.                                IntValue = Math.Round(Convert.ToDouble(Item(2), Globalization.CultureInfo.InvariantCulture)) + SNR_dBRange.Offset
  793.                                 IntValue = Math.Max(IntValue, 0)
  794.                                 IntValue = Math.Min(IntValue, .SNR_dBHisto.Length - 1)
  795.                                 .SNR_dBHisto(IntValue) += 1
  796.  
  797.                                 'Frequency Offset
  798.                                IntValue = CInt(Math.Round(CDbl(Item(3)) / MyChannels.BW(Index) * 100.0)) + CORangePercentRange.Offset
  799.                                 IntValue = Math.Max(IntValue, 0)
  800.                                 IntValue = Math.Min(IntValue, .CORangePercentHisto.Length - 1)
  801.                                 .CORangePercentHisto(IntValue) += 1
  802.  
  803.                                 ' BW
  804.                                IntValue = CInt(Math.Round(CDbl(Item(4)) / MyChannels.BW(Index) * 100.0)) + BandwidthPercentRange.Offset
  805.                                 IntValue = Math.Max(IntValue, 0)
  806.                                 IntValue = Math.Min(IntValue, .BandwidthPercentRangeHisto.Length - 1)
  807.                                 .BandwidthPercentRangeHisto(IntValue) += 1
  808.  
  809.                                 If IsFirstScan Then
  810.                                     ' Set burst state as state of burst
  811.                                    MyChannels.BurstStatePrevious(Index) = True
  812.                                     MyChannels.BurstStateCurrent(Index) = True
  813.                                 End If
  814.  
  815.                                 ' Burst Off
  816.                                If MyChannels.BurstStatePrevious(Index) = False Then
  817.                                     ' Channel when from off to on
  818.                                    ' Burst Off value
  819.                                    BurstSpan = ScanDate - MyChannels.BurstTime(Index)
  820.                                     If BurstSpan.TotalMilliseconds <= 0 Then
  821.                                         ' Bug in scanner where first two scan have the same time stamp
  822.                                        ScanDate = ScanDate.AddMilliseconds(My.Settings.AddMilliSecond)
  823.                                         BurstSpan = ScanDate - MyChannels.BurstTime(Index)
  824.                                         If BurstSpan.TotalSeconds < 0 Then
  825.                                             ' Still negative in time: set to AddMilliSecond
  826.                                            BurstSpan = New TimeSpan(0, 0, 0, 0, My.Settings.AddMilliSecond)
  827.                                         End If
  828.                                     End If
  829.                                     IntValue = Math.Round(10 * Math.Log10(BurstSpan.TotalSeconds / 0.001)) + Burst_dBmsRange.Offset
  830.                                     IntValue = Math.Max(IntValue, 0)
  831.                                     IntValue = Math.Min(IntValue, .BurstOff_dBmsHisto.Length - 1)
  832.                                     .BurstOff_dBmsHisto(IntValue) += 1
  833.                                     MyChannels.BurstTime(Index) = ScanDate
  834.                                 End If
  835.                                 MyChannels.BurstStateCurrent(Index) = True
  836.                                 MyChannels.IndexCurrentlyOn(LinesChannels) = Index
  837.  
  838.                             End With
  839.  
  840.                             DestinationChannelMeasurement += 1
  841.                         Loop 'End Scan
  842.  
  843.                         If IsFirstScan Then
  844.                             MyHeader.StartDateTime = DateTime.SpecifyKind(ScanDate, DateTimeKind.Utc)
  845.                             IsFirstScan = False
  846.                         End If
  847.  
  848.                         ' Check for ended burst and set Burst On histogram
  849.                        For k = 0 To NbLinesPreviousScan - 1
  850.                             Index = MyChannels.IndexPreviouslyOn(k)
  851.                             If MyChannels.BurstStatePrevious(Index) = True And MyChannels.BurstStateCurrent(Index) = False Then
  852.                                 ' Burst from on to off
  853.                                BurstSpan = ScanDate - MyChannels.BurstTime(Index)
  854.                                 IntValue = Math.Round(10 * Math.Log10(BurstSpan.TotalSeconds / 0.001)) + Burst_dBmsRange.Offset
  855.                                 IntValue = Math.Max(IntValue, 0)
  856.                                 IntValue = Math.Min(IntValue, MyHisto(Index).BurstOn_dBmsHisto.Length - 1)
  857.                                 MyHisto(Index).BurstOn_dBmsHisto(IntValue) += 1
  858.                                 MyChannels.BurstTime(Index) = ScanDate
  859.                             End If
  860.                         Next
  861.  
  862.                         ' Reset current states
  863.                        Array.Clear(MyChannels.BurstStatePrevious, 0, TOTAL_FREQUENCIES)
  864.                         For k = 0 To NbLinesCurrentScan - 1
  865.                             Index = MyChannels.IndexCurrentlyOn(k)
  866.                             MyChannels.BurstStatePrevious(Index) = MyChannels.BurstStateCurrent(Index)
  867.                             MyChannels.BurstStateCurrent(Index) = False
  868.                             MyChannels.IndexPreviouslyOn(k) = MyChannels.IndexCurrentlyOn(k)
  869.                         Next
  870.                         NbLinesPreviousScan = NbLinesCurrentScan
  871.  
  872.                         ' Read for next scan
  873.                        SourceLine = SourceStreamReader.ReadLine()
  874.                         If SourceStreamReader.EndOfStream Then
  875.                             ' End of file
  876.                            Exit While
  877.                         Else
  878.                             Item = Split(SourceLine, ",")
  879.                             LinesChannels = Item(3)
  880.                             LinesDetections = Item(4)
  881.                             LinesAlarm = Item(5)
  882.                             NbLinesCurrentScan = LinesChannels
  883.  
  884.                             SourceLine2 = SourceStreamReader.ReadLine()
  885.                             Item = Split(SourceLine2, ",")
  886.                             ScanDate = GetDate(Item(0))
  887.                             Index = Item(0).IndexOf(".") + 1
  888.                             ScanDate = ScanDate.AddMilliseconds(CDbl(Item(0).Substring(Index, 3)))
  889.                             PeriodSpan = MyPeriodStopDateTime - ScanDate
  890.  
  891.                             AverageRevisitCount += 1
  892.                         End If
  893.  
  894.                     End While 'End Period
  895.  
  896.                     '
  897.                    ' TO DO: Deal with the Burst_on and Burst_off at the end of the analysis period
  898.                    '
  899.  
  900.                     'Save data period to consolidated file
  901.                    If ckbCorrectForUTC.Checked = True Then
  902.                         ' UTC correction
  903.                        Dim TmpDate As DateTime
  904.                         TmpDate = MyPeriodStartDateTime.Subtract(MyHeader.TimeZoneOffset)
  905.                         DestinationLine = "StartDateTime: " + TmpDate.ToString("o")
  906.                         DestinationStreamWriter.WriteLine(DestinationLine)
  907.  
  908.                         If PeriodSpan.TotalSeconds > 0 Then
  909.                             TmpDate = ScanDate.Subtract(MyHeader.TimeZoneOffset)
  910.                             DestinationLine = "StopDateTime: " + DateTime.SpecifyKind(TmpDate, DateTimeKind.Utc).ToString("o")
  911.                         Else
  912.                             TmpDate = MyPeriodStopDateTime.Subtract(MyHeader.TimeZoneOffset)
  913.                             DestinationLine = "StopDateTime: " + TmpDate.ToString("o")
  914.                         End If
  915.                     Else
  916.                         ' N0 UTC corrections
  917.                        DestinationLine = "StartDateTime: " + MyPeriodStartDateTime.ToString("o")
  918.                         DestinationStreamWriter.WriteLine(DestinationLine)
  919.                         If PeriodSpan.TotalSeconds > 0 Then
  920.                             DestinationLine = "StopDateTime: " + DateTime.SpecifyKind(ScanDate, DateTimeKind.Utc).ToString("o")
  921.                         Else
  922.                             DestinationLine = "StopDateTime: " + MyPeriodStopDateTime.ToString("o")
  923.                         End If
  924.                     End If
  925.                     DestinationStreamWriter.WriteLine(DestinationLine)
  926.  
  927.                     If (MyBox.LatMax = MyBox.LatMin) And
  928.                            (MyBox.LonMax = MyBox.LonMin) And IsPointAllowed Then
  929.                         ' POINT
  930.                        DestinationLine = "LOCATION: POINT " + MyBox.LatMax.ToString(Globalization.CultureInfo.InvariantCulture) +
  931.                             " " + MyBox.LonMax.ToString(Globalization.CultureInfo.InvariantCulture) +
  932.                             " " + MyBox.AltMax.ToString(Globalization.CultureInfo.InvariantCulture)
  933.                     Else
  934.                         ' BOX
  935.                        DestinationLine = "LOCATION: BOX " + MyBox.LatMin.ToString(Globalization.CultureInfo.InvariantCulture) +
  936.                             " " + MyBox.LatMin.ToString(Globalization.CultureInfo.InvariantCulture) +
  937.                             " " + MyBox.LatMax.ToString(Globalization.CultureInfo.InvariantCulture) +
  938.                             " " + MyBox.LatMax.ToString(Globalization.CultureInfo.InvariantCulture) +
  939.                             " " + MyBox.LonMin.ToString(Globalization.CultureInfo.InvariantCulture) +
  940.                             " " + MyBox.LonMax.ToString(Globalization.CultureInfo.InvariantCulture) +
  941.                             " " + MyBox.LonMax.ToString(Globalization.CultureInfo.InvariantCulture) +
  942.                             " " + MyBox.LonMin.ToString(Globalization.CultureInfo.InvariantCulture) +
  943.                             " " + MyBox.AltMin.ToString(Globalization.CultureInfo.InvariantCulture) +
  944.                             " " + MyBox.AltMax.ToString(Globalization.CultureInfo.InvariantCulture)
  945.                     End If
  946.                     DestinationStreamWriter.WriteLine(DestinationLine)
  947.  
  948.                     ' Other parameters
  949.                    DestinationLine = "# of revisit: " + NbRevisit.ToString
  950.                     DestinationStreamWriter.WriteLine(DestinationLine)
  951.                     NbRevisit = 0
  952.  
  953.                     ActiveChannelCount = 0
  954.                     For k = 0 To TOTAL_FREQUENCIES - 1
  955.                         If MyChannels.Count(k) Then
  956.                             ActiveChannelCount += 1
  957.                         End If
  958.                     Next
  959.                     DestinationLine = "Active Channels count: " + ActiveChannelCount.ToString
  960.                     DestinationStreamWriter.WriteLine(DestinationLine)
  961.  
  962.                     ' Position information
  963.                    ' Compare with global box
  964.                    MyGlobalBox.LatMin = Math.Min(MyBox.LatMin, MyGlobalBox.LatMin)
  965.                     MyGlobalBox.LatMax = Math.Max(MyBox.LatMax, MyGlobalBox.LatMax)
  966.                     MyGlobalBox.LonMin = Math.Min(MyBox.LonMin, MyGlobalBox.LonMin)
  967.                     MyGlobalBox.LonMax = Math.Max(MyBox.LonMax, MyGlobalBox.LonMax)
  968.                     MyGlobalBox.AltMin = Math.Min(MyBox.AltMin, MyGlobalBox.AltMin)
  969.                     MyGlobalBox.AltMax = Math.Max(MyBox.AltMax, MyGlobalBox.AltMax)
  970.                     ResetBox(MyBox)
  971.  
  972.                     ' Write Histograms
  973.                    WriteHisto(DestinationStreamWriter)
  974.                     ' Reset Arrays
  975.                    ResetArrays()
  976.  
  977.                     'Update the GUI with the estimated Time Left
  978.                    Duration = NowTime.Subtract(PastTime)
  979.                     If NowPosition > PastPosition Then
  980.                         DataCovered = NowPosition - PastPosition
  981.                         CoverageRate = Duration.TotalSeconds / DataCovered
  982.                         TimeLeftSeconds = (SourceStreamReader.BaseStream.Length - NowPosition) * CoverageRate
  983.                         TimeLeftsSeconds.Enqueue(TimeLeftSeconds)
  984.                         If TimeLeftsSeconds.Count > 5 Then TimeLeftsSeconds.Dequeue()
  985.                         TimeLeftSecondsSum = 0
  986.                         For Each I As Double In TimeLeftsSeconds
  987.                             TimeLeftSecondsSum += I
  988.                         Next
  989.                         TimeLeftSecondsAvg = TimeLeftSecondsSum / TimeLeftsSeconds.Count
  990.                         'Update the GUI if at least 1 second has passed since last update
  991.                        DurationRefresh = NowTime.Subtract(PastRefresh)
  992.                         If DurationRefresh.TotalSeconds > 1 Then
  993.                             PastRefresh = NowTime
  994.                             Dim DurationTimeSpan As New TimeSpan(TimeLeftSecondsAvg * TimeSpan.TicksPerSecond)
  995.                             Dim TimeText As String = Mid(DurationTimeSpan.ToString, 1, DurationTimeSpan.ToString.IndexOf("."c)) '& Format(TimeLeftSecondsAvg, "0.00") & " seconds"
  996.                            lblStatus.Text = "Consolidation in progress... Time remaining: " & TimeText & "."
  997.                             Me.Refresh()
  998.                             RaiseEvent ConversionCompleted(pgbStatus.Value, TimeText, True, DestinationFilename)
  999.                             ConversionCompletedToStdOutput(pgbStatus.Value, TimeText, True, SourceFilename, DestinationFilename)
  1000.                         End If
  1001.                         'Get variables ready for next algorithm pass
  1002.                        PastPosition = NowPosition
  1003.                         PastTime = NowTime
  1004.                     End If
  1005.                 Else
  1006.                     'Read a new line from the source file
  1007.                    SourceLine = SourceStreamReader.ReadLine()
  1008.                 End If 'End Period
  1009.  
  1010.                 If SourceStreamReader.EndOfStream Then
  1011.                     ' Write Start/StopDateTime, revisit time
  1012.                    PeriodSpan = ScanDate - MyHeader.StartDateTime
  1013.                     MyHeader.StopDateTime = DateTime.SpecifyKind(ScanDate, DateTimeKind.Utc)
  1014.                     MySubHeader.REVISIT_TIME_s = PeriodSpan.TotalSeconds / AverageRevisitCount
  1015.                     Exit While
  1016.                 End If
  1017.  
  1018.                 ' Listen to user inputs
  1019.                System.Windows.Forms.Application.DoEvents()
  1020.  
  1021.                 ' The application is closing. Close any opened file
  1022.                If isClosing Then
  1023.                     DestinationStreamWriter.Close()
  1024.                     SourceStreamReader.Close()
  1025.                     Return False
  1026.                 End If
  1027.  
  1028.                 ' Report the error and close any opened file
  1029.                If isCanceled Then
  1030.                     lblStatus.Text = "Consolidation was canceled by the user."
  1031.                     DestinationStreamWriter.Close()
  1032.                     SourceStreamReader.Close()
  1033.                     Return False
  1034.                 End If
  1035.  
  1036.             End While
  1037.  
  1038.         Catch ex As Exception
  1039.  
  1040.             ' Report the error and close any opened file
  1041.            LogError(ex.Message)
  1042.             DestinationStreamWriter.Close()
  1043.             SourceStreamReader.Close()
  1044.             Return False
  1045.  
  1046.         End Try
  1047.  
  1048.         ' Success. Close any opened file. Combine the header with the data. Report success
  1049.        DestinationStreamWriter.Close()
  1050.         SourceStreamReader.Close()
  1051.         Dim Analysis As Boolean = True
  1052.         CompleteDestination(MyHeader, DestinationFilename, Pathname, Analysis)
  1053.         pgbStatus.Value = 100
  1054.  
  1055.         'Zip the file
  1056.        Dim tempFolder As String = Pathname + "\temp"
  1057.         My.Computer.FileSystem.CreateDirectory(tempFolder)
  1058.         'To zip the output into a new directory, just change "zipPath" below to the desired directory
  1059.        Dim zipPath As String = DestinationPath + "\" + MyHeader.SENSOR_HOST_ID + "-" + MyHeader.SENSOR_OUTPUT + "-" + MyHeader.TASK_MISSION + "-" +
  1060.                 Replace(MyHeader.StartDateTime.ToString("o"), ":", "-") + ".zip"
  1061.         Dim targetFile As String = tempFolder + "\" + MyHeader.SENSOR_HOST_ID + "-" + MyHeader.SENSOR_OUTPUT + "-" + MyHeader.TASK_MISSION + "-" +
  1062.                 Replace(MyHeader.StartDateTime.ToString("o"), ":", "-") + ".txt"
  1063.         My.Computer.FileSystem.MoveFile(DestinationFilename, targetFile)
  1064.  
  1065.  
  1066.         Console.Write("Zipping to    ")
  1067.         Console.WriteLine(zipPath)
  1068.         ZipFile.CreateFromDirectory(tempFolder, zipPath)
  1069.         My.Computer.FileSystem.DeleteDirectory(tempFolder, FileIO.DeleteDirectoryOption.DeleteAllContents)
  1070.  
  1071.         Return True
  1072.  
  1073.     End Function
  1074.  
  1075.     Private Function ConvertToMeasurement(ByVal SourceFilename As String, ByVal DestinationFilename As String, ByVal Pathname As String, ByVal DestinationPath As String) As Boolean
  1076.  
  1077.         Dim SourceStreamReader As System.IO.StreamReader
  1078.         Dim SourceLine As String
  1079.         Dim SourceLine2 As String = ""
  1080.         Dim DestinationLine As String
  1081.         Dim DestinationStreamWriter As System.IO.StreamWriter
  1082.         Dim DestinationChannelMeasurement As Long = 1
  1083.         Dim NewProgressValue As Integer
  1084.  
  1085.         Dim EndMin As Integer
  1086.  
  1087.         '---------------------------------------------------------------------------------------
  1088.        'Function input validation
  1089.  
  1090.         'Make sure the source file exists
  1091.        If System.IO.File.Exists(SourceFilename) = False Then
  1092.             Return False
  1093.         End If
  1094.  
  1095.         'Make sure the destination file is not equal to the source file, because it will get deleted
  1096.        If SourceFilename = DestinationFilename Then
  1097.             LogError("Source file can't equal destination file.")
  1098.             Return False
  1099.         End If
  1100.  
  1101.         'Make sure the destination doesn't exist
  1102.        If System.IO.File.Exists(DestinationFilename) Then
  1103.             Try
  1104.                 Kill(DestinationFilename)
  1105.             Catch ex As Exception
  1106.                 LogError(ex.Message)
  1107.                 Return False
  1108.             End Try
  1109.         End If
  1110.  
  1111.         '---------------------------------------------------------------------------------------
  1112.        'Open source and destination files
  1113.  
  1114.         'Open the source file (CRC SE Wideband Scanner *.txt)
  1115.        Try
  1116.             SourceStreamReader = System.IO.File.OpenText(SourceFilename)
  1117.         Catch ex As Exception
  1118.             LogError(ex.Message)
  1119.             Return False
  1120.         End Try
  1121.  
  1122.         'Create destination file (Consolidation *.asc)
  1123.        Try
  1124.             DestinationStreamWriter = System.IO.File.CreateText(DestinationFilename)
  1125.             MySubHeader.MEASUREMENTFILE = SourceFilename
  1126.         Catch ex As Exception
  1127.             LogError(ex.Message)
  1128.             SourceStreamReader.Close()
  1129.             Return False
  1130.         End Try
  1131.  
  1132.         Try
  1133.             '---------------------------------------------------------------------------------------
  1134.            'Transfer data from the source file to the destination file
  1135.  
  1136.             'Initialize data related to the Time Left estimation
  1137.            Dim PastTime As Date = Now
  1138.             Dim NowTime As Date = Now
  1139.             Dim Duration As TimeSpan
  1140.             Dim PastPosition As Long = 0
  1141.             Dim NowPosition As Long = 0
  1142.             Dim DataCovered As Long = 0
  1143.             Dim CoverageRate As Double = 0
  1144.             Dim TimeLeftSeconds As Double = 0
  1145.             Dim TimeLeftsSeconds As New Queue(Of Double)
  1146.             Dim TimeLeftSecondsSum As Double = 0
  1147.             Dim TimeLeftSecondsAvg As Double = 0
  1148.             Dim PastRefresh As Date = Now
  1149.             Dim DurationRefresh As TimeSpan
  1150.             Dim ChannelID As New Dictionary(Of String, String)
  1151.  
  1152.             Dim IsHeader As Boolean = True
  1153.             Dim IsFirstScan As Boolean = True
  1154.  
  1155.             Dim ScanDate As System.DateTime
  1156.             Dim PeriodSpan As TimeSpan
  1157.             Dim MyPeriodStopDateTime As DateTime
  1158.             Dim MyPeriodStartDateTime As DateTime
  1159.             Dim Index As Integer
  1160.             Dim NbLinesPreviousScan As Long = 0
  1161.             Dim ActiveChannelCount As Integer
  1162.             Dim NbRevisit As Integer = 0
  1163.  
  1164.             Dim output As MeasurementData
  1165.  
  1166.             ' Set headers & ranges
  1167.            Power_dBmRange.Offset = 120
  1168.             Power_dBmRange.RangeStart = -120
  1169.             Power_dBmRange.RangeStop = -20
  1170.             SNR_dBRange.Offset = 0
  1171.             SNR_dBRange.RangeStart = 0
  1172.             SNR_dBRange.RangeStop = 80
  1173.             Burst_dBmsRange.Offset = 30
  1174.             Burst_dBmsRange.RangeStart = -30
  1175.             Burst_dBmsRange.RangeStop = 70
  1176.             ResetBox(MyBox)
  1177.             ResetBox(MyGlobalBox)
  1178.  
  1179.             'Transfer data from the log file to mdb
  1180.            SourceLine = SourceStreamReader.ReadLine()
  1181.             While Not SourceStreamReader.EndOfStream
  1182.  
  1183.                 'Read a new line from the source file
  1184.                '                SourceLine = SourceStreamReader.ReadLine()
  1185.  
  1186.                 'Update the progress bar
  1187.                NowTime = Now
  1188.                 NowPosition = SourceStreamReader.BaseStream.Position
  1189.                 NewProgressValue = NowPosition / SourceStreamReader.BaseStream.Length * 99
  1190.                 If pgbStatus.Value <> NewProgressValue Then
  1191.                     pgbStatus.Value = NewProgressValue
  1192.                     Me.Text = pgbStatus.Value & "% - " & DestinationFilename
  1193.                     Me.Refresh()
  1194.                 End If
  1195.  
  1196.                 'Read the description of the file to fill the headers
  1197.                If IsHeader Then
  1198.                     If SourceLine.Contains("Start Date ") Then
  1199.                         'Set Date & Time
  1200.                        Dim Moment As String
  1201.  
  1202.                         Dim Item() As String = Split(SourceLine, ",")
  1203.                         Moment = Item(1).ToCharArray
  1204.                         SourceLine = SourceStreamReader.ReadLine()
  1205.                         Item = Split(SourceLine, ",")
  1206.                         Moment = Moment + " " + Item(1)
  1207.  
  1208.                         ' Header
  1209.                        MyHeader.VERSION = 2.0
  1210.                         MyHeader.SENSOR_ROLE = "SCANNER"
  1211.                         MyHeader.SENSOR_OUTPUT = "SPECTRUM_MEASUREMENT"
  1212.                         MyHeader.TASK_MISSION = "0-0"
  1213.                         MyHeader.SENSOR_TECHNOLOGY = "CRC_SPECTRUM_EXPLORER"
  1214.                         MyHeader.TimeZoneOffset = TimeSpan.FromHours(CDbl(txtTimezoneOffset.Text))
  1215.                         ReDim MyHeader.FREQ_RANGE(0 To 1)
  1216.                         MyHeader.FREQ_RANGE(0) = Double.MaxValue
  1217.                         MyHeader.SENSOR_HOST_ID = txtSite.Text
  1218.                         MyHeader.SENSOR_HW_ID = txtHW.Text
  1219.  
  1220.                         ' Sub-Header
  1221.                        ' Validate My.Settings.BWRatio
  1222.                        If My.Settings.BWRatio <= 0 Then
  1223.                             ' It is possible that My.Settings.BWRatio = 0 if the user ran a previous version of the application,
  1224.                            ' that didn't have that particular setting in the user.config file located in
  1225.                            ' C:\Users\[user]\AppData\Local\Communications_Research_C\SEConsolidation[...]\1.0.0.0\user.config
  1226.                            Dim newBWRatio = CInt(InputBox("Please provide a Bandwidth Ratio." & vbCrLf & "Current value: " & My.Settings.BWRatio & vbCrLf & "Suggested Value: 3", "Bandwidth Ratio Error", "3"))
  1227.                             If newBWRatio <= 0 Then newBWRatio = 3
  1228.                             My.Settings.BWRatio = newBWRatio
  1229.                         End If
  1230.                         BandwidthPercentRange.Offset = 1
  1231.                         BandwidthPercentRange.RangeStart = 1
  1232.                         BandwidthPercentRange.RangeStop = My.Settings.BWRatio * 100
  1233.                         CORangePercentRange.Offset = My.Settings.BWRatio / 2 * 100
  1234.                         CORangePercentRange.RangeStart = -My.Settings.BWRatio / 2 * 100
  1235.                         CORangePercentRange.RangeStop = My.Settings.BWRatio / 2 * 100
  1236.  
  1237.                     End If 'StartDateTime
  1238.  
  1239.                     ' Sub Header
  1240.                    If SourceLine.Contains("Resolution (Hz) ") Then
  1241.                         Dim Item() As String = Split(SourceLine, ",",)
  1242.                         MySubHeader.RESOLUTION_BW_Hz = Convert.ToDouble(Item(1), Globalization.CultureInfo.InvariantCulture)
  1243.                     End If
  1244.                     If SourceLine.Contains("Th. Type ...... ") Then
  1245.                         Dim Item() As String = Split(SourceLine, ",")
  1246.                         If Item(1).Contains("False") Then
  1247.                             MySubHeader.THRESHOLD_TYPE = enmThresholdType.CPFA
  1248.                         Else
  1249.                             MySubHeader.THRESHOLD_TYPE = enmThresholdType.SNR
  1250.                             SourceLine = SourceStreamReader.ReadLine()
  1251.                             Item = Split(SourceLine, ",")
  1252.                             MySubHeader.THRESHOLD = Convert.ToDouble(Item(1), Globalization.CultureInfo.InvariantCulture)
  1253.                         End If
  1254.                     End If
  1255.  
  1256.                     If SourceLine.Contains("Pro. False Alarm ") Then
  1257.                         Dim Item() As String = Split(SourceLine, ",")
  1258.                         MySubHeader.THRESHOLD = Convert.ToDouble(Item(1), Globalization.CultureInfo.InvariantCulture)
  1259.                     End If
  1260.  
  1261.                     If SourceLine.Contains("FFT Window  ") Then
  1262.                         Dim Item = Split(SourceLine, ",")
  1263.                         If Item(1).Contains("Blackman") Then
  1264.                             MySubHeader.FFT_WINDOW = enmWindow.Blackman
  1265.                         ElseIf Item(1).Contains("Hann") Then
  1266.                             MySubHeader.FFT_WINDOW = enmWindow.Hann
  1267.                         ElseIf Item(1).Contains("Flat") Then
  1268.                             MySubHeader.FFT_WINDOW = enmWindow.FlatTop
  1269.                         Else
  1270.                             MySubHeader.FFT_WINDOW = enmWindow.Rectangular
  1271.                         End If
  1272.                         MySubHeader.FRAME_NB = CInt(txtNbFrames.Text)
  1273.                         MySubHeader.FRAME_AVG = enmFrame_Avg.PERIODIGRAM
  1274.                         MySubHeader.BW_ESTIMATION_RATIO = CDbl(txtBWRatio.Text)
  1275.                         MySubHeader.ANALYSIS_DURATION_MIN = MyPeriod
  1276.                         MySubHeader.ISDF = False
  1277.                     End If
  1278.  
  1279.                     'Read the description of the Channels
  1280.                    If SourceLine.Contains("Total Frequencies: ") Then
  1281.  
  1282.                         'Read number of frequencies covered
  1283.                        Dim Item() As String = Split(SourceLine, ",")
  1284.                         TOTAL_FREQUENCIES = Item(1)
  1285.                         ReDim MyChannels.BW(0 To TOTAL_FREQUENCIES - 1)
  1286.                         ReDim MyChannels.Carrier(0 To TOTAL_FREQUENCIES - 1)
  1287.                         ReDim MyChannels.Count(0 To TOTAL_FREQUENCIES - 1)
  1288.                         ReDim MyChannels.ID(0 To TOTAL_FREQUENCIES - 1)
  1289.                         ReDim MyChannels.BurstStateCurrent(0 To TOTAL_FREQUENCIES - 1)
  1290.                         ReDim MyChannels.BurstStatePrevious(0 To TOTAL_FREQUENCIES - 1)
  1291.                         ReDim MyChannels.BurstTime(0 To TOTAL_FREQUENCIES - 1)
  1292.                         ReDim MyChannels.IndexCurrentlyOn(0 To TOTAL_FREQUENCIES - 1)
  1293.                         ReDim MyChannels.IndexPreviouslyOn(0 To TOTAL_FREQUENCIES - 1)
  1294.  
  1295.                         'v. 2.2 - "Channel Number","Frequency Center (MHz)","Bandwidth (Hz)","Number of FFT Points","Channel ID"
  1296.                        If TOTAL_FREQUENCIES > 0 Then
  1297.                             'Skip 2 lines of header
  1298.                            If Not SourceStreamReader.EndOfStream Then SourceStreamReader.ReadLine()
  1299.                             If Not SourceStreamReader.EndOfStream Then SourceStreamReader.ReadLine()
  1300.                             'Read subsequent channel values & Write to file
  1301.                            DestinationLine = "DATA_LABELS: ChannelNb,Frequency(MHz),Bandwidth(Hz),NbFFTBins,ChannelID"
  1302.                             DestinationStreamWriter.WriteLine(DestinationLine)
  1303.  
  1304.                             SourceLine = SourceStreamReader.ReadLine()
  1305.                             Do Until SourceLine.Contains("Total Frequency Bands: ") ' Initiase the channels
  1306.                                DestinationStreamWriter.WriteLine(SourceLine)
  1307.                                 Item = Split(SourceLine, ",")
  1308.                                 Index = CInt(Item(0)) - 1
  1309.                                 MyChannels.ID(Index) = Item(4)
  1310.                                 MyChannels.BW(Index) = Convert.ToDouble(Item(2), Globalization.CultureInfo.InvariantCulture)
  1311.                                 MyChannels.Carrier(Index) = Convert.ToDouble(Item(1), Globalization.CultureInfo.InvariantCulture)
  1312.                                 SourceLine = SourceStreamReader.ReadLine()
  1313.                             Loop
  1314.                             SourceLine = "---"
  1315.                             DestinationStreamWriter.WriteLine(SourceLine)
  1316.                         End If
  1317.  
  1318.                         ' Set Histogrammes
  1319.                        ReDim MyHisto(0 To TOTAL_FREQUENCIES - 1)
  1320.  
  1321.                         For k = 0 To TOTAL_FREQUENCIES - 1
  1322.                             With MyHisto(k)
  1323.                                 ReDim .Power_dBmHisto(0 To Power_dBmRange.RangeStop - Power_dBmRange.RangeStart)
  1324.                                 ReDim .SNR_dBHisto(0 To SNR_dBRange.RangeStop - SNR_dBRange.RangeStart)
  1325.                                 ReDim .BandwidthPercentRangeHisto(0 To BandwidthPercentRange.RangeStop - BandwidthPercentRange.RangeStart)
  1326.                                 ReDim .CORangePercentHisto(0 To CORangePercentRange.RangeStop - CORangePercentRange.RangeStart)
  1327.                                 ReDim .BurstOn_dBmsHisto(0 To Burst_dBmsRange.RangeStop - Burst_dBmsRange.RangeStart)
  1328.                                 ReDim .BurstOff_dBmsHisto(0 To Burst_dBmsRange.RangeStop - Burst_dBmsRange.RangeStart)
  1329.                             End With
  1330.                         Next
  1331.                         IsHeader = False
  1332.                     End If 'Channel List
  1333.  
  1334.                     'Read a new line from the source file
  1335.                    SourceLine = SourceStreamReader.ReadLine()
  1336.  
  1337.                 ElseIf SourceLine.Contains("Scan:") Then
  1338.                     'Read scans
  1339.                    '"Elapsed Time (ms)","Number of GPS Data Lines","Number of Channels","Number of Signal Detections","Number of Messages in Alarm","Number of noise level measurements","Number of Occupancy bins"
  1340.                    'Read number of data lines
  1341.                    Dim Item() As String = Split(SourceLine, ",")
  1342.                     Dim TimeMilliseconds As Long = Item(1)
  1343.                     Dim LinesChannels As Long = Item(3)
  1344.                     Dim LinesDetections As Long = Item(4)
  1345.                     Dim LinesAlarm As Long = Item(5)
  1346.                     Dim NbLinesCurrentScan As Long = LinesChannels
  1347.  
  1348.  
  1349.                     If SourceLine2.Length = 0 Then
  1350.                         SourceLine = SourceStreamReader.ReadLine()
  1351.                     Else
  1352.                         SourceLine = SourceLine2
  1353.                     End If
  1354.  
  1355.                     Item = Split(SourceLine, ",")
  1356.                     ScanDate = GetDate(Item(0))
  1357.                     Index = Item(0).IndexOf(".") + 1
  1358.                     ScanDate = ScanDate.AddMilliseconds(Item(0).Substring(Index, 3))
  1359.  
  1360.                     EndMin = Math.Ceiling(ScanDate.Minute / MyPeriod + ScanDate.Second / 60.0 / MyPeriod + (ScanDate.Millisecond + 1) / 1000.0 / 60.0 / MyPeriod) * MyPeriod ' Add 1 ms to avoid case where hour is bang on
  1361.                    MyPeriodStartDateTime = DateTime.SpecifyKind(ScanDate, DateTimeKind.Utc)
  1362.                     MyPeriodStopDateTime = New DateTime(ScanDate.Year, ScanDate.Month, ScanDate.Day, ScanDate.Hour, 0, 0, DateTimeKind.Utc)
  1363.                     MyPeriodStopDateTime = MyPeriodStopDateTime.AddMinutes(EndMin)
  1364.                     PeriodSpan = MyPeriodStopDateTime - ScanDate
  1365.  
  1366.                     'Get Channel Measurements for the period
  1367.                    While PeriodSpan.TotalSeconds > 0 And Not SourceStreamReader.EndOfStream ' Does the period
  1368.                        NbRevisit += 1
  1369.  
  1370.                         ' Location
  1371.                        MyBox.LatMin = Math.Min(MyBox.LatMin, Convert.ToDouble(Item(1), Globalization.CultureInfo.InvariantCulture))
  1372.                         MyBox.LatMax = Math.Max(MyBox.LatMax, Convert.ToDouble(Item(1), Globalization.CultureInfo.InvariantCulture))
  1373.                         MyBox.LonMin = Math.Min(MyBox.LonMin, Convert.ToDouble(Item(2), Globalization.CultureInfo.InvariantCulture))
  1374.                         MyBox.LonMax = Math.Max(MyBox.LonMax, Convert.ToDouble(Item(2), Globalization.CultureInfo.InvariantCulture))
  1375.                         MyBox.AltMin = Math.Min(MyBox.AltMin, Convert.ToDouble(Item(3), Globalization.CultureInfo.InvariantCulture))
  1376.                         MyBox.AltMax = Math.Max(MyBox.AltMax, Convert.ToDouble(Item(3), Globalization.CultureInfo.InvariantCulture))
  1377.  
  1378.                         Dim Status As Integer, MovementStatus As Integer, GroundSpeed As Double, GroundAcceleration As Double, TrackMadeGood As Double, TrueHeading As Double
  1379.                         If Item.Length > 6 Then
  1380.                             Status = Item(5)
  1381.                             MovementStatus = Item(6)
  1382.                             GroundSpeed = Item(7)
  1383.                             GroundAcceleration = Item(8)
  1384.                             TrackMadeGood = Item(9)
  1385.                             TrueHeading = Item(10)
  1386.                         Else
  1387.                             Status = 1              'Default value, "Fixed Position"
  1388.                            MovementStatus = 0      'Default value, "Not Ready"
  1389.                            GroundSpeed = 0         'Default value, "No Movement"
  1390.                            GroundAcceleration = 0  'Default value, "No Movement"
  1391.                            TrackMadeGood = -1      'Default value, Negative value is considered invalid. Valid values cover [0 to 360[
  1392.                            TrueHeading = -1        'Default value, Negative value is considered invalid. Valid values cover [0 to 360[
  1393.                        End If
  1394.  
  1395.                         'Read the data to be written
  1396.                        output.Status = Status
  1397.                         output.MovementStatus = MovementStatus
  1398.                         output.GroundSpeed = GroundSpeed
  1399.                         output.GroundAcceleration = GroundAcceleration
  1400.                         output.TrackMadeGood = TrackMadeGood
  1401.                         output.TrueHeading = TrueHeading
  1402.                         Dim FixedDate As String = ""
  1403.                         FixedDate = FixedDate & ScanDate.Year & "-" & ScanDate.Month & "-" & ScanDate.Day & "T" & ScanDate.Hour & ":" & ScanDate.Minute & ":" & ScanDate.Second & "." & ScanDate.Millisecond
  1404.                         output.FixedDate = FixedDate
  1405.                         output.Latitude = MyBox.LatMin
  1406.                         output.Longitude = MyBox.LonMin
  1407.                         output.Altitude = MyBox.AltMin
  1408.  
  1409.                         DestinationLine = "GPS DATA LABELS: GPS scan Date And time,Latitude,Longitude,Elevation,Status (0=No GPS,1=Fixed Position,2=GPS Locked,3=GPS Unlocked,4=GPS Error),Movement Status (0=Not Ready, 1 = Ready),Ground Speed (m/sec),Ground Acceleration (m/sec2),Track Made Good (Degre relative To True north),True Heading (Degre relative To True north)"
  1410.                         DestinationStreamWriter.WriteLine(DestinationLine)
  1411.                         DestinationLine = "CHANNEL DATA LABELS: Channel Number,Power (dBm),C/N (dB),Frequency Center Deviation (Hz),Bandwidth (Hz),Direction (deg),Direction Quality (deg)"
  1412.                         DestinationStreamWriter.WriteLine(DestinationLine)
  1413.  
  1414.                         Do Until SourceStreamReader.EndOfStream Or LinesChannels <= 0 'Does one scan
  1415.                            LinesChannels -= 1
  1416.                             SourceLine = SourceStreamReader.ReadLine()
  1417.                             Item = Split(SourceLine, ",")
  1418.                             Index = CInt(Item(0)) - 1
  1419.                             MyChannels.Count(Index) += 1
  1420.                             If MyChannels.Carrier(Index) < MyHeader.FREQ_RANGE(0) Then
  1421.                                 MyHeader.FREQ_RANGE(0) = MyChannels.Carrier(Index)
  1422.                             End If
  1423.                             If MyChannels.Carrier(Index) > MyHeader.FREQ_RANGE(1) Then
  1424.                                 MyHeader.FREQ_RANGE(1) = MyChannels.Carrier(Index)
  1425.                             End If
  1426.  
  1427.                             'Read Power, SNR, Frequency Offset, BW
  1428.                            output.Power = Convert.ToDouble(Item(1), Globalization.CultureInfo.InvariantCulture)
  1429.                             output.SNR = Convert.ToDouble(Item(2), Globalization.CultureInfo.InvariantCulture)
  1430.                             output.Freq = Convert.ToDouble(Item(3), Globalization.CultureInfo.InvariantCulture)
  1431.                             output.BW = Convert.ToDouble(Item(4), Globalization.CultureInfo.InvariantCulture)
  1432.                             output.Dir = Convert.ToDouble(Item(5), Globalization.CultureInfo.InvariantCulture)
  1433.                             output.DirQuality = Convert.ToDouble(Item(6), Globalization.CultureInfo.InvariantCulture)
  1434.  
  1435.                             output.ChannelNum = Index + 1
  1436.  
  1437.                             WriteMeasurement(output, DestinationStreamWriter)
  1438.                             DestinationChannelMeasurement += 1
  1439.                         Loop 'End Scan
  1440.  
  1441.                         If IsFirstScan Then
  1442.                             MyHeader.StartDateTime = DateTime.SpecifyKind(ScanDate, DateTimeKind.Utc)
  1443.                             IsFirstScan = False
  1444.                         End If
  1445.  
  1446.                         ' Reset current states
  1447.                        Array.Clear(MyChannels.BurstStatePrevious, 0, TOTAL_FREQUENCIES)
  1448.                         For k = 0 To NbLinesCurrentScan - 1
  1449.                             Index = MyChannels.IndexCurrentlyOn(k)
  1450.                             MyChannels.BurstStatePrevious(Index) = MyChannels.BurstStateCurrent(Index)
  1451.                             MyChannels.BurstStateCurrent(Index) = False
  1452.                             MyChannels.IndexPreviouslyOn(k) = MyChannels.IndexCurrentlyOn(k)
  1453.                         Next
  1454.                         NbLinesPreviousScan = NbLinesCurrentScan
  1455.  
  1456.                         ' Read for next scan
  1457.                        SourceLine = SourceStreamReader.ReadLine()
  1458.                         If SourceStreamReader.EndOfStream Then
  1459.                             ' End of file
  1460.                            Exit While
  1461.                         Else
  1462.                             Item = Split(SourceLine, ",")
  1463.                             LinesChannels = Item(3)
  1464.                             LinesDetections = Item(4)
  1465.                             LinesAlarm = Item(5)
  1466.                             NbLinesCurrentScan = LinesChannels
  1467.  
  1468.                             SourceLine2 = SourceStreamReader.ReadLine()
  1469.                             Item = Split(SourceLine2, ",")
  1470.                             ScanDate = GetDate(Item(0))
  1471.                             Index = Item(0).IndexOf(".") + 1
  1472.                             ScanDate = ScanDate.AddMilliseconds(CDbl(Item(0).Substring(Index, 3)))
  1473.                             PeriodSpan = MyPeriodStopDateTime - ScanDate
  1474.  
  1475.                             AverageRevisitCount += 1
  1476.                         End If
  1477.  
  1478.                     End While
  1479.  
  1480.                     'Save data period to consolidated file
  1481.                    If ckbCorrectForUTC.Checked = True Then
  1482.                         ' UTC correction
  1483.                        Dim TmpDate As DateTime
  1484.                         TmpDate = MyPeriodStartDateTime.Subtract(MyHeader.TimeZoneOffset)
  1485.                         DestinationLine = "StartDateTime: " + TmpDate.ToString("o")
  1486.                         DestinationStreamWriter.WriteLine(DestinationLine)
  1487.  
  1488.                         If PeriodSpan.TotalSeconds > 0 Then
  1489.                             TmpDate = ScanDate.Subtract(MyHeader.TimeZoneOffset)
  1490.                             DestinationLine = "StopDateTime: " + DateTime.SpecifyKind(TmpDate, DateTimeKind.Utc).ToString("o")
  1491.                         Else
  1492.                             TmpDate = MyPeriodStopDateTime.Subtract(MyHeader.TimeZoneOffset)
  1493.                             DestinationLine = "StopDateTime: " + TmpDate.ToString("o")
  1494.                         End If
  1495.                     Else
  1496.                         ' N0 UTC corrections
  1497.                        DestinationLine = "StartDateTime: " + MyPeriodStartDateTime.ToString("o")
  1498.                         DestinationStreamWriter.WriteLine(DestinationLine)
  1499.                         If PeriodSpan.TotalSeconds > 0 Then
  1500.                             DestinationLine = "StopDateTime: " + DateTime.SpecifyKind(ScanDate, DateTimeKind.Utc).ToString("o")
  1501.                         Else
  1502.                             DestinationLine = "StopDateTime: " + MyPeriodStopDateTime.ToString("o")
  1503.                         End If
  1504.                     End If
  1505.                     DestinationStreamWriter.WriteLine(DestinationLine)
  1506.  
  1507.                     If (MyBox.LatMax = MyBox.LatMin) And
  1508.                            (MyBox.LonMax = MyBox.LonMin) And IsPointAllowed Then
  1509.                         ' POINT
  1510.                        DestinationLine = "LOCATION: POINT " + MyBox.LatMax.ToString(Globalization.CultureInfo.InvariantCulture) +
  1511.                             " " + MyBox.LonMax.ToString(Globalization.CultureInfo.InvariantCulture) +
  1512.                             " " + MyBox.AltMax.ToString(Globalization.CultureInfo.InvariantCulture)
  1513.                     Else
  1514.                         ' BOX
  1515.                        DestinationLine = "LOCATION: BOX " + MyBox.LatMin.ToString(Globalization.CultureInfo.InvariantCulture) +
  1516.                             " " + MyBox.LatMin.ToString(Globalization.CultureInfo.InvariantCulture) +
  1517.                             " " + MyBox.LatMax.ToString(Globalization.CultureInfo.InvariantCulture) +
  1518.                             " " + MyBox.LatMax.ToString(Globalization.CultureInfo.InvariantCulture) +
  1519.                             " " + MyBox.LonMin.ToString(Globalization.CultureInfo.InvariantCulture) +
  1520.                             " " + MyBox.LonMax.ToString(Globalization.CultureInfo.InvariantCulture) +
  1521.                             " " + MyBox.LonMax.ToString(Globalization.CultureInfo.InvariantCulture) +
  1522.                             " " + MyBox.LonMin.ToString(Globalization.CultureInfo.InvariantCulture) +
  1523.                             " " + MyBox.AltMin.ToString(Globalization.CultureInfo.InvariantCulture) +
  1524.                             " " + MyBox.AltMax.ToString(Globalization.CultureInfo.InvariantCulture)
  1525.                     End If
  1526.                     DestinationStreamWriter.WriteLine(DestinationLine)
  1527.  
  1528.                     ' Other parameters
  1529.                    DestinationLine = "# of revisit: " + NbRevisit.ToString
  1530.                     DestinationStreamWriter.WriteLine(DestinationLine)
  1531.                     NbRevisit = 0
  1532.  
  1533.                     ActiveChannelCount = 0
  1534.                     For k = 0 To TOTAL_FREQUENCIES - 1
  1535.                         If MyChannels.Count(k) Then
  1536.                             ActiveChannelCount += 1
  1537.                         End If
  1538.                     Next
  1539.                     DestinationLine = "Active Channels count: " + ActiveChannelCount.ToString
  1540.                     DestinationStreamWriter.WriteLine(DestinationLine)
  1541.                     DestinationLine = "---"
  1542.                     DestinationStreamWriter.WriteLine(DestinationLine)
  1543.  
  1544.                     ' Position information
  1545.                    ' Compare with global box
  1546.                    MyGlobalBox.LatMin = Math.Min(MyBox.LatMin, MyGlobalBox.LatMin)
  1547.                     MyGlobalBox.LatMax = Math.Max(MyBox.LatMax, MyGlobalBox.LatMax)
  1548.                     MyGlobalBox.LonMin = Math.Min(MyBox.LonMin, MyGlobalBox.LonMin)
  1549.                     MyGlobalBox.LonMax = Math.Max(MyBox.LonMax, MyGlobalBox.LonMax)
  1550.                     MyGlobalBox.AltMin = Math.Min(MyBox.AltMin, MyGlobalBox.AltMin)
  1551.                     MyGlobalBox.AltMax = Math.Max(MyBox.AltMax, MyGlobalBox.AltMax)
  1552.                     ResetBox(MyBox)
  1553.  
  1554.                     ' Reset Arrays
  1555.                    ResetArrays()
  1556.  
  1557.                     'Update the GUI with the estimated Time Left
  1558.                    Duration = NowTime.Subtract(PastTime)
  1559.                     If NowPosition > PastPosition Then
  1560.                         DataCovered = NowPosition - PastPosition
  1561.                         CoverageRate = Duration.TotalSeconds / DataCovered
  1562.                         TimeLeftSeconds = (SourceStreamReader.BaseStream.Length - NowPosition) * CoverageRate
  1563.                         TimeLeftsSeconds.Enqueue(TimeLeftSeconds)
  1564.                         If TimeLeftsSeconds.Count > 5 Then TimeLeftsSeconds.Dequeue()
  1565.                         TimeLeftSecondsSum = 0
  1566.                         For Each I As Double In TimeLeftsSeconds
  1567.                             TimeLeftSecondsSum += I
  1568.                         Next
  1569.                         TimeLeftSecondsAvg = TimeLeftSecondsSum / TimeLeftsSeconds.Count
  1570.                         'Update the GUI if at least 1 second has passed since last update
  1571.                        DurationRefresh = NowTime.Subtract(PastRefresh)
  1572.                         If DurationRefresh.TotalSeconds > 1 Then
  1573.                             PastRefresh = NowTime
  1574.                             Dim DurationTimeSpan As New TimeSpan(TimeLeftSecondsAvg * TimeSpan.TicksPerSecond)
  1575.                             Dim TimeText As String = Mid(DurationTimeSpan.ToString, 1, DurationTimeSpan.ToString.IndexOf("."c)) '& Format(TimeLeftSecondsAvg, "0.00") & " seconds"
  1576.                            lblStatus.Text = "Consolidation in progress... Time remaining: " & TimeText & "."
  1577.                             Me.Refresh()
  1578.                             RaiseEvent ConversionCompleted(pgbStatus.Value, TimeText, True, DestinationFilename)
  1579.                             ConversionCompletedToStdOutput(pgbStatus.Value, TimeText, True, SourceFilename, DestinationFilename)
  1580.                         End If
  1581.                         'Get variables ready for next algorithm pass
  1582.                        PastPosition = NowPosition
  1583.                         PastTime = NowTime
  1584.                     End If
  1585.                 Else
  1586.                     'Read a new line from the source file
  1587.                    SourceLine = SourceStreamReader.ReadLine()
  1588.                 End If 'End Period
  1589.  
  1590.                 If SourceStreamReader.EndOfStream Then
  1591.                     ' Write Start/StopDateTime, revisit time
  1592.                    PeriodSpan = ScanDate - MyHeader.StartDateTime
  1593.                     MyHeader.StopDateTime = DateTime.SpecifyKind(ScanDate, DateTimeKind.Utc)
  1594.                     MySubHeader.REVISIT_TIME_s = PeriodSpan.TotalSeconds / AverageRevisitCount
  1595.                     Exit While
  1596.                 End If
  1597.  
  1598.                 ' Listen to user inputs
  1599.                System.Windows.Forms.Application.DoEvents()
  1600.  
  1601.                 ' The application is closing. Close any opened file
  1602.                If isClosing Then
  1603.                     DestinationStreamWriter.Close()
  1604.                     SourceStreamReader.Close()
  1605.                     Return False
  1606.                 End If
  1607.  
  1608.                 ' Report the error and close any opened file
  1609.                If isCanceled Then
  1610.                     lblStatus.Text = "Consolidation was canceled by the user."
  1611.                     DestinationStreamWriter.Close()
  1612.                     SourceStreamReader.Close()
  1613.                     Return False
  1614.                 End If
  1615.  
  1616.             End While
  1617.         Catch ex As Exception
  1618.  
  1619.             ' Report the error and close any opened file
  1620.            LogError(ex.Message)
  1621.             DestinationStreamWriter.Close()
  1622.             SourceStreamReader.Close()
  1623.             Return False
  1624.  
  1625.         End Try
  1626.         ' Success. Close any opened file. Combine the header with the data. Report success
  1627.        DestinationStreamWriter.Close()
  1628.         SourceStreamReader.Close()
  1629.         Dim Analysis As Boolean = False
  1630.         CompleteDestination(MyHeader, DestinationFilename, Pathname, Analysis)
  1631.         pgbStatus.Value = 100
  1632.  
  1633.         'Zip the file
  1634.        Dim tempFolder As String = Pathname + "\temp"
  1635.         My.Computer.FileSystem.CreateDirectory(tempFolder)
  1636.         'To zip the output into a new directory, just change "zipPath" below to the desired directory
  1637.        Dim zipPath As String = DestinationPath + "\" + MyHeader.SENSOR_HOST_ID + "-" + MyHeader.SENSOR_OUTPUT + "-" + MyHeader.TASK_MISSION + "-" +
  1638.                 Replace(MyHeader.StartDateTime.ToString("o"), ":", "-") + ".zip"
  1639.         Dim targetFile As String = tempFolder + "\" + MyHeader.SENSOR_HOST_ID + "-" + MyHeader.SENSOR_OUTPUT + "-" + MyHeader.TASK_MISSION + "-" +
  1640.                 Replace(MyHeader.StartDateTime.ToString("o"), ":", "-") + ".txt"
  1641.         My.Computer.FileSystem.MoveFile(DestinationFilename, targetFile)
  1642.  
  1643.  
  1644.         Console.Write("Zipping to    ")
  1645.         Console.WriteLine(zipPath)
  1646.         ZipFile.CreateFromDirectory(tempFolder, zipPath)
  1647.         My.Computer.FileSystem.DeleteDirectory(tempFolder, FileIO.DeleteDirectoryOption.DeleteAllContents)
  1648.  
  1649.         Return True
  1650.  
  1651.     End Function
  1652.  
  1653.     Private Sub CompleteDestination(ByVal Header As udtHeader, ByRef DataFilename As String, ByVal Path As String, ByVal Analysis As Boolean)
  1654.         ' Header file to write header and sub-header.
  1655.        Dim HeadFileName As String = Replace(DataFilename, ".histo", ".hed")
  1656.         Dim HeaderDestinationStreamWriter = New IO.StreamWriter(HeadFileName, False, System.Text.Encoding.Default)
  1657.  
  1658.         WriteHeader(HeaderDestinationStreamWriter)
  1659.         WriteSubHeader(HeaderDestinationStreamWriter, Analysis)
  1660.  
  1661.         ' Close the header file
  1662.        HeaderDestinationStreamWriter.Close()
  1663.  
  1664.         ' Merge files: Destination file to write header, sub-header and data
  1665.        Dim DestinationFile As String
  1666.         If ckbCorrectForUTC.Checked = True Then
  1667.             Dim tmpDate As DateTime
  1668.             tmpDate = MyHeader.StartDateTime.Subtract(MyHeader.TimeZoneOffset)
  1669.             DestinationFile = Path + "\" + Header.SENSOR_HOST_ID + "-" + Header.SENSOR_OUTPUT + "-" + Header.TASK_MISSION + "-" +
  1670.                 Replace(tmpDate.ToString("o"), ":", "-") + ".txt"
  1671.         Else
  1672.             DestinationFile = Path + "\" + Header.SENSOR_HOST_ID + "-" + Header.SENSOR_OUTPUT + "-" + Header.TASK_MISSION + "-" +
  1673.                 Replace(MyHeader.StartDateTime.ToString("o"), ":", "-") + ".txt"
  1674.         End If
  1675.  
  1676.         lblDestination.Text = DestinationFile
  1677.  
  1678.         Dim DestinationStream As IO.FileStream = IO.File.Create(DestinationFile)
  1679.         Dim aFileStream As IO.FileStream = IO.File.OpenRead(HeadFileName)
  1680.         aFileStream.CopyTo(DestinationStream)
  1681.         aFileStream.Close()
  1682.  
  1683.         aFileStream = IO.File.OpenRead(DataFilename)
  1684.         aFileStream.CopyTo(DestinationStream)
  1685.         aFileStream.Close()
  1686.  
  1687.         DestinationStream.Close()
  1688.         Kill(HeadFileName)
  1689.         Kill(DataFilename)
  1690.         DataFilename = DestinationFile
  1691.     End Sub
  1692.  
  1693.     Private Sub ConversionCompletedToStdOutput(pct As Integer, timeLeft As String, isBusy As Boolean, filename As String, outputFilename As String)
  1694.         Console.WriteLine(pct.ToString + "," + timeLeft + "," + isBusy.ToString + "," + filename + "," + outputFilename)
  1695.     End Sub
  1696.  
  1697.     Private Sub ErrorReportToStdOutput(errMsg As String)
  1698.         Console.WriteLine(errMsg)
  1699.     End Sub
  1700.  
  1701.     Private Shared Function GetDate(ByVal StringDate As String) As Date
  1702.         Dim DateTimeParts() As String = Split(StringDate, " ")
  1703.         Dim DateParts() As String = Split(DateTimeParts(0), "-")
  1704.         Dim TimeParts() As String = Split(DateTimeParts(1), ":")
  1705.         Dim NewTime As Date
  1706.         Try
  1707.             'Try in English
  1708.            NewTime = New DateTime(CInt(DateParts(2)), CInt(DateParts(1)), CInt(DateParts(0).Remove(0, 1)),
  1709.                                   CInt(TimeParts(0)), CInt(TimeParts(1)), CInt(Math.Floor(Val(TimeParts(2)))))
  1710.         Catch ex As Exception
  1711.             'If an error occurs, it could be that the date was written in another order
  1712.            Try
  1713.                 'Try in French
  1714.                NewTime = New DateTime(CInt(DateParts(2)), CInt(DateParts(0).Remove(0, 1)), CInt(DateParts(1)),
  1715.                                     CInt(TimeParts(0)), CInt(TimeParts(1)), CInt(Math.Floor(Val(TimeParts(2)))))
  1716.             Catch ex1 As Exception
  1717.                 'Do nothing
  1718.            End Try
  1719.         End Try
  1720.         Return NewTime
  1721.     End Function
  1722.  
  1723.     Private Sub tmrTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrTimer.Tick
  1724.  
  1725.         Dim IsHisto As Boolean
  1726.         Dim IsMeasurement As Boolean
  1727.         Dim ThePath As String
  1728.  
  1729.         IsHisto = ckbHisto.Checked
  1730.         IsMeasurement = ckbMeasurement.Checked
  1731.  
  1732.         'Disable the timer after it was initially called
  1733.        tmrTimer.Enabled = False
  1734.  
  1735.         'Work on the assigned task
  1736.        Select Case MyTimerTask
  1737.             'If files need to be converted to database
  1738.            Case enmTasks.ProcessDragAndDropFiles
  1739.                 Try
  1740.                     'Convert each file
  1741.                    Dim Result As Boolean
  1742.                     For Each File As String In MyDragAndDropFiles
  1743.                         ThePath = System.IO.Path.GetDirectoryName(folderpath)
  1744.                         Result = UnzipDirectory(folderpath, ThePath, IsHisto, IsMeasurement)
  1745.                         If Result = False Then
  1746.                             Exit For
  1747.                         End If
  1748.                     Next
  1749.                 Catch ex As Exception
  1750.                     'Do nothing
  1751.                End Try
  1752.                 'Clean up the files and task
  1753.                MyTimerTask = enmTasks.DoNothing
  1754.                 MyDragAndDropFiles = Nothing
  1755.             Case enmTasks.ProcessFolderfile
  1756.                 Try
  1757.                     'Convert each file
  1758.                    Dim Result As Boolean
  1759.                     ThePath = System.IO.Path.GetDirectoryName(folderpath)
  1760.                     Result = UnzipDirectory(folderpath, ThePath, IsHisto, IsMeasurement)
  1761.                 Catch ex As Exception
  1762.                 End Try
  1763.         End Select
  1764.  
  1765.     End Sub
  1766.  
  1767.     ' This sub is used by SEDBE Folder Monitor
  1768.    Public Sub ConvertFiles(filenames As String())
  1769.         MyDragAndDropFiles = filenames
  1770.         MyTimerTask = enmTasks.ProcessDragAndDropFiles
  1771.         tmrTimer.Enabled = True
  1772.     End Sub
  1773.  
  1774.     ' This sub is used by SEDBE Folder Monitor
  1775.    Public Sub CancelConversion()
  1776.         'Inform any running algorithm of the user's intervention
  1777.        If InvokeRequired Then
  1778.             Invoke(Sub() isCanceled = True)
  1779.             Invoke(Sub() btnCancel.Enabled = False)
  1780.         Else
  1781.             isCanceled = True
  1782.             btnCancel.Enabled = False
  1783.         End If
  1784.     End Sub
  1785.  
  1786.     ' This sub is used by SEDBE Folder Monitor
  1787.    Public Sub ConvertFile(filename As String)
  1788.         If InvokeRequired Then
  1789.             Invoke(Sub() MyDragAndDropFiles = {filename})
  1790.             Invoke(Sub() MyTimerTask = enmTasks.ProcessDragAndDropFiles)
  1791.             Invoke(Sub() tmrTimer.Enabled = True)
  1792.         Else
  1793.             MyDragAndDropFiles = {filename}
  1794.             MyTimerTask = enmTasks.ProcessDragAndDropFiles
  1795.             If isHidden Then
  1796.                 tmrTimer_Tick(Nothing, Nothing)
  1797.             Else
  1798.                 tmrTimer.Enabled = True
  1799.             End If
  1800.         End If
  1801.     End Sub
  1802.  
  1803.     ' This sub is used by SEDBE Folder Monitor
  1804.    Public Sub Quit()
  1805.         If InvokeRequired Then
  1806.             Invoke(Sub() Me.Close())
  1807.         Else
  1808.             Me.Close()
  1809.         End If
  1810.  
  1811.     End Sub
  1812.  
  1813.     Private Sub btnHelp_Click(sender As Object, e As EventArgs) Handles btnHelp.Click
  1814.         DisplayHelpFile()
  1815.     End Sub
  1816.  
  1817.     Private Sub btnInfo_Click(sender As Object, e As EventArgs) Handles btnInfo.Click
  1818.         ' Display the info file contents in the command line and in a message box like Remote Desktop (mstsc.exe)
  1819.        Try
  1820.             Dim helpFilename As String = Application.StartupPath & "\SEDBE info.txt"
  1821.             Dim helpMessage As String = System.IO.File.ReadAllText(helpFilename)
  1822.             System.Diagnostics.Process.Start("notepad.exe", helpFilename)
  1823.  
  1824.         Catch ex As Exception
  1825.             MsgBox("Error accessing the info file: " & ex.Message)
  1826.         End Try
  1827.     End Sub
  1828.  
  1829.     Private Sub DisplayHelpFile()
  1830.         ' Display the help file contents in the command line and in a message box like Remote Desktop (mstsc.exe)
  1831.        Try
  1832.             Dim helpFilename As String = Application.StartupPath & "\SEDBE help.txt"
  1833.             Dim helpMessage As String = System.IO.File.ReadAllText(helpFilename)
  1834.             Console.Write(helpMessage)
  1835.             System.Diagnostics.Process.Start("notepad.exe", helpFilename)
  1836.         Catch ex As Exception
  1837.             MsgBox("Error accessing the help file: " & ex.Message)
  1838.         End Try
  1839.     End Sub
  1840.  
  1841.     Private Sub WriteHeader(TheDestinationStreamWriter As System.IO.StreamWriter)
  1842.         Dim DestinationLine As String
  1843.  
  1844.         DestinationLine = "FILE_VERSION: " + MyHeader.VERSION.ToString("F1", Globalization.CultureInfo.InvariantCulture)
  1845.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1846.         DestinationLine = "SENSOR_ROLE: " + MyHeader.SENSOR_ROLE
  1847.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1848.         DestinationLine = "SENSOR_OUTPUT: " + MyHeader.SENSOR_OUTPUT
  1849.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1850.         DestinationLine = "SENSOR_HOST_ID: " + MyHeader.SENSOR_HOST_ID
  1851.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1852.         DestinationLine = "SENSOR_TECHNOLOGY: " + MyHeader.SENSOR_TECHNOLOGY
  1853.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1854.         DestinationLine = "SENSOR_HW_ID: " + MyHeader.SENSOR_HW_ID
  1855.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1856.         DestinationLine = "TASK/MISSION: " + MyHeader.TASK_MISSION
  1857.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1858.         If ckbCorrectForUTC.Checked = True Then
  1859.             Dim TmpDate As DateTime
  1860.             TmpDate = MyHeader.StartDateTime.Subtract(MyHeader.TimeZoneOffset)
  1861.             DestinationLine = "START_TIME: " + TmpDate.ToString("o")
  1862.             TheDestinationStreamWriter.WriteLine(DestinationLine)
  1863.             TmpDate = MyHeader.StopDateTime.Subtract(MyHeader.TimeZoneOffset)
  1864.             DestinationLine = "END_TIME: " + TmpDate.ToString("o")
  1865.             TheDestinationStreamWriter.WriteLine(DestinationLine)
  1866.         Else
  1867.             DestinationLine = "START_TIME: " + MyHeader.StartDateTime.ToString("o")
  1868.             TheDestinationStreamWriter.WriteLine(DestinationLine)
  1869.             DestinationLine = "END_TIME: " + MyHeader.StopDateTime.ToString("o")
  1870.             TheDestinationStreamWriter.WriteLine(DestinationLine)
  1871.         End If
  1872.  
  1873.         If MyHeader.TimeZoneOffset.Hours >= 0 Then
  1874.             DestinationLine = "TIME_ZONE_OFFSET: " + MyHeader.TimeZoneOffset.ToString("hh\:mm")
  1875.         Else
  1876.             DestinationLine = "TIME_ZONE_OFFSET: " + "-" + MyHeader.TimeZoneOffset.ToString("hh\:mm")
  1877.         End If
  1878.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1879.         DestinationLine = "FREQ_RANGE_MHZ: " +
  1880.             MyHeader.FREQ_RANGE(0).ToString("F0", Globalization.CultureInfo.InvariantCulture) + " " +
  1881.             MyHeader.FREQ_RANGE(1).ToString("F0", Globalization.CultureInfo.InvariantCulture)
  1882.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1883.         If (MyGlobalBox.LatMax = MyGlobalBox.LatMin) And
  1884.                 (MyGlobalBox.LonMax = MyGlobalBox.LonMin) And IsPointAllowed Then
  1885.             ' Point
  1886.            DestinationLine = "LOCATION: POINT " + MyGlobalBox.LatMin.ToString(Globalization.CultureInfo.InvariantCulture) +
  1887.                 " " + MyGlobalBox.LonMax.ToString(Globalization.CultureInfo.InvariantCulture) +
  1888.                 " " + MyGlobalBox.AltMax.ToString(Globalization.CultureInfo.InvariantCulture)
  1889.         Else
  1890.             'Box
  1891.            DestinationLine = "LOCATION: BOX " + MyGlobalBox.LatMin.ToString(Globalization.CultureInfo.InvariantCulture) +
  1892.                 " " + MyGlobalBox.LatMin.ToString(Globalization.CultureInfo.InvariantCulture) +
  1893.                 " " + MyGlobalBox.LatMax.ToString(Globalization.CultureInfo.InvariantCulture) +
  1894.                 " " + MyGlobalBox.LatMax.ToString(Globalization.CultureInfo.InvariantCulture) +
  1895.                 " " + MyGlobalBox.LonMin.ToString(Globalization.CultureInfo.InvariantCulture) +
  1896.                 " " + MyGlobalBox.LonMax.ToString(Globalization.CultureInfo.InvariantCulture) +
  1897.                 " " + MyGlobalBox.LonMax.ToString(Globalization.CultureInfo.InvariantCulture) +
  1898.                 " " + MyGlobalBox.LonMin.ToString(Globalization.CultureInfo.InvariantCulture) +
  1899.                 " " + MyGlobalBox.AltMin.ToString(Globalization.CultureInfo.InvariantCulture) +
  1900.                 " " + MyGlobalBox.AltMax.ToString(Globalization.CultureInfo.InvariantCulture)
  1901.         End If
  1902.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1903.         DestinationLine = "---"
  1904.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1905.     End Sub
  1906.     Private Sub WriteSubHeader(TheDestinationStreamWriter As System.IO.StreamWriter, ByVal Analysis As Boolean)
  1907.  
  1908.         Dim DestinationLine As String
  1909.         DestinationLine = "MEASUREMENTFILE: " + MySubHeader.MEASUREMENTFILE
  1910.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1911.         DestinationLine = "REVISIT_TIME(s): " + MySubHeader.REVISIT_TIME_s.ToString(Globalization.CultureInfo.InvariantCulture)
  1912.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1913.         DestinationLine = "RESOLUTION_BW(Hz): " + MySubHeader.RESOLUTION_BW_Hz.ToString(Globalization.CultureInfo.InvariantCulture)
  1914.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1915.         DestinationLine = "THRESHOLD_TYPE: " + MySubHeader.THRESHOLD_TYPE.ToString
  1916.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1917.         DestinationLine = "THRESHOLD: " + MySubHeader.THRESHOLD.ToString((Globalization.CultureInfo.InvariantCulture))
  1918.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1919.         DestinationLine = "BW_ESTIMATION_RATIO: " + MySubHeader.BW_ESTIMATION_RATIO.ToString((Globalization.CultureInfo.InvariantCulture))
  1920.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1921.         DestinationLine = "FFT_WINDOW: " + MySubHeader.FFT_WINDOW.ToString
  1922.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1923.         DestinationLine = "FRAME_AVG: " + MySubHeader.FRAME_AVG.ToString
  1924.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1925.         DestinationLine = "NB_BLOCK: " + MySubHeader.FRAME_NB.ToString
  1926.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1927.         DestinationLine = "IS_DF: " + MySubHeader.ISDF.ToString(Globalization.CultureInfo.InvariantCulture)
  1928.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1929.         If Analysis Then
  1930.             DestinationLine = "ANALYSIS_DURATION(MIN): " + MySubHeader.ANALYSIS_DURATION_MIN.ToString
  1931.             TheDestinationStreamWriter.WriteLine(DestinationLine)
  1932.             DestinationLine = "Power(dBm)_range: " + Power_dBmRange.RangeStart.ToString + "/1/" + Power_dBmRange.RangeStop.ToString
  1933.             TheDestinationStreamWriter.WriteLine(DestinationLine)
  1934.             DestinationLine = "SNR(dB)_range: " + SNR_dBRange.RangeStart.ToString + "/1/" + SNR_dBRange.RangeStop.ToString
  1935.             TheDestinationStreamWriter.WriteLine(DestinationLine)
  1936.             DestinationLine = "Bandwidth(%)_range: " + BandwidthPercentRange.RangeStart.ToString + "/1/" + BandwidthPercentRange.RangeStop.ToString
  1937.             TheDestinationStreamWriter.WriteLine(DestinationLine)
  1938.             DestinationLine = "CF_offset(%)_range: " + CORangePercentRange.RangeStart.ToString + "/1/" + CORangePercentRange.RangeStop.ToString
  1939.             TheDestinationStreamWriter.WriteLine(DestinationLine)
  1940.             DestinationLine = "Burst_(dbms)_range: " + Burst_dBmsRange.RangeStart.ToString + "/1/" + Burst_dBmsRange.RangeStop.ToString
  1941.             TheDestinationStreamWriter.WriteLine(DestinationLine)
  1942.         End If
  1943.     End Sub
  1944.  
  1945.     Private Sub WriteHisto(TheDestinationStreamWriter As System.IO.StreamWriter)
  1946.         Dim k, Count As Integer
  1947.         Dim DestinationLine As String = ""
  1948.         DestinationLine = "DATA_LABELS: ChannelID,Count,Power_histogramm_dBm"
  1949.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1950.         For k = 0 To TOTAL_FREQUENCIES - 1
  1951.             If MyChannels.Count(k) Then
  1952.                 DestinationLine = MyChannels.ID(k).ToString + " " + MyChannels.Count(k).ToString + " " + String.Join(",", MyHisto(k).Power_dBmHisto)
  1953.                 TheDestinationStreamWriter.WriteLine(DestinationLine)
  1954.             End If
  1955.         Next
  1956.  
  1957.         DestinationLine = "DATA_LABELS: ChannelID,Count,SNR_histogram_dB"
  1958.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1959.         For k = 0 To TOTAL_FREQUENCIES - 1
  1960.             If MyChannels.Count(k) Then
  1961.                 DestinationLine = MyChannels.ID(k).ToString + " " + MyChannels.Count(k).ToString + " " + String.Join(",", MyHisto(k).SNR_dBHisto)
  1962.                 TheDestinationStreamWriter.WriteLine(DestinationLine)
  1963.             End If
  1964.         Next
  1965.         'OVERFLOW OCCURS HERE, BELOW
  1966.        DestinationLine = "DATA_LABELS: ChannelID,Count,CF_offset_histogram_%"
  1967.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1968.         For k = 0 To TOTAL_FREQUENCIES - 1
  1969.             If MyChannels.Count(k) Then
  1970.                 DestinationLine = MyChannels.ID(k).ToString + " " + MyChannels.Count(k).ToString + " " + String.Join(",", MyHisto(k).CORangePercentHisto)
  1971.                 TheDestinationStreamWriter.WriteLine(DestinationLine)
  1972.             End If
  1973.         Next
  1974.  
  1975.         DestinationLine = "DATA_LABELS: ChannelID,Count,Bandwidth_histogram_%"
  1976.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1977.         For k = 0 To TOTAL_FREQUENCIES - 1
  1978.             If MyChannels.Count(k) Then
  1979.                 DestinationLine = MyChannels.ID(k).ToString + " " + MyChannels.Count(k).ToString + " " + String.Join(",", MyHisto(k).BandwidthPercentRangeHisto)
  1980.                 TheDestinationStreamWriter.WriteLine(DestinationLine)
  1981.             End If
  1982.         Next
  1983.  
  1984.         DestinationLine = "DATA_LABELS: ChannelID,Count,Burst_on_histogram_dbms"
  1985.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1986.         For k = 0 To TOTAL_FREQUENCIES - 1
  1987.             If MyChannels.Count(k) Then
  1988.                 Count = MyHisto(k).BurstOn_dBmsHisto.Sum
  1989.                 DestinationLine = MyChannels.ID(k).ToString + " " + Count.ToString + " " + String.Join(",", MyHisto(k).BurstOn_dBmsHisto)
  1990.                 TheDestinationStreamWriter.WriteLine(DestinationLine)
  1991.             End If
  1992.         Next
  1993.  
  1994.         DestinationLine = "DATA_LABELS: ChannelID,Count,Burst_off_histogram_dbms"
  1995.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  1996.         For k = 0 To TOTAL_FREQUENCIES - 1
  1997.             If MyChannels.Count(k) Then
  1998.                 Count = MyHisto(k).BurstOff_dBmsHisto.Sum
  1999.                 DestinationLine = MyChannels.ID(k).ToString + " " + Count.ToString + " " + String.Join(",", MyHisto(k).BurstOff_dBmsHisto)
  2000.                 TheDestinationStreamWriter.WriteLine(DestinationLine)
  2001.             End If
  2002.         Next
  2003.         DestinationLine = "---"
  2004.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  2005.     End Sub
  2006.  
  2007.     Private Sub WriteMeasurement(ByVal output As MeasurementData, TheDestinationStreamWriter As System.IO.StreamWriter)
  2008.         Dim DestinationLine As String
  2009.         DestinationLine = output.FixedDate & "," & MyBox.LatMin & "," & MyBox.LonMin & "," & MyBox.AltMin & "," & output.Status & "," & output.MovementStatus & "," & output.GroundSpeed & "," & output.GroundAcceleration & "," & output.TrackMadeGood & "," & output.TrueHeading & ","
  2010.         TheDestinationStreamWriter.Write(DestinationLine)
  2011.         DestinationLine = "" & output.ChannelNum & "," & output.Power & "," & output.SNR & "," & output.Freq & "," & output.BW & "," & output.Dir & "," & output.DirQuality
  2012.         TheDestinationStreamWriter.WriteLine(DestinationLine)
  2013.     End Sub
  2014.  
  2015.     Private Sub ResetArrays()
  2016.         For k = 0 To TOTAL_FREQUENCIES - 1
  2017.             If MyChannels.Count(k) Then
  2018.                 Array.Clear(MyHisto(k).Power_dBmHisto, 0, MyHisto(k).Power_dBmHisto.Length)
  2019.                 Array.Clear(MyHisto(k).SNR_dBHisto, 0, MyHisto(k).SNR_dBHisto.Length)
  2020.                 Array.Clear(MyHisto(k).CORangePercentHisto, 0, MyHisto(k).CORangePercentHisto.Length)
  2021.                 Array.Clear(MyHisto(k).BandwidthPercentRangeHisto, 0, MyHisto(k).BandwidthPercentRangeHisto.Length)
  2022.                 Array.Clear(MyHisto(k).BurstOn_dBmsHisto, 0, MyHisto(k).BurstOn_dBmsHisto.Length)
  2023.                 Array.Clear(MyHisto(k).BurstOff_dBmsHisto, 0, MyHisto(k).BurstOff_dBmsHisto.Length)
  2024.                 MyChannels.Count(k) = 0
  2025.             End If
  2026.         Next
  2027.     End Sub
  2028.  
  2029.     Private Sub ResetBox(ByRef Box As udtLocationBox)
  2030.         Box.AltMax = -100
  2031.         Box.AltMin = 10000
  2032.         Box.LatMax = -90
  2033.         Box.LatMin = 90
  2034.         Box.LonMax = -180
  2035.         Box.LonMin = 180
  2036.     End Sub
  2037.  
  2038.     Private Sub LogError(errorMessage As String)
  2039.         RaiseEvent ErrorReport(errorMessage)
  2040.         ErrorReportToStdOutput(errorMessage)
  2041.         If Not isHidden Then
  2042.             MsgBox(errorMessage, MsgBoxStyle.Exclamation, Me.Text)
  2043.         End If
  2044.     End Sub
  2045.  
  2046. End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement