
Imports System.IO
Imports System.Text
Imports System.Windows.Forms
Imports System.Drawing
Public Class frmExport

    Inherits System.Windows.Forms.Form
    Dim FolderLocation As String
    Dim bibliDs As New DataSet()
    Dim DBcon As New Connection
    Dim longBibliDsRowIteration As Long
    Dim strFvalues As String
    Dim strIndicator As String
    Dim strSbfld As String
    Dim sbfldCount As Long
    Dim strStartingPosOfPrevTag As String
    Dim strDirStructure As String 'to get directory structure(directory of all tags)
    Dim strLeader As String
    Dim strSingleRecord As String
    Dim FinalRecord As String
    Dim prevFileLen As Long
    Dim LongIter As Long = 1
    Dim Library_Name As String
    Dim Lib_CD As String
    Dim recCounter As Long
    Dim GetMaxID_DS As New DataSet
    Friend WithEvents BackgroundWorker1 As System.ComponentModel.BackgroundWorker
    Friend WithEvents sbsearch As System.Windows.Forms.StatusBar
    Friend WithEvents pnldatabase As System.Windows.Forms.StatusBarPanel
    Friend WithEvents PMAX As System.Windows.Forms.StatusBarPanel
    Friend WithEvents pnlcount As System.Windows.Forms.StatusBarPanel
    Dim RecordCount As Long = 0
