Option Explicit
Dim dev:dev = "local"
Dim outFile
Dim WaitTime:WaitTime = 15000 
Dim DataDirectory
Dim ExportDirectory
Dim PurpleEnvelopeProofReport,OfficeCopiesProofReport,CustomOfficeCopiesProof
Dim WshShell:Set WshShell = WScript.CreateObject("Wscript.Shell")
Dim oConn:Set oConn = WScript.CreateObject("ADODB.Connection")
Dim ConnectionString
Dim objFSO:Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim glob:set glob = CreateObject("Chilkat_9_5_0.Global")
Dim success:success = glob.UnlockBundle("KENTCM.CB1022025_RGzBPM5J655e")

	If (success <> 1) Then
    	WriteLine(glob.LastErrorText)
    	WScript.Quit
	End If
	
Dim objCSV:Set objCsv = CreateObject("Chilkat_9_5_0.Csv")
Dim WorkingDirectory:WorkingDirectory = Replace(WScript.ScriptFullName,WScript.ScriptName,"")
	Select Case dev
	Case "local" 
		DataDirectory = "C:\Share\TrackingDataImport\"
		ExportDirectory = "C:\Share\TrackingDataExport\"
		ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Engine Type=5;Data Source=F:\Development\Tracking_Kits\Data\webdata - Copy.mdb;"
		PurpleEnvelopeProofReport = "F:\Development\Tracking_Kits\Data\Proofs.rep"
		OfficeCopiesProofReport="F:\Development\Tracking_Kits\Data\Office-Copy-Proof.rep"
		CustomOfficeCopiesProof="F:\Development\Tracking_Kits\Data\Custom Office Copies Proof.rep"
		set outFile = objFSO.CreateTextFile("C:\Share\TrackingDataExport\temp.csv",True)
	Case true 
		DataDirectory = "C:\Share\TrackingDataImport\"
		ExportDirectory = "C:\Share\TrackingDataExport\"
		ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Engine Type=5;Data Source=C:\Git Repos\tracking_kits\Data\webdata - Copy.mdb;"
		PurpleEnvelopeProofReport = "C:\Git Repos\tracking_kits\Data\Proofs.rep"
		OfficeCopiesProofReport = "C:\Git Repos\tracking_kits\Data\Office-Copy-Proof.rep"
		CustomOfficeCopiesProof="F:\Development\Tracking_Kits\Data\Custom Office Copies Proof.rep"
		set outFile = objFSO.CreateTextFile("C:\Git Repos\tracking_kits\Data\TrackingDataExport\temp.csv",True)
	Case Else
		DataDirectory = "\\kci-syn-cl01\PC Transfer\TrackingDataImport"
		ExportDirectory = "\\kci-syn-cl01\PC Transfer\TrackingDataExport\"
		ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Engine Type=5;Data Source=C:\inetpub\Data\webdata - Copy.mdb;"
		PurpleEnvelopeProofReport ="C:\inetpub\tracking\Data\Proofs.rep"
		OfficeCopiesProofReport = "C:\inetpub\tracking\Data\Office-Copy-Proof.rep"
		CustomOfficeCopiesProof="C:\inetpub\tracking\Data\Custom Office Copies Proof.rep"
		set outFile = objFSO.CreateTextFile("\\kci-syn-cl01\PC Transfer\TrackingDataExport\temp.csv",True)
	End Select
	
'ToDo create a checkstatus function so I dont need four functions of create a case switch that responds to the status of jobs
	CreateCustomOfficeCopyJobsProofFiles
	If ThereAreCustomOfficeCopyJobsReady() Then
		CreateCustomOfficeCopyJobsInKjetFiles
		CreateCustomOfficeCopyJobsProofFiles
		
	End If
	
	
	Dim KitID:CheckForFiles:KitID = CheckForJobsToCass()
		If KitID > 0 Then
	    ExportMMCsv(KitID)
	    RunMailManager
	    ImportCass
	End If
	KitID = CheckStatusFor("Ready to Assign Labels"):If KitID > 0 Then:createTrackingInfoForKit(KitID):End If
	KitID = CheckStatusFor("Ready For Export"):If KitID > 0 Then:CreateExportForSnailWorks(KitID):End If 
	KitID = CheckStatusFor("Ready to Proof"):If KitID > 0 Then:CreateProofForJurisdiction(KitID):End If
	KitID = CheckStatusFor("Ready For Inkjet Export"):If KitID > 0 Then:ExportInkjetFile(KitID):End If
	
	if dev = False then
		CheckSnailWorksPurpleEnvelopeExport
		CheckSnailWorksTrakingKitExport 
	End if 
	WScript.Quit
	
Sub CreateCustomOfficeCopyJobsInKjetFiles
	If oConn.State = 0 Then:oConn.Open(ConnectionString):End If
		Dim JurisdictionRs,JobsRs,ContactRs,objInkjetCSV:set JobsRs = oConn.Execute("Select * From [CustomOfficeCopyJob] Where [Status] ='Ready';")
		Do While Not JobsRs.Eof  
		
				Set JurisdictionRs = oConn.Execute("SELECT * FROM Jurisdiction WHERE JCode ='" & JobsRs("Jcode").Value & "';")
				Set ContactRs = oConn.Execute("SELECT * FROM Contacts WHERE [JURISCODE] ='" & JobsRs("Jcode").Value & "';")
				Set objInkJetCSV = CreateObject("Chilkat_9_5_0.Csv")
				
				objInkjetCSV.HasColumnNames = 1
				objInkjetCSV.EnableQuotes = 1
				
				objInkjetCSV.SetColumnName 0,"Full Name"
				objInkjetCSV.SetColumnName 1,"Address 1"
				objInkjetCSV.SetColumnName 2,"Address 2"
				objInkjetCSV.SetColumnName 3,"Address 3"
				objInkjetCSV.SetColumnName 4,"Address 4"
				objInkjetCSV.SetColumnName 5,"IM barcode Characters"
				objInkjetCSV.SetColumnName 6,"Precinct"
				objInkjetCSV.SetColumnName 7,"Ballot ID"
				objInkjetCSV.SetColumnName 8,"Ballot Number"
				objInkjetCSV.SetColumnName 9,"Jurisdiction code"
				objInkjetCSV.SetColumnName 10,"Election Date"
				objInkJetCSV.SetColumnName 11,"Combined  Pct_Ballot Num"
				objInkJetCSV.SetColumnName 12,"Title"
				objInkJetCSV.SetColumnName 13,"G2 Full Name"
				objInkJetCSV.SetColumnName 14,"G2 Company"
				objInkJetCSV.SetColumnName 15,"G2 Alternate 1 Address"
				objInkJetCSV.SetColumnName 16,"G2 Delivery Address"
				objInkJetCSV.SetColumnName 17,"G2 City St ZIP+4"
				objInkJetCSV.SetColumnName 18,"G2 IM barcode Characters"
				objInkJetCSV.SetColumnName 19,"Matching Code"
		
		Dim Record
		For Record = 0 To  JobsRs("Amount").Value -1
			objInkJetCSV.SetCellByName Record,"Precinct",JobsRs("Precinct").Value
			objInkJetCSV.SetCellByName Record,"Ballot Number",JobsRs("StartingBallotNumber").Value + Record
			objInkjetCSV.SetCellByName Record,"Title",CleanNull(ContactRs("Title").Value)
			objInkJetCSV.SetCellByName Record,"G2 Full Name",JurisdictionRs("Name").Value
			objInkJetCSV.SetCellByName Record,"G2 Company",JurisdictionRs("Mailing_Address").Value
			objInkJetCSV.SetCellByName Record,"G2 Alternate 1 Address",JurisdictionRs("CSZ").Value
			objInkJetCSV.SetCellByName Record,"G2 Delivery Address",""
			objInkJetCSV.SetCellByName Record,"G2 City St ZIP+4",""
			objInkJetCSV.SetCellByName Record,"G2 IM barcode Characters",JurisdictionRs("IMB_Digits").Value
			
		
		Next
		objInkjetCSV.SaveFile(ExportDirectory & JurisdictionRs("Name").Value & "-" & JobsRs("Precinct").Value & ".csv" )
		Set objInkjetCSV = Nothing		
		Set JurisdictionRs = Nothing
		set ContactRs = Nothing
		oConn.Execute("Update [CustomOfficeCopyJob] Set [Status] ='Ready To Proof' where [ID] = " & JobsRs("ID").Value & ";")
		JobsRs.MoveNext
		Loop
		
	If JobsRs.State = 1 Then:JobsRs.Close
	If oConn.State = 1 Then:oConn.Close
	