#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents SaveMARCFileDialog As System.Windows.Forms.SaveFileDialog
    Friend WithEvents gpbExport As System.Windows.Forms.GroupBox
    Friend WithEvents btnBrowse As System.Windows.Forms.Button
    Friend WithEvents btnExport As System.Windows.Forms.Button
    Friend WithEvents txtEndRecNo As System.Windows.Forms.TextBox
    Friend WithEvents txtstrtRecNo As System.Windows.Forms.TextBox
    Friend WithEvents lblEndRecNo As System.Windows.Forms.Label
    Friend WithEvents lblStrtRecNo As System.Windows.Forms.Label
    Friend WithEvents txtMARCfile As System.Windows.Forms.TextBox
    Friend WithEvents lblMarcfile As System.Windows.Forms.Label
    Friend WithEvents btnExit As System.Windows.Forms.Button
    Friend WithEvents tmrProcRec As System.Windows.Forms.Timer
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container
        Me.SaveMARCFileDialog = New System.Windows.Forms.SaveFileDialog
        Me.gpbExport = New System.Windows.Forms.GroupBox
        Me.lblEndRecNo = New System.Windows.Forms.Label
        Me.lblStrtRecNo = New System.Windows.Forms.Label
        Me.lblMarcfile = New System.Windows.Forms.Label
        Me.btnBrowse = New System.Windows.Forms.Button
        Me.btnExport = New System.Windows.Forms.Button
        Me.txtEndRecNo = New System.Windows.Forms.TextBox
        Me.txtstrtRecNo = New System.Windows.Forms.TextBox
        Me.txtMARCfile = New System.Windows.Forms.TextBox
        Me.btnExit = New System.Windows.Forms.Button
        Me.tmrProcRec = New System.Windows.Forms.Timer(Me.components)
        Me.BackgroundWorker1 = New System.ComponentModel.BackgroundWorker
        Me.sbsearch = New System.Windows.Forms.StatusBar
        Me.pnldatabase = New System.Windows.Forms.StatusBarPanel
        Me.PMAX = New System.Windows.Forms.StatusBarPanel
        Me.pnlcount = New System.Windows.Forms.StatusBarPanel
        Me.gpbExport.SuspendLayout()
        CType(Me.pnldatabase, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.PMAX, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.pnlcount, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        '
        'SaveMARCFileDialog
        '
        Me.SaveMARCFileDialog.FileName = "doc1"
        Me.SaveMARCFileDialog.Filter = "All Files |*.*|Text Files *.txt|*.txt"
        '
        'gpbExport
        '
        Me.gpbExport.Controls.Add(Me.lblEndRecNo)
        Me.gpbExport.Controls.Add(Me.lblStrtRecNo)
        Me.gpbExport.Controls.Add(Me.lblMarcfile)
        Me.gpbExport.Controls.Add(Me.btnBrowse)
        Me.gpbExport.Controls.Add(Me.btnExport)
        Me.gpbExport.Controls.Add(Me.txtEndRecNo)
        Me.gpbExport.Controls.Add(Me.txtstrtRecNo)
        Me.gpbExport.Controls.Add(Me.txtMARCfile)
        Me.gpbExport.Controls.Add(Me.btnExit)
        Me.gpbExport.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        Me.gpbExport.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.gpbExport.ForeColor = System.Drawing.SystemColors.WindowText
        Me.gpbExport.Location = New System.Drawing.Point(5, 12)
        Me.gpbExport.Name = "gpbExport"
        Me.gpbExport.Size = New System.Drawing.Size(619, 144)
        Me.gpbExport.TabIndex = 0
        Me.gpbExport.TabStop = False
        Me.gpbExport.Text = "Range  of  Records"
        '
        'lblEndRecNo
        '
        Me.lblEndRecNo.BackColor = System.Drawing.Color.Transparent
        Me.lblEndRecNo.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lblEndRecNo.ForeColor = System.Drawing.SystemColors.WindowText
        Me.lblEndRecNo.Location = New System.Drawing.Point(34, 78)
        Me.lblEndRecNo.Name = "lblEndRecNo"
        Me.lblEndRecNo.Size = New System.Drawing.Size(138, 19)
        Me.lblEndRecNo.TabIndex = 39
        Me.lblEndRecNo.Text = "Ending  Record  No"
        Me.lblEndRecNo.TextAlign = System.Drawing.ContentAlignment.MiddleRight
        '
        'lblStrtRecNo
        '
        Me.lblStrtRecNo.BackColor = System.Drawing.Color.Transparent
        Me.lblStrtRecNo.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lblStrtRecNo.ForeColor = System.Drawing.SystemColors.WindowText
        Me.lblStrtRecNo.Location = New System.Drawing.Point(34, 53)
        Me.lblStrtRecNo.Name = "lblStrtRecNo"
        Me.lblStrtRecNo.Size = New System.Drawing.Size(138, 19)
        Me.lblStrtRecNo.TabIndex = 38
        Me.lblStrtRecNo.Text = "Starting  Record  No"
        Me.lblStrtRecNo.TextAlign = System.Drawing.ContentAlignment.MiddleRight
        '
        'lblMarcfile
        '
        Me.lblMarcfile.BackColor = System.Drawing.Color.Transparent
        Me.lblMarcfile.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lblMarcfile.ForeColor = System.Drawing.SystemColors.WindowText
        Me.lblMarcfile.Location = New System.Drawing.Point(13, 28)
        Me.lblMarcfile.Name = "lblMarcfile"
        Me.lblMarcfile.Size = New System.Drawing.Size(159, 18)
        Me.lblMarcfile.TabIndex = 36
        Me.lblMarcfile.Text = "Location of  MARC  File"
        Me.lblMarcfile.TextAlign = System.Drawing.ContentAlignment.MiddleRight
        '
        'btnBrowse
        '
        Me.btnBrowse.BackColor = System.Drawing.Color.FromArgb(CType(CType(185, Byte), Integer), CType(CType(209, Byte), Integer), CType(CType(240, Byte), Integer))
        Me.btnBrowse.FlatAppearance.BorderSize = 0
        Me.btnBrowse.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btnBrowse.ForeColor = System.Drawing.SystemColors.ControlText
        Me.btnBrowse.Location = New System.Drawing.Point(455, 23)
        Me.btnBrowse.Name = "btnBrowse"
        Me.btnBrowse.Size = New System.Drawing.Size(80, 30)
        Me.btnBrowse.TabIndex = 1
        Me.btnBrowse.Text = "Browse"
        Me.btnBrowse.UseVisualStyleBackColor = True
        '
        'btnExport
        '
        Me.btnExport.BackColor = System.Drawing.Color.FromArgb(CType(CType(185, Byte), Integer), CType(CType(209, Byte), Integer), CType(CType(240, Byte), Integer))
        Me.btnExport.FlatAppearance.BorderSize = 0
        Me.btnExport.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btnExport.ForeColor = System.Drawing.SystemColors.ControlText
        Me.btnExport.Location = New System.Drawing.Point(174, 105)
        Me.btnExport.Name = "btnExport"
        Me.btnExport.Size = New System.Drawing.Size(80, 30)
        Me.btnExport.TabIndex = 4
        Me.btnExport.Text = "Export"
        Me.btnExport.UseVisualStyleBackColor = True
        '
        'txtEndRecNo
        '
        Me.txtEndRecNo.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
        Me.txtEndRecNo.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.txtEndRecNo.ForeColor = System.Drawing.SystemColors.WindowText
        Me.txtEndRecNo.Location = New System.Drawing.Point(176, 78)
        Me.txtEndRecNo.Name = "txtEndRecNo"
        Me.txtEndRecNo.Size = New System.Drawing.Size(96, 21)
        Me.txtEndRecNo.TabIndex = 3
        '
        'txtstrtRecNo
        '
        Me.txtstrtRecNo.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
        Me.txtstrtRecNo.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.txtstrtRecNo.ForeColor = System.Drawing.SystemColors.WindowText
        Me.txtstrtRecNo.Location = New System.Drawing.Point(176, 52)
        Me.txtstrtRecNo.Name = "txtstrtRecNo"
        Me.txtstrtRecNo.Size = New System.Drawing.Size(96, 21)
        Me.txtstrtRecNo.TabIndex = 2
        '
        'txtMARCfile
        '
        Me.txtMARCfile.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
        Me.txtMARCfile.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.txtMARCfile.ForeColor = System.Drawing.SystemColors.WindowText
        Me.txtMARCfile.Location = New System.Drawing.Point(176, 26)
        Me.txtMARCfile.Name = "txtMARCfile"
        Me.txtMARCfile.Size = New System.Drawing.Size(272, 21)
        Me.txtMARCfile.TabIndex = 0
        Me.txtMARCfile.TabStop = False
        '
        'btnExit
        '
        Me.btnExit.BackColor = System.Drawing.Color.FromArgb(CType(CType(185, Byte), Integer), CType(CType(209, Byte), Integer), CType(CType(240, Byte), Integer))
        Me.btnExit.FlatAppearance.BorderSize = 0
        Me.btnExit.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btnExit.ForeColor = System.Drawing.SystemColors.ControlText
        Me.btnExit.Location = New System.Drawing.Point(254, 105)
        Me.btnExit.Name = "btnExit"
        Me.btnExit.Size = New System.Drawing.Size(80, 30)
        Me.btnExit.TabIndex = 5
        Me.btnExit.Text = "Close"
        Me.btnExit.UseVisualStyleBackColor = True
        '
        'tmrProcRec
        '
        '
        'sbsearch
        '
        Me.sbsearch.Font = New System.Drawing.Font("Arial", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.sbsearch.Location = New System.Drawing.Point(0, 163)
        Me.sbsearch.Name = "sbsearch"
        Me.sbsearch.Panels.AddRange(New System.Windows.Forms.StatusBarPanel() {Me.pnldatabase, Me.PMAX, Me.pnlcount})
        Me.sbsearch.ShowPanels = True
        Me.sbsearch.Size = New System.Drawing.Size(636, 24)
        Me.sbsearch.TabIndex = 22
        '
        'pnldatabase
        '
        Me.pnldatabase.Name = "pnldatabase"
        Me.pnldatabase.Text = "Total Records"
        Me.pnldatabase.Width = 90
        '
        'PMAX
        '
        Me.PMAX.Name = "PMAX"
        Me.PMAX.Width = 75
        '
        'pnlcount
        '
        Me.pnlcount.Name = "pnlcount"
        Me.pnlcount.Text = "Exported:"
        Me.pnlcount.Width = 250
        '
        'frmExport
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(6, 14)
        Me.BackColor = System.Drawing.Color.FromArgb(CType(CType(185, Byte), Integer), CType(CType(209, Byte), Integer), CType(CType(240, Byte), Integer))
        Me.ClientSize = New System.Drawing.Size(636, 187)
        Me.Controls.Add(Me.sbsearch)
        Me.Controls.Add(Me.gpbExport)
        Me.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
        Me.Name = "frmExport"
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.Text = "MARC Data(Export)"
        Me.gpbExport.ResumeLayout(False)
        Me.gpbExport.PerformLayout()
        CType(Me.pnldatabase, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.PMAX, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.pnlcount, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)

    End Sub

#End Region


    Private Function addFvaluesTogather()

        Dim lenOfTag As Long
        Dim lenOfPrevFvalues As Long
        Dim lenOfSbflds As Long
        Dim lenOfPrevTag As Long
        Dim RecID As Long
        Dim LatestLeader As String



        'create a dataset that will be used to fill data in a file
        Dim i As Integer
        FolderLocation = Application.StartupPath & "\Data.csv"
        'Dim GetRecordDS As New DataSet
        'GetRecordDS.Tables.Clear()
        Dim str As String = "select RecID,TagSrNo,Tag,Ind,SbFldSrNo,SbFld,FValue FROM " & FolderLocation & " where RecID between " & txtstrtRecNo.Text & " and " & txtEndRecNo.Text & " "
        bibliDs = DBcon.CreateDS(str)
        'DgviewCSV.DataSource = bibliDs.Tables(0)
        'Iterate through dataset's all row to get values 
        For longBibliDsRowIteration = 0 To bibliDs.Tables(0).Rows.Count - 1

            'chek if next record in reached or not
            If bibliDs.Tables(0).Rows(longBibliDsRowIteration).IsNull("Tag") = False Then
                'If CStr(bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("Tag")).Length = 1 Then
                '    bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("Tag") = "00" & CStr(bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("Tag"))
                'ElseIf CStr(bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("Tag")).Length = 2 Then
                '    bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("Tag") = "0" & bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("Tag")
                'Else
                '    bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("Tag") = bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("Tag")
                'End If

                If bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("Tag") = "000" Then

                    strLeader = bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("Fvalue")
                    ''messagebox.show("Leader:-" & strLeader)
                    strFvalues = ""

                Else
                    If bibliDs.Tables(0).Rows(longBibliDsRowIteration).IsNull("sbfld") = True Then
                        bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("sbfld") = ""
                    End If
                    If bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("sbfld") = "" Then

                        'if there is no sub field we dont have to take indicator and sub field value 
                        strFvalues = strFvalues & bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("fvalue") & "" 'Tag delimiter

                        lenOfTag = Len(strFvalues) - lenOfPrevFvalues
                        'Dim Tag As String = bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("tag")

                        ''messagebox.show("Length of tag(0 sbfld)" & lenOfTag)
                        'messagebox.show("Length of previous tag " & lenOfPrevTag)
                        ''messagebox.show("Tag's Fvalue " & strFvalues.Substring(lenOfPrevFvalues, lenOfTag))
                        GetDirectory(bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("tag"), lenOfTag, lenOfPrevTag)
                        lenOfPrevFvalues = Len(strFvalues)
                        lenOfPrevTag = lenOfTag 'we have to remember tag's length coz when processing next tag we have to consider prev tag length

                    Else 'sub fields are present 

                        Do

                            If longBibliDsRowIteration + 1 = bibliDs.Tables(0).Rows.Count Then

                                If bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("tag") = bibliDs.Tables(0).Rows(longBibliDsRowIteration - 1).Item("tag") And bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("tagsrno") = bibliDs.Tables(0).Rows(longBibliDsRowIteration - 1).Item("tagsrno") Then

                                    ''messagebox.show("end of record " & bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("recid"))
                                    strSbfld = bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("sbfld")

                                    strFvalues = strFvalues & strIndicator & "" & strSbfld & bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("fvalue") & ""  'tag delimiter

                                    lenOfSbflds = lenOfSbflds + Len(strFvalues) - lenOfPrevFvalues
                                    lenOfTag = lenOfSbflds
                                    GetDirectory(bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("tag"), lenOfTag, lenOfPrevTag)
                                    ''messagebox.show(strFvalues.Substring(Len(strFvalues) - lenOfTag, lenOfTag))
                                    lenOfPrevFvalues = Len(strFvalues)

                                    RecID = bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("RecID")

                                    'Create Function For Add TAG 852

                                    strSingleRecord = strLeader & strDirStructure & "" & strFvalues & "" 'record delimiter 
                                    'create leader
                                    'create record Length

                                    LatestLeader = CreateLeader()



                                    strFvalues = strFvalues & "" 'record delimiter 

                                    FinalRecord = LatestLeader & strDirStructure & "" & strFvalues '& "" 'record delimiter 
                                    RecordCount += 1
                                    pnlcount.Text = RecordCount - 1 & " Records are imported"
                                    'MsgBox(Len(FinalRecord))
                                    FilePut(1, FinalRecord)

                                    Exit For

                                Else

                                    If bibliDs.Tables(0).Rows(longBibliDsRowIteration).IsNull("ind") = False Then
                                        strIndicator = bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("ind")
                                    Else
                                        strIndicator = ""
                                    End If

                                    'messagebox.show("Indicator:- " & strIndicator)
                                    If strIndicator = "" Then ' indicators are undefined
                                        strIndicator = "  "
                                        'ElseIf strIndicator.Length = 1 Then
                                        '    strIndicator = strIndicator & " "
                                    End If
                                    strSbfld = bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("sbfld")
                                    strFvalues = strFvalues & strIndicator & "" & strSbfld & bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("fvalue") & "" 'tag delimiter 
                                    'lenOfTag = Len(bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("fvalue"))
                                    lenOfTag = Len(strFvalues) - lenOfPrevFvalues
                                    GetDirectory(bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("tag"), lenOfTag, lenOfPrevTag)
                                    ' ''strSingleRecord = strLeader & strDirStructure & "" & strFvalues & "" 'record delimiter 
                                    ' ''FilePut(1, strSingleRecord)

                                    'Change Here
                                    RecID = bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("RecID")

                                    'Create Function For Add TAG 852

                                    strSingleRecord = strLeader & strDirStructure & "" & strFvalues & "" 'record delimiter 
                                    'create leader
                                    'create record Length

                                    LatestLeader = CreateLeader()



                                    strFvalues = strFvalues & "" 'record delimiter 

                                    FinalRecord = LatestLeader & strDirStructure & "" & strFvalues '& "" 'record delimiter 
                                    RecordCount += 1
                                    pnlcount.Text = RecordCount - 1 & " Records are imported"
                                    'MsgBox(Len(FinalRecord))
                                    FilePut(1, FinalRecord)
                                    Exit For

                                End If

                            End If
                            'cheking for if tag contain more than one subfield
                            'if tags of sequential row are not same and sbfldcount=0 it means tag has only one sub field
                            'if tags of sequential row are not same and sbfldcount !=0 then tag has more than 1 subfield 
                            'suppose 3 sub fields than the counter is at 3rd subfield in biblids and next row will have diff tag
                            If bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("tag") <> bibliDs.Tables(0).Rows(longBibliDsRowIteration + 1).Item("tag") Then

                                If sbfldCount = 0 Then 'for tag having only one subfield(indicator+sbfld delimiter+fvalue)
                                    If bibliDs.Tables(0).Rows(longBibliDsRowIteration).IsNull("ind") = False Then
                                        strIndicator = bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("ind")
                                    Else
                                        strIndicator = ""
                                    End If


                                    'messagebox.show("Indicator:- " & strIndicator)

                                    If strIndicator = "" Then ' indicators are undefined
                                        strIndicator = "  "
                                        'ElseIf strIndicator.Length = 1 Then
                                        '    strIndicator = strIndicator & " "
                                    End If

                                    strSbfld = bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("sbfld")
                                    ''messagebox.show("fvalue " & Len(bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("fvalue")))
                                    strFvalues = strFvalues & strIndicator & "" & strSbfld & bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("fvalue") & ""  'Tag delimiter first "" is sbfld delimiter

                                    lenOfTag = Len(strFvalues) - lenOfPrevFvalues

                                    ''messagebox.show("Length of Tag(one sbfld):-" & lenOfTag)
                                    ' messagebox.show("length of prev tag " & lenOfPrevTag)
                                    ''messagebox.show("tag'fvalue is " & strFvalues.Substring(lenOfPrevFvalues, lenOfTag))
                                    GetDirectory(bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("tag"), lenOfTag, lenOfPrevTag)
                                    lenOfPrevFvalues = Len(strFvalues)
                                    lenOfPrevTag = lenOfTag
                                    sbfldCount = 0
                                    Exit Do

                                Else 'more than one sub field (sbfld delimiter + fvalue+tag delimiter)

                                    strSbfld = bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("sbfld")
                                    strFvalues = strFvalues & "" & strSbfld & bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("fvalue") & "" 'Tag delimiter, first "" is sbfld delimiter 

                                    lenOfSbflds = lenOfSbflds + Len(strFvalues) - lenOfPrevFvalues
                                    '' messagebox.show("length of sbflds at end " & lenOfSbflds)
                                    lenOfTag = lenOfSbflds
                                    'messagebox.show("length of prev tag " & lenOfPrevTag)
                                    'messagebox.show("tag'fvalue is:-" & strFvalues.Substring(lenOfPrevFvalues - lenOfSbflds + Len(bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("fvalue")) + 3, lenOfSbflds))
                                    ''messagebox.show("tag'fvalue is:-" & strFvalues.Substring(Len(strFvalues) - lenOfTag, lenOfSbflds))

                                    'messagebox.show("length of tag(more than one sbfld) :-" & lenOfTag)

                                    lenOfPrevFvalues = Len(strFvalues)
                                    GetDirectory(bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("tag"), lenOfTag, lenOfPrevTag)
                                    lenOfPrevTag = lenOfTag
                                    sbfldCount = 0
                                    Exit Do
                                End If

                            Else
                                'if tags are equal and sbfldcount=0 then first subfield is being processed
                                'add indicator+sbfld delimiter+sbfld fvalue 

                                If sbfldCount = 0 Then
                                    If bibliDs.Tables(0).Rows(longBibliDsRowIteration).IsNull("ind") = False Then
                                        strIndicator = bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("ind")
                                    Else
                                        strIndicator = ""
                                    End If

                                    If strIndicator = "" Then
                                        strIndicator = "  "
                                    End If

                                    strSbfld = bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("sbfld")

                                    If bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("tagsrno") = bibliDs.Tables(0).Rows(longBibliDsRowIteration + 1).Item("tagsrno") Then

                                        strFvalues = strFvalues & strIndicator & "" & strSbfld & bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("fvalue")

                                        lenOfSbflds = Len(strFvalues) - lenOfPrevFvalues
                                        '' messagebox.show("length of subfield " & lenOfSbflds)

                                        lenOfPrevFvalues = Len(strFvalues)
                                        longBibliDsRowIteration += 1
                                        sbfldCount += 1

                                    Else

                                        strFvalues = strFvalues & strIndicator & "" & strSbfld & bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("fvalue") & "" 'tag delimiter

                                        lenOfTag = Len(strFvalues) - lenOfPrevFvalues
                                        '' messagebox.show("length of subfield " & lenOfSbflds)
                                        '' messagebox.show("tag'fvalue is:-" & strFvalues.Substring(lenOfPrevFvalues, lenOfTag))

                                        lenOfPrevFvalues = Len(strFvalues)
                                        GetDirectory(bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("tag"), lenOfTag, lenOfPrevTag)
                                        longBibliDsRowIteration += 1
                                        lenOfPrevTag = lenOfTag
                                        sbfldCount = 0

                                    End If

                                Else 'here next sub fields of same tag will be processed
                                    'at this time we dont need to add indicator but we have to add sub field delimiter 
                                    If bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("tagsrno") = bibliDs.Tables(0).Rows(longBibliDsRowIteration + 1).Item("tagsrno") Then

                                        strSbfld = bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("sbfld")
                                        strFvalues = strFvalues & "" & strSbfld & bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("fvalue") 'here "" is subfield delimiter

                                        lenOfSbflds = lenOfSbflds + Len(strFvalues) - lenOfPrevFvalues
                                        '' messagebox.show("length of sbfld:-" & lenOfSbflds)
                                        lenOfPrevFvalues = Len(strFvalues)
                                        longBibliDsRowIteration += 1
                                        sbfldCount += 1
                                    Else

                                        strSbfld = bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("sbfld")
                                        'here we have to add tag delimiter just check this 
                                        strFvalues = strFvalues & "" & strSbfld & bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("fvalue") & "" 'here "" is subfield delimiter

                                        lenOfTag = lenOfSbflds + Len(strFvalues) - lenOfPrevFvalues
                                        ''messagebox.show("length of tag:-" & lenOfTag)
                                        lenOfPrevFvalues = Len(strFvalues)

                                        GetDirectory(bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("tag"), lenOfTag, lenOfPrevTag)
                                        lenOfPrevTag = lenOfTag
                                        sbfldCount = 0
                                        Exit Do
                                    End If

                                End If

                            End If

                        Loop

                        If bibliDs.Tables(0).Rows(longBibliDsRowIteration + 1).Item("tag") = "000" Then

                            'here we have to check whether next record is reached or not if yes we have add a record delimiter at the end of string
                            '' messagebox.show("end of record " & bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("recid"))

                            ''RecID = bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("RecID")

                            ' ''Create Function For Add TAG 852
                            ''AddTag852Value(RecID, strDirStructure, strFvalues)


                            ''strFvalues = strFvalues & "" 'record delimiter 
                            ' ''messagebox.show(Asc(strFvalues.Substring(Len(strFvalues) - 1, 1)))
                            ' ''messagebox.show(strFvalues)
                            ''strSingleRecord = strLeader & strDirStructure & "" & strFvalues
                            ' ''messagebox.show(strSingleRecord)
                            ''FilePut(1, strSingleRecord)

                            RecID = bibliDs.Tables(0).Rows(longBibliDsRowIteration).Item("RecID")

                            'Create Function For Add TAG 852

                            strSingleRecord = strLeader & strDirStructure & "" & strFvalues & "" 'record delimiter 
                            'create leader
                            'create record Length

                            LatestLeader = CreateLeader()



                            strFvalues = strFvalues & "" 'record delimiter 

                            FinalRecord = LatestLeader & strDirStructure & "" & strFvalues '& "" 'record delimiter 

                            RecordCount += 1
                            pnlcount.Text = RecordCount - 1 & " Records are imported"
                            'lblProcessingRecNo.Text = RecordCount
                            'MsgBox(Len(FinalRecord))
                            FilePut(1, FinalRecord)

                            Seek(1, prevFileLen + Len(strSingleRecord) + 1)
                            prevFileLen = prevFileLen + Len(strSingleRecord)
                            ''messagebox.show("file length :-" & prevFileLen)
                            strSingleRecord = ""
                            strFvalues = ""
                            lenOfTag = 0
                            lenOfPrevTag = 0
                            strDirStructure = ""
                            strStartingPosOfPrevTag = ""
                            lenOfPrevFvalues = 0
                            lenOfSbflds = 0

                        End If

                    End If

                End If
            End If

            ''   messagebox.show(strFvalues)
        Next
        FileClose(1)
        pnlcount.Text = "Total Exported Records : " & Val(txtEndRecNo.Text)
        'GetMaxRec()
        MsgBox("Record has been Exported", MsgBoxStyle.Information, "SOUL 2.0")
        'btnExport.UseWaitCursor = False
        'btnExport.Cursor = Cursors.Default

        Me.Enabled = True
        RecordCount = 0

    End Function
    'Create Leader 
#Region "Create New Leader Fileld Here"
    Private Function CreateLeader() As String
        Dim RecordLength As Long
        Dim RecLenght As String
        If strLeader Is Nothing Then
            Exit Function
        End If



        RecordLength = Len(strSingleRecord)
        If RecordLength < 10 Then
            RecLenght = "0000" & CStr(RecordLength)
        ElseIf RecordLength < 100 Then
            RecLenght = "000" & CStr(RecordLength)
        ElseIf RecordLength < 1000 Then
            RecLenght = "00" & CStr(RecordLength)
        ElseIf RecordLength < 10000 Then
            RecLenght = "0" & CStr(RecordLength)
        Else
            RecLenght = CStr(RecordLength)
        End If

        'create Directory length in leader
        Dim BaseAddressVal As Long
        Dim StrBaseAddress As String
        BaseAddressVal = Len(strLeader) + Len(strDirStructure)
        If BaseAddressVal < 10 Then
            StrBaseAddress = "0000" & CStr(BaseAddressVal)
        ElseIf BaseAddressVal < 100 Then
            StrBaseAddress = "000" & CStr(BaseAddressVal)
        ElseIf BaseAddressVal < 1000 Then
            StrBaseAddress = "00" & CStr(BaseAddressVal)
        ElseIf BaseAddressVal < 10000 Then
            StrBaseAddress = "0" & CStr(BaseAddressVal)
        Else
            StrBaseAddress = CStr(BaseAddressVal)
        End If


        'Add Record length and Base address to leader
        Dim OldRecordLength As String
        OldRecordLength = strLeader.Substring(0, 5)
        Dim OldBaseAddress As String
        OldBaseAddress = strLeader.Substring(12, 5)
        Dim CoLeader As String = RecLenght & strLeader.Remove(0, 5)

        'Dim CopyLeader As String = strLeader.Replace(OldRecordLength, RecLenght)
        Dim FinalLeader As String = CoLeader.Replace(OldBaseAddress, StrBaseAddress)
        LongIter = LongIter + 1
        'pnlcount.Text = LongIter - 1 & " Records are imported"
        Return FinalLeader


    End Function
#End Region


    Private Function GetDirectory(ByVal tag As String, ByVal currentTagLen As Long, ByVal previousTagLen As Long)
        'this function will create the directory structure for a record 

        Dim strSingleDir As String 'to get  directory(tag+length+starting position)
        Dim strStartingPosOfCurrentTag As String 'to get starting position of current tag
        Dim strlenOfCurrentTag As String 'to get length of currernt tag in string
        If tag.Length = 1 Then
            tag = "00" & tag
        ElseIf tag.Length = 2 Then
            tag = "0" & tag
        End If

        If currentTagLen < 10 Then
            strlenOfCurrentTag = "000" & currentTagLen
        ElseIf currentTagLen < 100 Then
            strlenOfCurrentTag = "00" & currentTagLen
        Else
            strlenOfCurrentTag = "0" & currentTagLen
        End If

        'here we have to remember starting position and length of previous tag to get starting position of current tag
        If previousTagLen = 0 Then
            strStartingPosOfCurrentTag = "0000" & previousTagLen
        ElseIf previousTagLen + CType(strStartingPosOfPrevTag, Long) < 10 Then
            strStartingPosOfCurrentTag = "0000" & previousTagLen + CType(strStartingPosOfPrevTag, Long)
        ElseIf previousTagLen + CType(strStartingPosOfPrevTag, Long) < 100 Then
            strStartingPosOfCurrentTag = "000" & previousTagLen + CType(strStartingPosOfPrevTag, Long)
        ElseIf previousTagLen + CType(strStartingPosOfPrevTag, Long) < 1000 Then
            strStartingPosOfCurrentTag = "00" & previousTagLen + CType(strStartingPosOfPrevTag, Long)
        Else
            strStartingPosOfCurrentTag = "0" & previousTagLen + CType(strStartingPosOfPrevTag, Long)
        End If

        'starting position is in string so we need to convert it in long to get starting position of current tag
        'add tag,current tag length(as string) and starting position of current tag to get directory of current tag
        strSingleDir = tag & strlenOfCurrentTag & strStartingPosOfCurrentTag
        'messagebox.show("startin pos of tag " & strStartingPosOfCurrentTag)
        '' messagebox.show(strSingleDir)
        strDirStructure = strDirStructure & strSingleDir
        'make current tag's starting position previous tag's starting position 
        'coz current tag has been processed just and this will be used as previous tag when next tag comes
        strStartingPosOfPrevTag = strStartingPosOfCurrentTag
        'messagebox.show(strDirStructure)

    End Function
    'messagebox.show("record delimiter-" & Asc("")) '29
    'messagebox.show("Tag delimiter-" & Asc("")) '30
    'messagebox.show("subfield delimiter-" & Asc("")) '31

    Private Sub SaveMARCFileDialog_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles SaveMARCFileDialog.FileOk
        txtMARCfile.Text = SaveMARCFileDialog.FileName
    End Sub


    Private Sub btnBrowse_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
        SaveMARCFileDialog.ShowDialog()
        txtstrtRecNo.Enabled = True
        txtEndRecNo.Enabled = True
        txtstrtRecNo.Clear()
        txtEndRecNo.Clear()
       
        btnExport.Enabled = True
        RecordCount = 0
    End Sub

   

    Private Sub Export() 'Handles BackgroundWorker1.DoWork
        Dim Get_Lib_CD_DS As DataSet
        Me.BackgroundWorker1.WorkerSupportsCancellation = False
        txtstrtRecNo.Enabled = False
        txtEndRecNo.Enabled = False
        If txtMARCfile.Text = "" Then
            MessageBox.Show("Please,Select a File")
            btnBrowse.Focus()
            Exit Sub
        End If


        'validating records entered by user
        If IsNumeric(txtstrtRecNo.Text) And IsNumeric(txtEndRecNo.Text) Then
            'checking whether range entered by user is a valid range or not
            Dim ds As New DataSet()
            ds = DBcon.CreateDS("SELECT Max(RecID) FROM " & FolderLocation & "")
            ' messagebox.show(ds.Tables(0).Rows(0).Item(0))

            If txtEndRecNo.Text > ds.Tables(0).Rows(0).Item(0) Or txtstrtRecNo.Text > ds.Tables(0).Rows(0).Item(0) Then
                MessageBox.Show("Range is not valid,Ending or Starting No. may be quite large", "Export", MessageBoxButtons.OK, MessageBoxIcon.Error)
                txtEndRecNo.Text = ""
                txtstrtRecNo.Text = ""
                txtstrtRecNo.Focus()
                Return
            End If

            If Int(txtstrtRecNo.Text) > Int(txtEndRecNo.Text) Then
                MessageBox.Show("Please,Make sure that  Starting No is not greater than Ending No ", "Export", MessageBoxButtons.OK, MessageBoxIcon.Error)
                txtstrtRecNo.Clear()
                'txtEndRecNo.Clear()
                txtstrtRecNo.Focus()
                Exit Sub
            End If

        Else

            MessageBox.Show("Please,Enter Digits Only", "Export", MessageBoxButtons.OK, MessageBoxIcon.Error)
            If Not IsNumeric(txtstrtRecNo.Text) Then
                txtstrtRecNo.Clear()
                txtstrtRecNo.Focus()
            Else
                txtEndRecNo.Clear()
                txtEndRecNo.Focus()
            End If
            'txtstrtRecNo.Clear()
            'txtEndRecNo.Clear()
            'txtstrtRecNo.Focus()
            Exit Sub

        End If
        recCounter = txtstrtRecNo.Text

        tmrProcRec.Enabled = True

        'create a file to wtrite data in
        FileOpen(1, txtMARCfile.Text, OpenMode.Binary)

        'this function will reads row of a table one by one  and adds fvalues togather
        addFvaluesTogather()
        'messagebox.show(strFvalues)
        'messagebox.show("length of fvalues:-" & Len(strFvalues))
        'messagebox.show("Directory structure:-" & strDirStructure)
        'messagebox.show("length of directory structure:-" & Len(strDirStructure))
        'messagebox.show("record :- " & strSingleRecord)
        'messagebox.show("length of a record:-" & Len(strSingleRecord))
        ' Seek(1, 1)

        'If ChkAcqProcessing.Checked = True Then

        'End If



    End Sub
    Private Sub GetMaxRec()
        FolderLocation = Application.StartupPath & "\Data.csv"
        Dim RecId As String
        Dim BibRecIDDS As New Data.DataSet
        Dim i As Integer
        'Get Max Record ID from File 
        Dim strgetRecid As String = "SELECT Max(RecId) FROM " & FolderLocation & ""
        BibRecIDDS = DBcon.CreateDS(strgetRecid)
        'Get Maximum Record id from File
        Try
            'check for record id value,  if null then assgn 1 as a record id otherwise add 1 in existing maximum record id value
            If BibRecIDDS.Tables(0).Rows(0).IsNull(0) = True Then
                RecId = 1
            Else
                RecId = BibRecIDDS.Tables(0).Rows(0).Item(0)
                'FileOpen(2, Application.StartupPath & "\Data.csv", OpenMode.Binary) 'bad record is come then it is set in "c:\BadRecord\record.txt
            End If
        Catch ex As Exception
            'MsgBox(ex.ToString)
            RecId = 0
        End Try
        PMAX.Text = RecId
    End Sub

    Private Sub btnExport_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click
        FolderLocation = Application.StartupPath & "\Data.csv"
        'btnExport.Enabled = False
        GetMaxRec()
        LongIter = 1
        'Following Function will Export Record
        Export()

        'Final()

    End Sub

    Private Sub btnExit_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
        Me.Close()
    End Sub


    Private Sub CloseIt()
        Me.Close()
    End Sub
    Private Sub frmExport_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        GetMaxRec()

        btnBrowse.Focus()
        tmrProcRec.Enabled = False




    End Sub

    Private Sub tmrProcRec_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrProcRec.Tick

        'If recCounter = GetMaxID_DS.Tables(0).Rows(0).Item("ID") Then
        '    lblTotalMNF.Text = txtEndRecNo.Text - txtstrtRecNo.Text + 1
        '    tmrProcRec.Enabled = False
        'End If
        'lblProcessingRecNo.Text = recCounter
        'recCounter += 1

    End Sub



    Private Sub lblProcessingRecNo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub txtEndRecNo_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtEndRecNo.TextChanged

    End Sub
End Class