End Sub
Sub CreateCustomOfficeCopyJobsProofFiles
	If oConn.State = 0 Then:oConn.Open(ConnectionString):End If
	Dim JobsRs:Set JobsRs = oConn.Execute("Select * From [CustomOfficeCopyJob] Where [Status] ='Ready To Proof';")
	If Not JobsRs.EOF Then
	Dim JurisdictionRs:Set JurisdictionRs = oConn.Execute("SELECT * FROM Jurisdiction WHERE JCode ='" & JobsRs("Jcode").Value & "';")
	Dim reportManager:set reportManager = CreateObject("ReportMan.ReportManX")
	With reportManager
			.Preview = False
			.ShowProgress = False
			.ShowPrintDialog = False
			.filename = CustomOfficeCopiesProof
			.SetDatabaseConnectionString "MORE_DATA",ConnectionString
			.SetParamValue "PBJCODE",JobsRs("Jcode")
			.SetParamValue "PBCSV",JurisdictionRs("Name").Value & "-" & JobsRs("Precinct").Value & ".csv"
			.SaveToPDF ExportDirectory & JurisdictionRs("Name").Value & "-" & JobsRs("Precinct").Value & ".pdf",1
	End With
	oConn.Execute("Update [CustomOfficeCopyJob] Set [Status] ='Done' where [ID] = " & JobsRs("ID").Value & ";")
	End If
	If JobsRs.State = 1 Then:JobsRs.Close
	If oConn.State = 1 Then:oConn.Close
	
End Sub
Function ThereAreCustomOfficeCopyJobsReady
	
	If oConn.State = 0 Then:oConn.Open(ConnectionString):End If
		Dim JobsRs:set JobsRs = oConn.Execute("Select [ID] From [CustomOfficeCopyJob] Where [Status] ='Ready';")
	 	If Not JobsRs.EOF  Then:ThereAreCustomOfficeCopyJobsReady = True:Else ThereAreCustomOfficeCopyJobsReady = False
	If JobsRs.State = 1 Then:JobsRs.Close
	If oConn.State = 1 Then:oConn.Close
End Function	
	
Sub CheckSnailWorksPurpleEnvelopeExport

Dim Sftp:set Sftp =  CreateObject("Chilkat_9_5_0.SFtp")
    Dim objFolder
    Dim success
    Set objFolder = objFSO.GetFolder("\\kci-syn-cl01\PC Transfer\TrackingDataExport\Export Purple Envelopes")
    
    	If objFolder.Files.Count > 0 Then
    		success = Sftp.Connect("sftp.snailworks.com",22)
    		success = Sftp.AuthenticatePw("KCIHotFolder2024FTPUser","Z!4WXLSQMM#f")
    		success = Sftp.InitializeSftp()
    		Dim file
    			For Each file In objFolder.Files
    				debug.WriteLine file.Path
    				Dim handle:handle = Sftp.OpenFile(file.Name,"writeOnly","createTruncate")
    				Sftp.UploadFile handle,file.Path
    				Sftp.CloseHandle handle
    				file.Delete
    			Next
    	End If 

End Sub

Sub CheckSnailWorksTrakingKitExport

Dim Sftp:set Sftp =  CreateObject("Chilkat_9_5_0.SFtp")
    Dim objFolder
    Dim success 
    Set objFolder = objFSO.GetFolder("\\kci-syn-cl01\PC Transfer\TrackingDataExport\Export Tracking Kits")
    
    	If objFolder.Files.Count > 0 Then
    		success = Sftp.Connect("sftp.snailworks.com",22)
    		success = Sftp.AuthenticatePw("KCI2024Type2FTPUser","Z!NXVRV5SH#f")
    		success = Sftp.InitializeSftp()
    		Dim file
    			For Each file In objFolder.Files
    				debug.WriteLine file.Path
    				Dim handle:handle = Sftp.OpenFile(file.Name,"writeOnly","createTruncate")
    				Sftp.UploadFile handle,file.Path
    				Sftp.CloseHandle handle
    				file.Delete
    			Next
    	End If 

End Sub
Function ExportInkjetFile(KitID)
	If oConn.State = 0 Then:oConn.Open(ConnectionString):End If 
		Dim KitRs:set KitRs = oConn.Execute("Select * From [Kit] Where [ID] =" &  KitID & ";")
	Dim KitLabelsRs: Set KitLabelsRs = oConn.Execute("SELECT * FROM ( " & _
    "SELECT IIf(Len([PRECINCT]) = 1, '0' & [PRECINCT] & Right([BALLOT_NUMBER],4), [PRECINCT] & Right([BALLOT_NUMBER],4)) AS SORT_ORDER, " & _
    "InkjetRecords.ID, InkjetRecords.KitID, InkjetRecords.VOTERID, InkjetRecords.LASTNAME, " & _
    "InkjetRecords.FIRSTNAME, InkjetRecords.MIDDLENAME, InkjetRecords.SUFFIX, InkjetRecords.PRECINCT, " & _
    "InkjetRecords.ADDRESS1, InkjetRecords.ADDRESS2, InkjetRecords.ADDRESS3, InkjetRecords.ADDRESS4, " & _
    "InkjetRecords.ADDRESS5, InkjetRecords.APPSENT, InkjetRecords.APPRETURNED, InkjetRecords.BALSENT, " & _
    "InkjetRecords.BALRETURNED, InkjetRecords.CountingBoard, InkjetRecords.UOCAVASTATUS, InkjetRecords.EMAILADDRESS, " & _
    "InkjetRecords.PHONENUMBER, InkjetRecords.BALLOT_NUMBER, InkjetRecords.CassADDRESS1, InkjetRecords.CassADDRESS2, " & _
    "InkjetRecords.CassADDRESS3, InkjetRecords.CassADDRESS4, InkjetRecords.CassADDRESS5, InkjetRecords.KitLabelID, " & _
    "KitLabels.ID, KitLabels.KitID, KitLabels.OutboundSerial, KitLabels.InBoundSerial, KitLabels.OutboundIMB, " & _
    "KitLabels.InBoundIMB, KitLabels.OutboundIMBDigits, KitLabels.InBoundIMBDigits, KitLabels.OutboundIMBPNG, " & _
    "KitLabels.INBOUNDIMBPNG, KitLabels.SetNumber " & _
    "FROM InkjetRecords " & _
    "LEFT JOIN [KitLabels] ON InkjetRecords.KitLabelID = KitLabels.ID " & _
    "WHERE InkjetRecords.KitID = " & KitID & ") AS [Data] " & _
    "ORDER BY Val(PRECINCT) DESC, PRECINCT DESC, " & _
    "Val(Right(BALLOT_NUMBER, 4)) DESC, Right(BALLOT_NUMBER, 4) DESC;")
	Dim JurisdictionRs:Set JurisdictionRs = oConn.Execute("SELECT * FROM Jurisdiction WHERE JCode ='" & KitRs("Jcode").Value & "';")
	Dim ContactRs:Set ContactRs = oConn.Execute("SELECT * FROM Contacts WHERE [JURISCODE] ='" & KitRs("Jcode").Value & "';")
	Dim ExportFileName:ExportFileName = objFSO.GetBaseName(KitRs("Filename")) & ".csv"
	If Not objFSO.FolderExists(ExportDirectory & KitRs("JobNumber").Value & "-" & JurisdictionRs("Name").value) Then:objFSO.CreateFolder(ExportDirectory & KitRs("JobNumber").Value & "-" & JurisdictionRs("Name").value):End If 
	If objFSO.FileExists(ExportDirectory & KitRs("JobNumber").Value & "-" & JurisdictionRs("Name").value & "/" & ExportFileName) Then:objFSO.DeleteFile(ExportDirectory & KitRs("JobNumber").Value & "-" & JurisdictionRs("Name").value & "/" & ExportFileName):End If 
	Dim ElectionDate:ElectionDate=GetSetting("ElectionDate")
	
	Dim objInkjetCSV:Set objInkJetCSV = CreateObject("Chilkat_9_5_0.Csv")
	objInkjetCSV.HasColumnNames = 1
	objInkjetCSV.EnableQuotes = 1
	
	objInkjetCSV.SetColumnName 0,"Full Name"
	objInkjetCSV.SetColumnName 1,"Address 1"
	objInkjetCSV.SetColumnName 2,"Address 2"
	objInkjetCSV.SetColumnName 3,"Address 3"
	objInkjetCSV.SetColumnName 4,"Address 4"
	objInkjetCSV.SetColumnName 5,"IM barcode Characters"
	objInkjetCSV.SetColumnName 6,"Precinct"
	objInkjetCSV.SetColumnName 7,"Ballot ID"
	objInkjetCSV.SetColumnName 8,"Ballot Number"
	objInkjetCSV.SetColumnName 9,"Jurisdiction code"
	objInkjetCSV.SetColumnName 10,"Election Date"
	objInkJetCSV.SetColumnName 11,"Combined  Pct_Ballot Num"
	objInkJetCSV.SetColumnName 12,"Title"
	objInkJetCSV.SetColumnName 13,"G2 Full Name"
	objInkJetCSV.SetColumnName 14,"G2 Company"
	objInkJetCSV.SetColumnName 15,"G2 Alternate 1 Address"
	objInkJetCSV.SetColumnName 16,"G2 Delivery Address"
	objInkJetCSV.SetColumnName 17,"G2 City St ZIP+4"
	objInkJetCSV.SetColumnName 18,"G2 IM barcode Characters"
	objInkJetCSV.SetColumnName 19,"Matching Code"

Dim AddressArray 
Dim row:row = 0	
		While Not KitLabelsRs.EOF
			AddressArray = CompressArray(Array(KitLabelsRs("CassADDRESS1").Value,KitLabelsRs("CassADDRESS2").Value,KitLabelsRs("CassADDRESS3").Value,KitLabelsRs("CassADDRESS4").Value,KitLabelsRs("CassADDRESS5").Value))
			objInkjetCSV.SetCellByName row,"Full Name",AddressArray(0)
			objInkjetCSV.SetCellByName row,"Address 1",AddressArray(1)
			objInkjetCSV.SetCellByName row,"Address 2",AddressArray(2)
			objInkjetCSV.SetCellByName row,"Address 3",AddressArray(3)
			objInkjetCSV.SetCellByName row,"Address 4",AddressArray(4)
			If KitRs("OutboundSTID") <> "0" Then
				objInkJetCSV.SetCellByName row,"IM barcode Characters",KitLabelsRs("OutboundIMBDigits").Value
			End If
			objInkJetCSV.SetCellByName row,"Precinct",KitLabelsRs("PRECINCT").Value
			objInkJetCSV.SetCellByName row,"Ballot ID","*" & KitLabelsRs("VOTERID").Value & "*" 
			objInkJetCSV.SetCellByName row,"Ballot Number",TrimLeadingZeros(KitLabelsRs("BALLOT_NUMBER").Value)
			objInkJetCSV.SetCellByName row,"Jurisdiction code",KitRs("Jcode").Value
			objInkJetCSV.SetCellByName row,"Election Date",ElectionDate
			objInkJetCSV.SetCellByName row,"Combined  Pct_Ballot Num",KitLabelsRs("PRECINCT").Value & TrimLeadingZeros(KitLabelsRs("BALLOT_NUMBER").Value)
			objInkjetCSV.SetCellByName row,"Title",CleanNull(ContactRs("Title").Value)
			objInkJetCSV.SetCellByName row,"G2 Full Name",JurisdictionRs("Name").Value
			objInkJetCSV.SetCellByName row,"G2 Company",JurisdictionRs("Mailing_Address").Value
			objInkJetCSV.SetCellByName row,"G2 Alternate 1 Address",JurisdictionRs("CSZ").Value
			objInkJetCSV.SetCellByName row,"G2 Delivery Address",""
			objInkJetCSV.SetCellByName row,"G2 City St ZIP+4",""			
			objInkJetCSV.SetCellByName row,"G2 IM barcode Characters",Choice(IsNull(KitRs("InboundSTID")),JurisdictionRs("IMB_Digits").Value,KitLabelsRs("InBoundIMBDigits").Value)
			objInkJetCSV.SetCellByName row,"Matching Code",KitRs("Jcode").Value & TrimLeadingZeros(KitLabelsRs("PRECINCT").Value) & TrimLeadingZeros(KitLabelsRs("BALLOT_NUMBER").Value)
			'Where do we put the roundtrip IMB
			row = row + 1
			KitLabelsRs.MoveNext
		Wend

	If KitRs("OfficeCopiesAmount").Value > 0 Then
		dim s 
		For s = 0 to KitRs("OfficeCopiesAmount").Value -1
			objInkjetCSV.SetCellByName row + s,"Title",CleanNull(ContactRs("Title").Value)
			objInkJetCSV.SetCellByName row + s,"G2 Full Name",JurisdictionRs("Name").Value
			objInkJetCSV.SetCellByName row + s,"G2 Company",JurisdictionRs("Mailing_Address").Value
			objInkJetCSV.SetCellByName row + s,"G2 Alternate 1 Address",JurisdictionRs("CSZ").Value
			objInkJetCSV.SetCellByName row + s,"G2 Delivery Address",""
			objInkJetCSV.SetCellByName row + s,"G2 City St ZIP+4",""
			objInkJetCSV.SetCellByName row + s,"G2 IM barcode Characters",JurisdictionRs("IMB_Digits").Value
		Next
	End If

	objInkjetCSV.SaveFile(ExportDirectory & KitRs("JobNumber").Value & "-" & JurisdictionRs("Name").value & "/" & ExportFileName)
	
	
	
	
	oConn.Execute("UPDATE KIT SET [Status] ='Done',[InkJetJob]=1  WHERE [ID] =" & KitID & ";")
	If KitRs.State = 1 Then:KitRs.Close:End If
	If ContactRs.State =1 Then:ContactRs.Close:End If 
	If KitLabelsRs.State = 1 Then:KitLabelsRs.Close: End If
	If JurisdictionRs.State = 1 Then:JurisdictionRs.Close:End If
	If oConn.State = 1 Then:oConn.Close:End If
End Function 

Function CheckStatusFor(StatusString)
	If oConn.State = 0 Then:oConn.Open(ConnectionString):End If
	Dim rs:Set rs = oConn.Execute("Select TOP 1 [ID] FROM [Kit] Where Status ='" & StatusString & "' and JobType='Purple Envelopes';")
		If Not rs.EOF Then
		CheckStatusFor = rs("ID").value
	Else
		CheckStatusFor = 0
	End If
		If rs.State = 1 Then:rs.Close:End If
		If oConn.State = 1 Then:oConn.Close:End If
End Function
	
Function CreateProofForJurisdiction(KitID)
	Dim Qpdf:Set Qpdf = WScript.CreateObject("DebenuPDFLibraryAX1013.PDFLibrary")
	Dim Result:Result = Qpdf.UnlockKey("j564z3wi9i66k93cp3r798b3y")
	If oConn.State = 0 Then:oConn.Open(ConnectionString):End If
	Dim Rs:set Rs = oConn.Execute("SELECT MIN(ID) as [MIN],MAX(ID) as [MAX] FROM InkjetRecords WHERE KitID = " & KitID &";")
	Dim MIN:MIN = Rs("MIN").Value
	Dim MAX:MAX = Rs("MAX").Value
	Dim RecordCount:RecordCount = (MAX - MIN) + 1
	Rs.Close
	Dim KitRs:set KitRs = oConn.Execute("Select * From [Kit] Where [ID] =" &  KitID & ";")
	Dim JurisdictionRs:set JurisdictionRs = oConn.Execute("SELECt * FROM [Jurisdiction] WHERE JCode='" & KitRs("Jcode").Value & "';")
	Dim ProofFileName:ProofFileName = objFSO.GetBaseName(KitRs("Filename")) & "-PROOF.PDF"
	If Not objFSO.FolderExists(ExportDirectory & KitRs("JobNumber").Value & "-" & JurisdictionRs("Name").value) Then:objFSO.CreateFolder(ExportDirectory & KitRs("JobNumber").Value & "-" & JurisdictionRs("Name").value):End If 
	Dim reportManager:set reportManager = CreateObject("ReportMan.ReportManX")
		With reportManager
			.Preview = False
			.ShowProgress = False
			.ShowPrintDialog = False
			.filename = PurpleEnvelopeProofReport
			.SetDatabaseConnectionString "WEBDATA",ConnectionString
			.SetParamValue "PBKITID",KitID
			.SetParamValue "PBJCODE",KitRs("Jcode").Value
			Dim MAXRECORDS:MAXRECORDS = 50000
			If RecordCount > MAXRECORDS Then
				Dim i
				For i = 0 To RecordCount / MAXRECORDS

					
					Dim newMin:If MIN + (i * MAXRECORDS) > MIN Then:newMin = MIN + (i * MAXRECORDS) + 1:Else newMin = MIN:End If 
					Dim newMax:If MIN + (i * MAXRECORDS) + MAXRECORDS > MAX Then:newMax = MAX:Else newMax = MIN + (i * MAXRECORDS) + MAXRECORDS:End If
					.SetParamValue "PBMIN",newMin
					.SetParamValue "PBMAX",newMax
					.SaveToPDF ExportDirectory & KitRs("JobNumber").Value & "-" & JurisdictionRs("Name").value & "\Part_" & i & "_" & ProofFileName,1
					Result = Qpdf.AddToFileList("Proofs",ExportDirectory & KitRs("JobNumber").Value & "-" & JurisdictionRs("Name").value & "\Part_" & i & "_" & ProofFileName)
				Next
					Result = Qpdf.MergeFileListFast("Proofs",ExportDirectory & KitRs("JobNumber").Value & "-" & JurisdictionRs("Name").value & "/" & ProofFileName)
				Dim test
				For test = 1 To Qpdf.FileListCount("Proofs")
			
				WshShell.Run "cmd.exe /c DEL /F /Q """ & Qpdf.FileListItem("Proofs",test) & """" ,0,True

				Next
				Else
					.SetParamValue "PBMIN",MIN
					.SetParamValue "PBMAX",MAX
					.SaveToPDF ExportDirectory & KitRs("JobNumber").Value & "-" & JurisdictionRs("Name").value & "/" & ProofFileName,1
			End If
		End With
	oConn.Execute("UPDATE KIT SET [Status] ='Ready For Inkjet Export' WHERE [ID] =" & KitID & ";")
	If KitRs.State = 1 Then:KitRs.Close:End If
	If JurisdictionRs.State = 1 Then:JurisdictionRs.Close:End If
	If oConn.State = 1 Then:oConn.Close:End If
	
End Function

Function CreateExportForSnailWorks(KitID)
	Dim State
	Dim AddressArray
	Dim ForeignTest
	If oConn.State = 0 Then:oConn.Open(ConnectionString):End If  
	Dim KitRs:set KitRs = oConn.Execute("Select * From [Kit] Where [ID] =" &  KitID & ";")
	If KitRs("OutboundSTID") <> "0" Then

		Dim KitLabelsRs: Set KitLabelsRs = oConn.Execute("SELECT InkjetRecords.ID, InkjetRecords.KitID, InkjetRecords.VOTERID, InkjetRecords.LASTNAME," &_
				" InkjetRecords.FIRSTNAME, InkjetRecords.MIDDLENAME, InkjetRecords.SUFFIX, InkjetRecords.PRECINCT," &_
				" InkjetRecords.ADDRESS1, InkjetRecords.ADDRESS2, InkjetRecords.ADDRESS3, InkjetRecords.ADDRESS4," &_
				" InkjetRecords.ADDRESS5, InkjetRecords.APPSENT, InkjetRecords.APPRETURNED, InkjetRecords.BALSENT," &_
				" InkjetRecords.BALRETURNED, InkjetRecords.CountingBoard, InkjetRecords.UOCAVASTATUS, InkjetRecords.EMAILADDRESS," &_
				" InkjetRecords.PHONENUMBER, InkjetRecords.BALLOT_NUMBER, InkjetRecords.CassADDRESS1, InkjetRecords.CassADDRESS2," &_
				" InkjetRecords.CassADDRESS3, InkjetRecords.CassADDRESS4, InkjetRecords.CassADDRESS5, InkjetRecords.KitLabelID," &_
				" KitLabels.ID, KitLabels.KitID, KitLabels.OutboundSerial, KitLabels.InBoundSerial, KitLabels.OutboundIMB," &_
				" KitLabels.InBoundIMB, KitLabels.OutboundIMBDigits, KitLabels.InBoundIMBDigits, KitLabels.OutboundIMBPNG," &_
				" KitLabels.INBOUNDIMBPNG, KitLabels.SetNumber" &_
				" FROM InkjetRecords" &_
				" LEFT JOIN [KitLabels] ON InkjetRecords.KitLabelID = KitLabels.ID" & _
				" WHERE InkjetRecords.KitID =" & KitID & " ;")
		Dim JurisdictionRs:Set JurisdictionRs = oConn.Execute("SELECT * FROM Jurisdiction WHERE JCode ='" & KitRs("Jcode").Value & "';")
		Dim ExportFileName:ExportFileName = objFSO.GetBaseName(KitRs("Filename")) & "_SW_EXPORT.csv"
		
		If Not objFSO.FolderExists(ExportDirectory & KitRs("JobNumber").Value & "-" & JurisdictionRs("Name").value) Then:objFSO.CreateFolder(ExportDirectory & KitRs("JobNumber").Value & "-" & JurisdictionRs("Name").value):End If 
		
		If objFSO.FileExists(ExportDirectory & KitRs("JobNumber").Value & "-" & JurisdictionRs("Name").value & "/" & ExportFileName) Then:objFSO.DeleteFile(ExportDirectory & KitRs("JobNumber").Value & "-" & JurisdictionRs("Name").value & "/" & ExportFileName):End If 
		Dim objExportFile:set objExportFile = objFSO.CreateTextFile(ExportDirectory & KitRs("JobNumber").Value & "-" & JurisdictionRs("Name").value & "/" & ExportFileName,2)
		With objExportFile
			.Write("""H"",") 																'Record Type Required value must be = "H" (Header)
			.Write(Truncate("5.2",5))														'Version Required value must be ="5.2" for current release
			.Write(Truncate("KCIHotFolder2024FTPUser",50))														'UserId Required 													
			.Write(Truncate(KitRs("Jcode").Value,50))										'Client Name Required (will create new subaccount if not already defined) - We decideded to make this the juriscode 
			.Write(Truncate("",50))															'Parent Client Name Optional (use if 3-tier account structure)
			.Write(Truncate("Purple envelope - " & KitRs("JobNumber").Value,50))			'Job Name Required
			.Write(Truncate("",50))															'Job Description Optional
			.Write(Truncate("",50))															'Split Name Optional � will default to �Default�
			.Write(Truncate("",80))															'Split Description Optional
			.Write(Truncate("L",1))															'Piece Type Required  L-Letters, C-Cards, F-Flats
			.Write(Truncate(Year(Now()) & "/" &_
				Right("0" & Month(Now()), 2) & "/" & Right("0" & Day(Now()), 2),10))		'MailDate Required (YYYY/MM/DD)
			.Write(Truncate("N",1))															'UploadType Required N = New job, new split A = Append new split to existing job R = Replace existing split
			.Write(Truncate("",8))															'TrackedQuantity Optional
			.Write(Truncate("",8))															'PiecesMailed Optional � shown as Estimated Quantity
			.Write(Truncate("",10))															'Target InHomeDateStart Optional (YYYY/MM/DD)
			.Write(Truncate("",10))															'Target InHomeDateEnd Optional (YYYY/MM/DD)
			.Write(Truncate("danielc@kentcommunications.com",100))							'ConfirmationEmail Optional
			.Write(Truncate("",9))															'JobId (SW) Optional for previously created jobs  SWJobId
			.Write(Truncate("",4))															'SplitId (SW) Optional for previously created jobs  SWJobId
			.Write(Truncate(Choice(IsNull(KitRs("InboundSTID")),"O","R"),1))				'TypeofTracking Required Values: O- Outbound Only I-Inbound Only R-Round Trip
			.Write(Truncate("",11))															'ReturnedPostalRoutingCode
			.Write(Truncate("",2))															'ReportId1
			.Write(Truncate("",255))														'Report1Email
			.Write(Truncate("",2))															'ReportId2
			.Write(Truncate("",255))														'Report2Email
			.Write("""N""")																	'INFOONLY
			.Write(vbCrLf)
		While Not KitLabelsRs.EOF
		AddressArray = Array(KitLabelsRs("CassADDRESS2").Value,KitLabelsRs("CassADDRESS3").Value,KitLabelsRs("CassADDRESS4").Value,KitLabelsRs("CassADDRESS5").Value)
			PushNonEmptyToBottom AddressArray
			ForeignTest = AddressArray(3) & " " & AddressArray(2)
			State = GetState(AddressArray(3))
			State = Replace(State," ","")
			If CheckStringDoesNotHaveForiegnCountries(ForeignTest) And State <> """""," then
			'If InStr(ForeignTest,"CANADA") = 0 And InStr(ForeignTest,"AUSTRALIA") = 0 And State <> ""  Then      " ",
			
				.Write("""D"",")																'RecordType Required value must be = �D� (Detail)
				.Write(Truncate("",20))															'CustomerUniqueIdentifier Optional- any identifier you designate
				.Write(Truncate(KitLabelsRs("OutboundIMBDigits"),31))							'IMB Required � Unencoded, numeric IMB
				.Write(Truncate("",10))															'Greeting Optional
				.Write(Truncate("",50))															'First Name Optional
				.Write(Truncate("",2))															'MI  Optional
				.Write(Truncate("",50))															'Last Name Optional
				.Write(Truncate("",10))															'Suffix Optional
				.Write(Truncate((KitLabelsRs("CassADDRESS1").Value),100))						'Full Name Optional
				.Write(Truncate("",50))															'Company Optional
				.Write(Truncate("",50))															'Title  Optional
				.Write(Truncate(AddressArray(1),128))							'Address1   Optional
				.Write(Truncate(AddressArray(2),128))							'Address2   Optional
				.Write(Truncate(Left(AddressArray(3), _
					InStr(AddressArray(3), ",") - 1),50))						'City     Optional
				.Write(Truncate(State,2))																'State Optional
				.Write Choice(InStr(AddressArray(3),"-"),Truncate(Right(AddressArray(3),11),11),Truncate(Right(AddressArray(3),5),5)) 'Zip   Optional
				.Write(Truncate(KitRs("Jcode"),100))											'UserDefined1 Optional - Summary fields only
				.Write(Truncate("",100))														'UserDefined2 Optional - Summary fields only
				.Write(Truncate("",100))														'UserDefined3 Optional - Summary fields only
				.Write(Truncate(KitLabelsRs("PRECINCT").Value &_
					KitLabelsRs("BALLOT_NUMBER"),80))											'UserDefinedIdentifier4 Optional � Allows for unique identifiers
				.Write(Truncate(KitLabelsRs("VOTERID").Value,80))								'UserDefinedIdentifier5 Optional � Allows for unique identifiers
				.Write(Truncate("",1))															'SeedIndicator  Optional - if true provide �Y�
				.Write(Truncate("",80))															'InductionPoint  Optional
				.Write(Truncate("",10))															'InductionDate	Optional � Valid date format, ex. MM/DD/YYYY
				.Write(Truncate(Choice(IsNull(KitRs("InboundSTID")),"",  _
					KitLabelsRs("InBoundIMBDigits").Value),31))									'InboundIMB Optional � numeric IMB for Round trip jobs only
				.Write(Truncate("",24))															'IMCB Optional � Container Barcode
				.Write("""""")																	'IMTB Optional � Tray Barcode
				.Write(vbCrLf)
			
			End If	
		KitLabelsRs.MoveNext
		Wend

			.Close
		End With
	


	If KitLabelsRs.State = 1 Then:KitLabelsRs.Close: End If
	If JurisdictionRs.State = 1 Then:JurisdictionRs.Close:End If
	End If
	oConn.Execute("UPDATE KIT SET [Status] ='Ready to Proof',[ExportedToSnailWorks] =#" & Now() & "#  WHERE [ID] =" & KitID & ";")
	If oConn.State = 1 Then:oConn.Close:End If
	If KitRs.State = 1 Then:KitRs.Close:End If
End Function 

Function createTrackingInfoForKit(KitID)
If oConn.State = 0 Then:oConn.Open(ConnectionString):End If  
oConn.Execute("UPDATE Kit SET Status ='Applying Serial Numbers' WHERE ID =" & KitID & ";")
Dim KitRs:set KitRs = oConn.Execute("Select * from Kit Where ID =" & KitID & ";")

If KitRs("OutBoundSTID") = 0 Then
		oConn.Execute("UPDATE Kit Set [Status]='Ready For Export', LabelsPrinted=#" & Now() & "# WHERE [ID] =" & KitID &";")
Else

		Dim InkjetRs:Set InkjetRs = oConn.Execute("Select * from InkjetRecords Where KitID =" & KitID & ";")
		Dim JurisRs:set JurisRs = oConn.Execute("Select Right(IMB_Digits,9) as IMBZip FROM Jurisdiction Where JCode ='" & KitRs("Jcode") & "';"):Dim Jcode:Jcode = JurisRs("IMBZip"):JurisRs.Close
		Dim SerialNumberStart:SerialNumberStart = GetSetting("SerialNumberStart")
		Dim serialOffset:serialOffset = GetSetting("SerialOffset")
		Dim serialStart:serialStart = CLng(GetSetting("SerialNumberStart")) + CLng(GetSetting("SerialOffset"))
		Dim Counter:Counter=0
		Dim KitLabelID
		Dim KitLabelRs
		Dim Mid:Mid = GetSetting("MailingID")
		Dim Step : If KitRs("InboundSTID") <> "" Then : Step = 2  : Else Step = 1
		serialStart = PadLeft(serialStart + CLng(Counter),9,"0")
		Dim oRsKitLabels : Set oRsKitLabels = CreateObject("ADODB.Recordset"):oRsKitLabels.Open "Select * FROM [KitLabels] Where KitID =" & KitID & ";",oConn,3,3
		While Not InkjetRs.EOF
			oRsKitLabels.AddNew
			KitLabelID = oRsKitLabels("ID").value
			If Step = 1 Then
				oRsKitLabels("KitID") = KitID
				oRsKitLabels("OutboundSerial") = serialStart
				oRsKitLabels("OutboundIMBDigits") = KitRs("OutBoundSTID").Value & Mid & serialStart
			Else
				oRsKitLabels("KitID") = KitID
				oRsKitLabels("OutboundSerial") = serialStart
				oRsKitLabels("InBoundSerial") = serialStart + 1
				oRsKitLabels("OutboundIMBDigits") = KitRs("OutBoundSTID").Value & Mid & serialStart
				oRsKitLabels("InBoundIMBDigits") = KitRs("InboundSTID").Value & Mid & serialStart + 1 & Jcode
			End If 
			oRsKitLabels.Update
			oConn.Execute("UPDATE InkjetRecords Set [KitLabelID]=" & KitLabelID & " WHERE ID=" & InkjetRs("ID") & ";")
			Counter = Counter + Step
			serialStart = serialStart + Step

		InkjetRs.MoveNext
		Wend
		oRsKitLabels.Update	
		oRsKitLabels.Close
		oConn.Execute("UPDATE Settings Set [Value]='" & serialOffset + Counter & "' WHERE [Name] = 'SerialOffset';")
		oConn.Execute("UPDATE Kit Set [Status]='Ready For Export', LabelsPrinted=#" & Now() & "# WHERE [ID] =" & KitID &";")
		oConn.Close
		End If
End Function

Function GetSetting(settingName)

Dim rs:Set rs = oConn.Execute("Select Value From [Settings] Where [Name] = '" & settingName & "';")

	If Not rs.EOF Then
		GetSetting = rs(0).value
		rs.Close
	Else
		SetSetting = 0
		rs.Close
	End If
	

End Function 

Function CheckForFiles()

	
	If objFSO.FolderExists(DataDirectory) Then
		Dim objFolder:Set objFolder = objFSO.GetFolder(DataDirectory)
	    
	    	If objFolder.Files.Count > 0 Then
        		'WScript.Echo "Files found in directory: " & DataDirectory
        		Dim objFile
        		For Each objFile In objFolder.Files
        			Dim CsvString:CsvString = ConvertCsvToString(objFile.Path)
            		If ValidImportCSV(CsvString) Then
            			SetupKit CsvString,objFile.Name
            			objFSO.MoveFile objFile.Path, DataDirectory & "\import\" & objFile.Name
            		End If 
        		Next
    		Else
        		'WScript.Echo "No files found in directory: " & DataDirectory
    		End If
	
	End If 
End Function 

Function ValidJcode(jcode)
Dim oConn
Set oConn = WScript.CreateObject("ADODB.Connection")
oConn.ConnectionString = ConnectionString
oConn.Open
Dim oRs
set oRs = oConn.Execute("Select * from Jurisdiction Where [JCode] = '" & jcode & "';")
If oRs.EOF Then 
	ValidJcode = 0
Else
	ValidJcode = 1
End If  
oRs.Close
oConn.Close
End Function

Function CheckStringDoesNotHaveForiegnCountries(StringToCheck)
Dim Countries
Countries = Array("SPAIN","LAGOS","PORTUGL","ON N4K 5-Y1","ITALY","CANADA","PHILIPPINES","GWYNEDD PENYGROES","NEW SOUTH WALES","UNITED KINGDOM","CHINA","SCOTLAND UK","ISRAEL","AUSTRIA","NORWAY","BUDAPEST","JAPAN","NEW ZEALAND","AUSTRALIA","FRANCE","UK LL","KENT  ENGLAND","CANADA","NETHERLANDS","GERMANY","TAIWAN","NICARAGUA","IREL")
Dim Country
For Each Country In Countries

	If InStr(StringToCheck,Country) Then
	
		CheckStringDoesNotHaveForiegnCountries = False
		Exit For
	End If
	
	CheckStringDoesNotHaveForiegnCountries = True
	
Next



End Function
Function SetupKit(CsvString,FileName)
Dim JobNumber:JobNumber = Mid(FileName,9,6)
Dim JCode:JCode = Left(Filename,5)
	If IsNumeric(JobNumber) Then
		If ValidJcode(JCode) Then
			WScript.Echo FileName & " Is a Valid CSV for Importing"
			Dim oConn:Set oConn = WScript.CreateObject("ADODB.Connection")
			oConn.ConnectionString = ConnectionString
			oConn.Open
			oConn.Execute("Insert Into Kit ([JobNumber], [Jcode], [CreatedOn], [JobType],[Filename],[Status]) VALUES ('" & JobNumber & "','" & JCode & "',#" & Now() & "#,'Purple Envelopes','" & FileName & "','Importing');") 
			Dim rs : set rs = oConn.Execute("Select TOP 1 ID from Kit ORDER BY ID DESC")
			Dim kitId : kitId = rs("ID").value
			rs.close
			Dim i
			For i = 1 To objCSV.NumRows -1
			Dim AddressArray:AddressArray = Array(Replace(objCSV.GetCell(i,6),"'","''"),Replace(objCSV.GetCell(i,7),"'","''"),Replace(objCSV.GetCell(i,8),"'","''"),Replace(objCSV.GetCell(i,9),"'","''"),Replace(objCSV.GetCell(i,10),"'","''"))
			PushNonEmptyToBottom AddressArray
			
			oConn.Execute("Insert Into [InkjetRecords] (KitID,VOTERID,LASTNAME,FIRSTNAME,MIDDLENAME" & _
			",SUFFIX,PRECINCT,ADDRESS1,ADDRESS2,ADDRESS3,ADDRESS4,ADDRESS5,APPSENT,APPRETURNED,BALSENT,BALRETURNED" & _
			",CountingBoard,UOCAVASTATUS,EMAILADDRESS,PHONENUMBER,BALLOT_NUMBER) VALUES (" & kitId & _
			",'" & Replace(objCSV.GetCell(i,0),"'","''") & _
			"','" & Replace(objCsv.GetCell(i,1),"'","''") & _
			"','" & Replace(objCSV.GetCell(i,2),"'","''") & _
			"','" & Replace(objCSV.GetCell(i,3),"'","''") & _
			"','" & Replace(objCSV.GetCell(i,4),"'","''") & _
			"','" & Replace(objCSV.GetCell(i,5),"'","''") & _
			"','" & AddressArray(0) & _
			"','" & AddressArray(1) & _
			"','" & AddressArray(2) & _
			"','" & AddressArray(3) & _
			"','" & AddressArray(4) & _
			"','" & Replace(objCSV.GetCell(i,11),"'","''") & _
			"','" & Replace(objCSV.GetCell(i,12),"'","''") & _
			"','" & Replace(objCsv.GetCell(i,13),"'","''") & _
			"','" & objCsv.GetCell(i,14) & _
			"','" & objCsv.GetCell(i,15) & _
			"','" & objCsv.GetCell(i,16) & _
			"','" & objCsv.GetCell(i,17) & _
			"','" & objCsv.GetCell(i,18) & _
			"','" & objCsv.GetCell(i,19) & _
			"')")
			Next
			oConn.Execute("Update Kit SET [Status] = 'Ready to Cass' Where ID = " & kitId &";")
			'oConn.Close
		End If
	End If
	
	

End Function 
Function ConvertCsvToString(FilePath)
	Dim objFSO:Set objFSO = CreateObject("Scripting.FileSystemObject")
	Dim objCsvFile:set objCsvFile = objFSO.OpenTextFile(FilePath)
	Dim strContent:strContent = ""
	Dim intLineCount:intLineCount = 0
	    Do Until objCsvFile.AtEndOfStream Or intLineCount >= 3
			objCsvFile.SkipLine
			intLineCount = intLineCount + 1
		Loop
	    ' Read the remaining content into a string

			Do Until objCsvFile.AtEndOfStream
			Dim strLine:strLine = objCsvFile.ReadLine
			strContent = strContent & strLine & vbCrLf
		Loop

ConvertCsvToString = strContent
End Function 

Function ValidImportCSV(CsvFileAsString)
	objCSV.LoadFromString(CsvFileAsString)
	If objCSV.NumColumns = 20 Then
		ValidImportCSV = True
	Else
		ValidImportCSV = False
	End If
End Function

Sub ImportCass
	Dim currentRow
	Select Case dev
	Case "local"
		objCsv.LoadFile("C:\Share\TrackingDataExport\FROM_MM.CSV")
	Case True 
		objCsv.LoadFile("C:\Share\TrackingDataExport\FROM_MM.CSV")
	Case Else
		objCsv.LoadFile("\\kci-syn-cl01\PC Transfer\TrackingDataExport\FROM_MM.CSV")
	End Select
	For currentRow = 0 To objCsv.NumRows -1
Dim AddressArray:AddressArray = CompressArray(Array(Replace(objCsv.GetCell(currentRow,1),"'","''"),Replace(objCsv.GetCell(currentRow,2),"'","''"),Replace(objCsv.GetCell(currentRow,3),"'","''"),Replace(objCsv.GetCell(currentRow,4),"'","''"),Replace(objCsv.GetCell(currentRow,5),"'","''"),Replace(objCsv.GetCell(currentRow,6) & ", " & objCsv.GetCell(currentRow,7) & " " & objCsv.GetCell(currentRow,8),"'","''")))

	
	oConn.Execute("UPDATE InkJetRecords SET CassADDRESS1 = '" & AddressArray(0) & "', " &_ 
	              "CassADDRESS2 = '"  & AddressArray(1) & "', " &_
	              "CassADDRESS3 = '"  & AddressArray(2) & "', " &_
	              "CassADDRESS4 = '"  & AddressArray(3) & "', " &_
	              "CassADDRESS5 = '"  & AddressArray(4) & "'" &_
	              " WHERE ID = " & objCSV.GetCell(currentRow,0) & ";")
		
	Next

			 oConn.Execute("UPDATE Kit SET Status ='Ready To Assign STIDS' WHERE ID =" & KitID & ";")
			 oConn.Execute("UPDATE Kit SET [Cass] = 1 WHERE ID =" & KitID & ";")
End Sub

Sub RunMailManager
	Select Case dev
	Case "local"
		WshShell.Run "PsExec64.exe -i -e -u ntp\danielc -p SunBrightShine! \\MarkH2 ""\\MM2012\APPS\BCC\MM2010\mailman.exe"" -p -j MMJOB-LOCAL.mjb -u DAN",1,True
	Case True  
		WshShell.Run "PsExec64.exe -i -e -u ntp\danielc -p SunBrightShine! \\MarkH2 ""\\MM2012\APPS\BCC\MM2010\mailman.exe"" -p -j MMJOB-DEV.mjb -u DAN",1,True
	Case Else
		WshShell.Run "PsExec64.exe -i -e -u ntp\danielc -p SunBrightShine! \\MarkH2 ""\\MM2012\APPS\BCC\MM2010\mailman.exe"" -p -j MMJOB.mjb -u DAN",1,True
	End Select
End Sub
Sub ExportMMCsv(KitId)
	
	Dim success
	objCsv.HasColumnNames = 1
	objCSV.EnableQuotes = 1
	success = objCsv.SetColumnName(0,"ID")
	success = objCsv.SetColumnName(1,"NAME")
	success = objCsv.SetColumnName(2,"ADDRESS1")
	success = objCsv.SetColumnName(3,"ADDRESS2")
	success = objCsv.SetColumnName(4,"ADDRESS3")
	success = objCsv.SetColumnName(5,"ADDRESS4")
	success = objCsv.SetColumnName(6,"ADDRESS5")
 	Dim rs : Set rs = oConn.Execute("Select ID," & _ 
 								 "IIF(FIRSTNAME IS NULL,'',FIRSTNAME & ' ') & " & _
 								 "IIF(MIDDLENAME IS NULL,'',MIDDLENAME & ' ') & " & _
 								 "IIF(LASTNAME IS NULL,'',LASTNAME & ' ') & " & _
 								 "IIF(SUFFIX IS NULL,'',SUFFIX & ' ') " & _
 								 "AS NAME, ADDRESS1,ADDRESS2,ADDRESS3,ADDRESS4,ADDRESS5 FROM InkjetRecords WHERE KitID =" & KitID & " ORDER By ID;")
		Dim CurrentRow:CurrentRow = 0 
		While Not rs.EOF
			objCSV.SetCell CurrentRow,0,rs("ID").value
			objCSV.SetCell CurrentRow,1,rs("NAME").value 
			objCSV.SetCell CurrentRow,2,rs("ADDRESS1").value 
			objCSV.SetCell CurrentRow,3,rs("ADDRESS2").value 
			objCSV.SetCell CurrentRow,4,rs("ADDRESS3").value 
			objCSV.SetCell CurrentRow,5,rs("ADDRESS4").value 
			objCSV.SetCell CurrentRow,6,rs("ADDRESS5").value  
			rs.MoveNext
			CurrentRow = CurrentRow +1
		Wend
		Dim CsvString:CsvString = objCSV.SaveToString()
		outFile.WriteLine CsvString
		outFile.Close

End Sub
Function CheckForJobsToCass()
oConn.ConnectionString = ConnectionString
oConn.Open

	'oConn.Open
	Dim rs : set rs = oConn.Execute("Select TOP 1 ID from Kit Where Status ='Ready to Cass' ORDER BY ID DESC;")
		If Not rs.EOF Then
			Dim kitId : kitId = rs("ID").value
			rs.Close
			CheckForJobsToCass = KitID
			 oConn.Execute("UPDATE Kit SET Status ='Cassing' WHERE ID =" & KitID & ";")
		Else 
			CheckForJobsToCass = 0
		End If 
	'oConn.Close
End Function

Public Function PadLeft(originalString,desiredLength,Char)
Dim padLength
    padLength = desiredLength - Len(originalString)
    If padLength > 0 Then
    ' Left pad the string with zeros
    PadLeft = String(padLength, Char) & originalString
Else
    ' If the original string is already longer or equal to the desired length, no padding is needed
    PadLeft = originalString
End If

End Function
Function Truncate(inputString, size)

	If Len(inputString) > size Then:Truncate = """" & Left(inputString,size) & """,":Else Truncate = """" & inputString  & """,":End If

End Function
Function PadString(inputString, size)
    Dim paddedString
    Dim inputLength
    Dim i
	If IsNull(inputString) Then:inputString = ""
    ' Get the length of the input string
    inputLength = Len(inputString)

    ' If the input string is already equal to or longer than the specified size, return it as is
    If inputLength >= size Then
        PadString = inputString
        Exit Function
    End If

    ' Initialize the padded string with the input string
    paddedString = inputString

    ' Pad spaces to the right of the input string until it reaches the specified size
    For i = 1 To (size - inputLength)
        paddedString = paddedString & " "
    Next

    ' Return the padded string
    PadString = paddedString
End Function

Function CleanNull(StringToClean)
	If IsNull(StringToClean) Then:CleanNull = "":Else CleanNull = StringToClean:End If
End Function  

Public Sub Assign(ByRef var, ByVal val)
    If IsObject(val) Then
        Set var = val
    Else
        var = val
    End If
End Sub

Public Function Choice(ByVal cond, ByVal if_true, ByVal if_false)
    If cond Then
        Assign Choice, if_true
    Else
        Assign Choice, if_false
    End If
End Function

Function CompressArray(arr)
    Dim temp,i,j
    For i = LBound(arr) To UBound(arr) - 1
        For j = i + 1 To UBound(arr)
            If arr(i) = "" Then
                temp = arr(i)
                arr(i) = arr(j)
                arr(j) = temp
            End If
        Next
    Next
    CompressArray = arr
End Function

Function TrimLeadingZeros(inputStr)
    Dim i
    For i = 1 To Len(inputStr)
        If Mid(inputStr, i, 1) <> "0" Then
            TrimLeadingZeros = Mid(inputStr, i)
            Exit Function
        End If
    Next
    ' If the input string is all zeros, return "0"
    TrimLeadingZeros = "0"
End Function

Sub PushNonEmptyToBottom(ByRef myArray)
    Dim tempArray(), i, count
    count = UBound(myArray)
    
    ' Create a temporary array to store the rearranged elements
    ReDim tempArray(UBound(myArray))
    
    ' Fill the temporary array with empty strings initially
    For i = 0 To UBound(myArray)
        tempArray(i) = ""
    Next

    ' Add non-empty elements to the highest-numbered positions
    For i = UBound(myArray) To 0 Step -1
        If myArray(i) <> "" Then
            tempArray(count) = myArray(i)
            count = count - 1
        End If
    Next
    
    ' Copy the temporary array back to the original array
    For i = 0 To UBound(myArray)
        myArray(i) = tempArray(i)
    Next
End Sub


Copy code
Function GetState(ByVal addressLine)
    Dim statePattern, matches, state
    statePattern = ",\s([A-Z]{2})\s\d{5}" ' Pattern to match ", STATE ZIP"
    Dim regEx
    Set regEx = New RegExp
    regEx.Pattern = statePattern
    regEx.IgnoreCase = False
    regEx.Global = False
    
    Set matches = regEx.Execute(addressLine)
    
    If matches.Count > 0 Then
        ' Extract the state abbreviation (the first captured group)
        state = Trim(matches(0).SubMatches(0))
    Else
        state = ""
    End If
    
    GetState = state
End Function