Jump to content

Issues Transfering Script to a new PC


MaxG
 Share

Recommended Posts

Hello All,

Have any of you seen aberrations in performance. reliability, or stability when transferring scripts from one PC to another?  I'm not asking for help debugging actual code, but if any of you have experiences you'd like to share or additional insight on the topic, please feel free to comment.

Scenario:
I wrote a script that extracts data from PDFs and then uses that data to operate enterprise mailing software.  Over the last year I've found the script to be stable and perform reliably.  I recently requisitioned a new workstation to run the script full time, but I'm finding that the behavior is not identical.  Most of the time it runs as expected, but there seem to be new issues popping up now and then that never appeared during the previous year on the old PC.  It feels like the code executes too fast despite gating code sections with WinWait / WinActivate pairs and sleep statements.

Sporadic Issue Examples:
- Code execution getting past WinWait / WinActivate code pairs before the window should exist.
- ControlSetText not registering even though correct window is activated.

Machine Details:
OLD:    HP Compaq Pro 4300 SFF (i3-3220, 4GB Ram, Windows 7 Pro)
NEW:    HP ProDesk 400 G1 SFF (i5-4590, 4GB Ram, Windows 7 Pro)

AutoIT Version: 3.3.12.0

Link to comment
Share on other sites

I wrote a script that extracts data from PDFs

I am curious: entirely in AutoIt ? or you are using any additional libraries to manged PDF files ? Which ones ?

Edited by mLipok
wording

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

Where's your script? How are we supposed to know why it doesn't work if we don't know what you're doing?

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

@mLipok There are some JS files for acrobat automation and some VBA addins for Excel, but I'm confident they are not the culprits as they run at the end without any deviation in expected results.  The PDF extraction involves converting the documents to text and then using regular expressions.

@KingBob I'm sorry, I intentionally left out the script itself as I thought this would be a more general question of "same script, same software/OS, different hardware, any thoughts?".  Its hundreds of lines long and very specific to our mailing software and network setup, so its essentialy un-runable for anyone else.  If you'd like to see it I can take some time to remove anything relating to our internal network and/or customers and post.

Link to comment
Share on other sites

Post a reproducer script, one that functions the same as the original script, and that demonstrates the error.

As I said, there's no magic involved here, we can't say that X is the problem if we don't know what you're doing in X.

BTW, your internal network information is useless to anyone not on your network, or even help them to know where your internal network is. Just because you're internal IP address might be 10,60.1.100, doesn't mean anyone can use that information to get into your network. User names and passwords to externally accessible data and customer names would be an issue, but nothing related to your internal network would be. Just an FYI

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

Can you share links to this:

There are some JS files for acrobat automation and some VBA addins for Excel,

 

For what Window APP you are using this:

Sporadic Issue Examples:
- Code execution getting past WinWait / WinActivate code pairs before the window should exist.
- ControlSetText not registering even though correct window is activated.

In the past I have similar issues because I use:

Opt("WinWaitDelay", 1)
Opt("MouseClickDelay", 1)
Opt("MouseClickDownDelay", 1)
Opt("MouseClickDragDelay", 1)
Opt("SendKeyDelay", 1)
Opt("SendKeyDownDelay", 1)

What can cause strange problems and it seems to me that were similar to yours (but not sure as this was long ago)

 

Machine Details:
OLD:    HP Compaq Pro 4300 SFF (i3-3220, 4GB Ram, Windows 7 Pro)
NEW:    HP ProDesk 400 G1 SFF (i5-4590, 4GB Ram, Windows 7 Pro)

... and in both cases, Windows was the same, I mean 32 or 64 bits ?

 

You are also talking about " acrobat automation " --> Acrobat which one exactly ?

 

But anyway, I agree with @KingBob.

 

Edited by mLipok

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

I am unable to reproduce these errors, they are intermittent in nature.  Its actually been running all morning with no problems, but yesterday I was practically tearing my hair out.  There can be considerable variable length lag between the server and the client and some of my issues may simply be a matter of timing.

I have nothing but respect for you KingBob, and everyone else on these forums for that matter.  I completely understand if this is a waste of your time without a reproducer script, but I appreciate that you stopped in to respond at all.

Link to comment
Share on other sites

@mLipok

  • I can't link the JS and Add-ins... I didn't download them, I wrote them for specific small tasks.
    The JS files were written and dumped in Acrobat's javascripts folder.
     
  • The app is "BCC Mail Manager Full Service"
     
  • These are my includes:
    #include <Excel.au3>
    #include <File.au3>
    #include <Array.au3>
    #include <GuiTab.au3>
    #include <Date.au3>
    #include <_ArrayRemoveBlanks.au3>
    #include <_LoadingAnimation.au3>
    #include <StringConstants.au3>
     
  • These are my opts:
    Opt("SendKeyDelay", 10)
    Opt("SendKeyDownDelay", 10)
    Opt("PixelCoordMode", 0)
    Opt("TrayIconDebug", 1)
     
  • Both Windows 7 installs are 64 bit.
     
  • Adobe Acrobat XI Standard in both cases
Link to comment
Share on other sites

; INCLUDES
#Region
#include <Excel.au3>
#include <File.au3>
#include <Array.au3>
#include <GuiTab.au3>
#include <Date.au3>
#include <_ArrayRemoveBlanks.au3>
#include <_LoadingAnimation.au3>
#include <StringConstants.au3>
#EndRegion

; OPTIONS
#Region
Opt("SendKeyDelay", 10)
Opt("SendKeyDownDelay", 10)
Opt("PixelCoordMode", 0)
Opt("TrayIconDebug", 1)

;BlockInput(1)              ;Will completely block keyboard input (Not yet in use during testing)
#EndRegion

;PAUSE / TERMINATE HOTKEYS
#Region
Global $Paused
HotKeySet("{PAUSE}", "TogglePause")
HotKeySet("{ESC}", "Terminate")
#EndRegion

;TIMER INITIALIZATION
#Region
Local $hTimer = TimerInit()
Local $RunTimeInMilliseconds = ""
Local $TimerHours = ""
Local $TimerMinutes = ""
Local $TimerSeconds = ""
#EndRegion

; DIRECTORY CONSTANTS
#Region
Const $dirGCMaps = @DesktopDir & "\Script Test Files\TEST_ENVIRONMENT\Grande Cheese Maps"
Const $dirJobTickets = @DesktopDir & "\Script Test Files\TEST_ENVIRONMENT\__JobTicketsToProcess"
Const $dirWideArray = @DesktopDir & "\Script Test Files\TEST_ENVIRONMENT\WideArray_Data"
Const $dirSuccessfulJobs = @DesktopDir & "\Script Test Files\TEST_ENVIRONMENT\_Successful"
Const $dirPermitTableExport = @DesktopDir & "\Script Test Files\TEST_ENVIRONMENT\Permit Table Export"
Const $dirTemplateFiles = @DesktopDir & "\Script Test Files\TEST_ENVIRONMENT\Template Files"
Const $dirPrebill = @DesktopDir & "\Script Test Files\TEST_ENVIRONMENT\Prebill Invoices"
Const $dirInvoice = @DesktopDir & "\Script Test Files\TEST_ENVIRONMENT\GC Invoice Dir\"
Const $dirEventLog = @DesktopDir & "\Script Test Files\TEST_ENVIRONMENT\Event Log"
Const $dirFailedJobs = @DesktopDir & "\Script Test Files\TEST_ENVIRONMENT\_Failed"
#EndRegion

; DELAY CONSTANTS
#Region
Const $microDelay = 250         ; Tiny pauses between commands. (Milliseconds)
Const $shortDelay = 1000            ; Small pauses between commands. (Milliseconds)
Const $mediumDelay = 5000       ; Medium pauses, (Milliseconds)
Const $longDelay = 10000            ; Long pauses. (Milliseconds)
Const $timeout = 30                 ; Command timeout.  (Seconds)
#EndRegion

; JOB TICKET VARIABLES
#Region
Local $listName = "Max_Test"    ; BCC List DBF Name - Obviously, this is hard coded for testing purposes. (ALSO SET IN FUNCTION)
Local $JobNum = ""                  ; Job Number extracted from the job ticket.
Local $PizzaPlace = ""                  ; Pizza Place name extracted from customer folder in GCMaps.
Local $GrandeID = ""                    ; Grande ID extracted from the job ticket.
Local $MailDate = ""                    ; Date of mailing extracted from the "Due Date" on the job ticket.
Local $PieceCount = ""              ; Total piece count for this mailing extracted from "ONLY #### MAILING" section of job ticket.
Local $BeginningQty = ""            ; Beginning quantity extracted from "Quantity: ####" section of the job ticket.
Local $PieceType = ""                   ; Piece type (Letter or Flat) extracted from job ticket specs.
Local $TicketPieceHeight = ""       ; Piece height extracted from job ticket specs.
Local $TicketPieceWidth = ""        ; Piece width extracted from job ticket specs.
Local $PieceLength = ""             ; BCC field value converted from the larger value in $TicketPieceHeight and $TicketPieceWidth.
Local $PieceHeight = ""             ; BCC field value converted from the smaller value in $TicketPieceHeight and $TicketPieceWidth.
Local $PieceWeight = ""             ; Piece weight per X number of samples extracted from job ticket specs.
Local $PieceThickness = ""          ; Piece thickness per X number of samples extracted from job ticket specs.
Local $PieceSampleQty = ""      ; The number of samples used to determine thickness and weight sample amounts from job ticket specs.
Local $EntryOfficeLine1 = ""        ; The first line of the entry office for the 8125 extracted from the shipping information on the job ticket.
Local $EntryOfficeLine2 = ""        ; The second  line of the entry office for the 8125 extracted from the shipping information on the job ticket.
Local $EntryOfficeLine3 = ""        ; The third line of the entry office for the 8125 extracted from the shipping information on the job ticket.
Local $EntryOfficePhone = ""        ; The phone number of the entry office for the 8125 extracted from the shipping information on the job ticket.
#EndRegion

; PROGRAM VARIABLES
#Region
Local $arrZipCodes                      ; An array that will hold the zip codes extracted from the distribution report.
Local $arrRegExFound                ; A temporary array to hold regular expression matches before assigning to a named variable.
Local $arrDateParts                     ; A temporary array used to split date strings so the day, month, and year are seperate elements.
Local $arrPermitPos = ""                ; Stores the X Y coordinates of the selected permit returned from a pixel search.
Local $arrPermitSize = ""           ; Stores the dimensions of the permit selection window to dynamically adjust pixel search window.
Local $jobTicketTextArray           ; An array that holds the file names of extracted text from each job ticket.
Local $jobTicketArray                   ; An array that holds the file names of the job ticket PDFs.
Local $folderArray                      ; An array that holds the customer folder path when extracted from the Grande Cheese Maps dir.

Local $iCountJobs = 0               ; Counter variable used in the batch processing loop.

Local $fullJobPath = ""             ; Holds the full path to the current job folder in process.
Local $JobFolder = ""                   ; Holds just the folder name for the current job in process.
Local $CustFolder = ""              ; Holds the base customer folder name as it appears in the Grande Cheese Maps directory.
Local $PermitNameFind = ""      ; Holds the permit name associated with the Grande ID as found in Permit.csv.
Local $PrebillFolder = ""               ; Holds the base customer prebill folder name as it appears in the Grande Cheese Prebill Invoices dir.
Local $PrebillFile = ""                 ; Holds the name of the job specific prebill file name.
Local $listFile = ""                        ; Holds the name of the list file found in the current job folder in process.
Local $LabelOutputName = "" ; Holds the constructed output file name prior to output to the WideArray_Data directory.
Local $FileNameOf8125 = ""      ; Currently Not Used - I may need to change this to an array for processing multiple drops.
Local $ControlText = ""             ; Temportary variable to hold intial text stored in controls such as initial file names.

Local $sLogDate = ""                    ; String value containing the event log file creation date.
Local $sLogName = ""                ; String value containing the name of the event log file.

Local $MailDateFormatted = ""   ; Mail date formatted as mm.dd.yy - Used for Mail.dat folders.

Local $WaitingFlag = False          ; A boolean flag used to determine if we are waiting for the permit database to be unused.

Local $hFileOpen = ""                   ; Stores the handle of a file opened for read/write access.
Local $sFileRead = ""                   ; Holds the text read-in from an opened file such as job ticket texts.

Local $sPermitCSV = ""              ; Holds the contents of the Permit.csv file for RegEx purposes.

Local $AcrobatApp = ""              ; Object variable to hold the OLE Acrobat Application instance.
Local $AcrobatAVDoc = ""            ; Object variable to hold the OLE Acrobat Viewer instance.
Local $AcrobatPDDoc = ""            ; Object variable to hold the OLE Acrobat Document instance.
Local $AcrobatJSO = ""              ; Object variable to hold the OLE Acrobat JSO instance.

Local $PaperPageCount = ""      ; Variable to hold the total number of regular paper pages in Paperwork.pdf.
Local $TagPageCount = ""            ; Variable to hold the total number of tag stock pages in Tags.pdf.

Local $APDFTxtExtractPID = ""   ; Holds the process ID for the A-PDF Text Extractor program - mostly used to close after use.
Local $AcroPID = ""                 ; Holds the process ID for Adobe Acrobat manipulation.

Local $oExcelApp = ""                   ; Object variable to hold an instance of the Microsoft Excel Application.
Local $oExcelBook = ""              ; Object variable to hold a Microsoft Excel Workbook object.

Local $hWnd = ""                        ; Stores the handle for window - used primarily for proper navigation of tabs on a BCC form.
Local $hBCCWnd = ""                 ; Stores the handle of the BCC main program window.
Local $hBCCBGWnd = ""           ; Stores the handle of the BCC Background Window.
Local $hAutoItWnd = ""              ; Stores the handle of the AutoIt - SciTE program window.

Local $sPrevValue = ""              ; Temporary string variable to hold previous values for comparison.
Local $sTempText = ""               ; Temporary string variable to hold various text.
#EndRegion

; SCRIPT INITIALIZATION
#Region
;Ensure that BCC Mail Manager is up and running.
If WinExists("BCC Mail Manager FS Network - ADMIN") = 0 Then
    MsgBox(0, "Fatal Error", "BCC Mail Manager Application is not currently running - existing script!")
    Exit
EndIf

;Closes the Acrobat process if it is currently open.
If ProcessExists("Acrobat.exe") Then
    ProcessClose("Acrobat.exe")
    ProcessWaitClose("Acrobat.exe")
EndIf

;Ensure BCC is not minimized and has focus.
WinSetState("BCC Mail Manager FS Network - ADMIN", "", @SW_RESTORE)
WinActivate("BCC Mail Manager FS Network - ADMIN")

;Stores window handles relating to AutoIt and BCC
Opt("WinTitleMatchMode", 3)
$hBCCBGWnd = WinGetHandle("BCC Mail Manager FS")
Opt("WinTitleMatchMode", 2)
$hAutoItWnd = WinGetHandle(".au3")
Opt("WinTitleMatchMode", 1)
$hBCCWnd = WinGetHandle("BCC Mail Manager FS Network - ADMIN")


;Create Event Log File if one does not exist for the current day.
$arrDateParts = StringSplit(_NowDate(), "/", 2)

$sLogDate = StringFormat("%02s", $arrDateParts[0]) & "-" & StringFormat("%02s", $arrDateParts[1]) & "-" & StringRight($arrDateParts[2], 2)
$sLogName = $sLogDate & ".log"

If FileExists($dirEventLog & "\" & $sLogName) = 0 Then
    $hFileOpen = FileOpen($dirEventLog & "\" & $sLogName, 1)

    ;Write first entry in the log stating that the log was created
    WriteToEventLog("NEW LOG", "Daily Event log created....", "Success")

    FileClose($hFileOpen)
    $hFileOpen = ""
EndIf

#EndRegion

; PERMIT TABLE INITIALIZATION
#Region
;Activates the BCC Windows
WinActivate("BCC Mail Manager FS Network - ADMIN")
Sleep($microDelay)
;Activates the "Postal" menu and access a standard mail form to allow access to the permit table.
Send("!p")
Sleep($microDelay)
Send("n")
Sleep($microDelay)
Send("1")
;ALTERNATE METHOD TO THE ABOVE:   Clicks the "Postal" menu option. (Obsolete).
;MouseClick("left", 235, 38, 1, 0 )
;Sleep($microDelay)
;MouseClick("left", 235, 285, 1, 0 )
;Sleep($microDelay)
;MouseClick("left", 533, 285, 1, 0 )

WinWait("PS Form 3602-R", "Change Permit")

Do
    
    WinActivate("PS Form 3602-R", "Change Permit")
    ControlClick("PS Form 3602-R", "Change Permit", "[CLASS:TButton; TEXT:Change Permit]")
    Sleep($shortDelay)
    
    If WinActive("BCC Mail Manager FS", "Borland Database Engine error") <> 0 Then
        $WaitingFlag = True
        
        WinActivate("BCC Mail Manager FS", "Borland Database Engine error")
        Sleep($shortDelay)
        Send("{enter}")
        
        ;Pauses, then re-attempts to access the permit
        Sleep($mediumDelay)
    Else
        $WaitingFlag = False
    EndIf
    
Until $WaitingFlag = False

WinWait("Select a Permit", "&Modify")
WinActivate("Select a Permit", "&Modify")
ControlClick("Select a Permit", "&Modify", "[CLASS:TBitBtn; TEXT:&Modify]")

WinWaitActive("Permit Information", "PreparedPanel")

;Remove old instance of "PermitTableExport.txt" before creating the new file.
If FileExists($dirPermitTableExport & "\PermitTableExport.txt") Then
    FileDelete($dirPermitTableExport & "\PermitTableExport.txt")
EndIf

Run("C:\Program Files (x86)\NirSoft\SysExporter\sysexp.exe")
WinWaitActive("SysExporter", "item(s)")
WinMove("SysExporter", "item(s)",1270, 410, 400, 600)
WinActivate("SysExporter", "item(s)")

Opt("MouseCoordMode", 0)
MouseClickDrag("left", 27, 60, -445, 113, 5)
Opt("MouseCoordMode", 1)

WinActivate("SysExporter")
Send("^e")
WinWaitActive("Select a filename to save", "")
ControlSetText("Select a filename to save", "&Save", "[CLASS:Edit; INSTANCE:1]", $dirPermitTableExport & "\PermitTableExport")
ControlClick("Select a filename to save", "&Save", "[CLASS:Button; TEXT:&Save]", "left", 1)
Sleep($shortDelay)

If WinExists("Confirm Save As", "&Yes") Then
    WinActivate("Confirm Save As", "&Yes")
    ControlClick("Confirm Save As", "&Yes", "[CLASS:Button; TEXT:&Yes]", "left", "1")
    Sleep($microDelay)
EndIf

;Cancel out of the windows I opened in BCC to get at the permit table.
WinActivate("Permit Information", "PreparedPanel")
Sleep($microDelay)
Send("!c")
Sleep($microDelay)
Send("!c")
Sleep($microDelay)
Send("!c")
Sleep($microDelay)
WinClose("SysExporter")

;Ensure that the permit table export file exists before proceeding.
If FileExists($dirPermitTableExport & "\PermitTableExport.txt") = 0 Then
    MsgBox(0, "Fatal Error", "Could not locate PermitTableExport.txt in the permit table export folder; exiting script!")
    Exit
EndIf

;Convert the permit table text extraction to a csv file containing just the company field and the identifier field.
ConvertPermitTextToCSV()

;Store the contents of Permit.csv in a string.  Each job will access this string for searching purposes.
$hFileOpen = FileOpen($dirPermitTableExport & "\Permit.csv")
$sPermitCSV = FileRead($hFileOpen)
FileClose($hFileOpen)

#EndRegion

; BATCH INITIALIZATION
#Region
;Tests job ticket folder to ensure there are tickets to process.
$jobTicketArray = _FileListToArray($dirJobTickets,"*.pdf")
If @error Then
    MsgBox(0,"Fatal Error","Could not locate job ticket PDFs in the folder; exiting script!")
    Exit
EndIf

$APDFTxtExtractPID = ShellExecute("C:\Program Files (x86)\A-PDF Text Extractor\PdfTE.exe")

;Loops through each job ticket PDF and uses A-PDF Text Extractor to extract to a text file..
For $Counter = 1 To $jobTicketArray[0] 

    ;For ease-of-use, places the path to the text file in a variable.
    $sTempText = StringReplace($dirJobTickets & "\" & $jobTicketArray[$Counter], ".pdf", ".txt")
    
    If FileExists($sTempText) Then FileDelete($sTempText)
    
    ;Open job ticket PDF and extract text
    WinWaitActive("A-PDF Text Extractor")
    Send("!o")
    WinWaitActive("Open", "PDF File")
    ControlSetText("Open", "PDF File", "[CLASS:Edit; INSTANCE:1]", $dirJobTickets & "\" & $jobTicketArray[$Counter])
    Sleep($microDelay)
    ControlClick("Open", "&Open", "[CLASS:Button; TEXT:&Open]", "left", 1)
    WinWaitActive("A-PDF Text Extractor")
    Send("!e")
    WinWaitActive("Save As", "&Save")
    ControlSetText("Save As", "&Save", "[CLASS:Edit; TEXT:&Save]", $sTempText )
    Sleep($microDelay)
    ControlClick("Save As", "&Save", "[CLASS:Button; TEXT:&Save]", "left", 1)
    WinWaitActive("A-PDF Text Extractor", "open the destination file?")
    ControlClick("A-PDF Text Extractor", "open the destination file?", "[CLASS:Button; TEXT:&No]", "left", 1)

    ;Set the waiting flag =  true before test loop
    $WaitingFlag = True
    
    ;Tests that Acrobat has written the file and the file is not empty before moving forward.
    Do
        If FileExists($sTempText) And FileGetSize($sTempText) = 0 Then
            Sleep($shortDelay)
        Else
            $WaitingFlag = False
        EndIf
    Until $WaitingFlag = False

Next

Sleep($shortDelay)
;Close the A-PDF Text Extractor Process
ProcessClose($APDFTxtExtractPID)
ProcessWaitClose($APDFTxtExtractPID)

;Read the job ticket text output to gather data.  This array's size in element 0 will determine the batch loop count.
$jobTicketTextArray = _FileListToArray($dirJobTickets,"*.txt")
If @error Then
    MsgBox(0,"Fatal Error","Could not locate job ticket TXTs in the folder; exiting script!")
    Exit
EndIf

#EndRegion

; BATCH PROCESSING LOOP
#Region

For $iCountJobs = 1 To $jobTicketTextArray[0]

    ;Write Event Log Entry for start of job processing.
    WriteToEventLog(StringStripWS(StringLeft($jobTicketTextArray[$iCountJobs], 5), $STR_STRIPTRAILING), "Beginning to process job...", "Start")
    
    ;Initialize current job.
    $hFileOpen = FileOpen($dirJobTickets & "\" & $jobTicketTextArray[$iCountJobs])
    Sleep($shortDelay)
    $sFileRead = FileRead($hFileOpen)
    Sleep($shortDelay)

    FileClose($hFileOpen)
    
    ;Delete the job ticket text document now that it is stored in a string variable (leaves the original PDF).
    FileDelete($dirJobTickets & "\" & $jobTicketTextArray[$iCountJobs])
    Sleep($microDelay)

    ;Finds and stores the job number from the job ticket.
    If StringRegExp($sFileRead, "Job\s(\d{4}\d?)") Then
        $arrRegExFound = StringRegExp($sFileRead, "Job\s(\d{4}\d?)", 1)
        $JobNum = $arrRegExFound[0]
    Else
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog(StringStripWS(StringLeft($jobTicketTextArray[$iCountJobs], 5), $STR_STRIPTRAILING), "The Job Number RegEx failed to match...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop
    EndIf

    ;Finds and stores the Grande ID from the job ticket.  When two IDs are present, this is a parent/child relationship,
    ;and we need to use the second ID, the child.
    ;NOTE: An ID placed in the Shipping section of the ticket can affect this.
    ;Updated 01-27-2015 - Previous RegEx used was ID\s?#\s?(\w\d\w\d{6})
    If StringRegExp($sFileRead, "([a-zA-Z]\d[a-zA-Z]\d{6})") Then
        $arrRegExFound = StringRegExp($sFileRead, "([a-zA-Z]\d[a-zA-Z]\d{6})", 3)
        If UBound($arrRegExFound) > 1 Then
            $GrandeID = $arrRegExFound[1]
        Else
            $GrandeID = $arrRegExFound[0]
        EndIf
    Else
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The Grande ID RegEx failed to match...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop        
    EndIf
    
    ;This block searches the string data from Permit.csv to ensure that a permit can be associated with the job.
    If StringRegExp($sPermitCSV, """(.*)"",""" & $GrandeID & """") Then
        $arrRegExFound = StringRegExp($sPermitCSV, """(.*)"",""" & $GrandeID & """", 1)
        $PermitNameFind = $arrRegExFound[0]
    Else
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The permit name could not be located in Permit.csv based on Grande ID...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop    
    EndIf

    ;Finds and stores the Mail Date from the job ticket.
    If StringRegExp($sFileRead, "Due\sDate:\s*(\d+\/\d+\/\d{4})") Then
        $arrRegExFound = StringRegExp($sFileRead, "Due\sDate:\s*(\d+\/\d+\/\d{4})", 1)
        $MailDate = $arrRegExFound[0]
    Else
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The Mailing Date RegEx failed to match...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop    
    EndIf
    
    ;Converts the Mail Date to mm.dd.yy format for the Mail.dat output folder name.
    $arrDateParts = StringSplit($MailDate, "/", 2)
    $MailDateFormatted = StringFormat("%02s", $arrDateParts[0]) & "." & StringFormat("%02s", $arrDateParts[1]) & "." & StringRight($arrDateParts[2], 2)
    
    ;REMOVE AT PRODUCTION TIME - Sets $MailDateFormatted to "Script_Test"
    $MailDateFormatted = "Script_Test"

    ;Finds and stores the piece count from the job ticket.
    If StringRegExp($sFileRead, "ONLY\s+(\S+)\s+MA") Then
        $arrRegExFound = StringRegExp($sFileRead, "ONLY\s+(\S+)\s+MA", 1)
        $PieceCount = StringReplace(StringStripWS($arrRegExFound[0], $STR_STRIPTRAILING), ",", "")
    Else
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The Piece Count RegEx failed to match...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop
    EndIf

    ;Finds and stores the beginning quantity from the job ticket.
    If StringRegExp($sFileRead, "Quantity:\s*(\d*,?\d+)") Then
        $arrRegExFound = StringRegExp($sFileRead, "Quantity:\s*(\d*,?\d+)", 1)
        $BeginningQty = $arrRegExFound[0]
    Else
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The Beginning Quantity RegEx failed to match...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop
    EndIf

    ;Finds and stores the piece type (Letter or Flat) from the job ticket.
    If StringRegExp($sFileRead, "MAILING:\s(\w*)") Then
        $arrRegExFound = StringRegExp($sFileRead, "MAILING:\s(\w*)", 1)
        $PieceType = $arrRegExFound[0]
    Else
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The Piece Type RegEx failed to match...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop
    EndIf
    
    ;Finds and stores the piece height dimension from the job ticket specs.
    If StringRegExp($sFileRead, "HEIGHT:\s?(.*)") Then
        $arrRegExFound = StringRegExp($sFileRead, "HEIGHT:\s?(.*)", 1)
        $TicketPieceHeight = StringStripWS($arrRegExFound[0], $STR_STRIPTRAILING)
    Else
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The Piece Height Dimension RegEx failed to match...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop
    EndIf
    
    ;Finds and stores the piece width dimension from the job ticket specs.
    If StringRegExp($sFileRead, "WIDTH:\s?(.*)") Then
        $arrRegExFound = StringRegExp($sFileRead, "WIDTH:\s?(.*)", 1)
        $TicketPieceWidth = StringStripWS($arrRegExFound[0], $STR_STRIPTRAILING)
    Else
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The Piece Width Dimension RegEx failed to match...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop
    EndIf
    
    ;In BCC the largest of the two dimensions in the ticket (height and width) go in the length field
    ;and the smaller of the two goes in the height field. This next section compares and assigns to variables.
    If Number($TicketPieceHeight) > Number($TicketPieceWidth) Then
        $PieceLength = $TicketPieceHeight
        $PieceHeight = $TicketPieceWidth
    Else
        $PieceLength = $TicketPieceWidth
        $PieceHeight = $TicketPieceHeight
    EndIf
    
    ;Finds and stores the sample quantity from the job ticket specs.
    If StringRegExp($sFileRead, "\#\sOF\sSAMPLES:\s?(.*)") Then
        $arrRegExFound = StringRegExp($sFileRead, "\#\sOF\sSAMPLES:\s?(.*)", 1)
        $PieceSampleQty = StringStripWS($arrRegExFound[0], $STR_STRIPTRAILING)
    Else
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The Sample Quantity RegEx failed to match...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop
    EndIf

    ;Finds and stores the piece thickness (for the given sample size) from the job ticket specs.
    If StringRegExp($sFileRead, "THICKNESS:\s?(.*)") Then
        $arrRegExFound = StringRegExp($sFileRead, "THICKNESS:\s?(.*)", 1)
        $PieceThickness = StringReplace(StringStripWS($arrRegExFound[0], $STR_STRIPTRAILING), """", "")
    Else
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The Piece Thickness RegEx failed to match...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop
    EndIf

    ;Finds and stores the piece weight (for the given sample size) from the job ticket specs.
    If StringRegExp($sFileRead, "WEIGHT.*?\:\s?(\d*?\.\d*)") Then
        $arrRegExFound = StringRegExp($sFileRead, "WEIGHT.*?\:\s?(\d*?\.\d*)", 1)
        $PieceWeight = StringStripWS($arrRegExFound[0], $STR_STRIPTRAILING)
    Else
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The Piece Weight RegEx failed to match...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop
    EndIf

        ;Finds and stores line 1 of the entry office address from the job ticket.
    If StringRegExp($sFileRead, "Federal Express\s*(.+?(?=   ))") Then
        $arrRegExFound = StringRegExp($sFileRead, "Federal Express\s*(.+?(?=   ))", 1)
        $EntryOfficeLine1 = $arrRegExFound[0]
    ElseIf StringRegExp($sFileRead, "United Parcel\s*(.+?(?=   ))") Then
        $arrRegExFound = StringRegExp($sFileRead, "United Parcel\s*(.+?(?=   ))", 1)
        $EntryOfficeLine1 = $arrRegExFound[0]
    Else
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The Entry Office Line 1 RegEx failed to match...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop
    EndIf

    ;Finds and stores line 2 of the entry office address from the job ticket.
    If StringRegExp($sFileRead, "Federal Express\s*.*\s*(.+?(?=   ))") Then
        $arrRegExFound = StringRegExp($sFileRead, "Federal Express\s*.*\s*(.+?(?=   ))", 1)
        $EntryOfficeLine2 = StringStripWS($arrRegExFound[0], $STR_STRIPTRAILING)
    ElseIf StringRegExp($sFileRead, "United Parcel\s*.*\s*(.+?(?=   ))") Then
        $arrRegExFound = StringRegExp($sFileRead, "United Parcel\s*.*\s*(.+?(?=   ))", 1)
        $EntryOfficeLine2 = StringStripWS($arrRegExFound[0], $STR_STRIPTRAILING)
    Else
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The Entry Office Line 2 RegEx failed to match...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop
    EndIf

    ;Finds and stores line 3 of the entry office address from the job ticket.
    ;Previously used RegEx "Federal Express[^.]+\s(\w+\,\s\w{2}\s\d{5}\-\d{4})" but it had issues with multi-word cities.
    ;When assigned to $EntryOfficeLine3 leading and trailing whitespace is removed using the value 3 in the second parameter.
    If StringRegExp($sFileRead, "(?m)Federal Express[^.]+(^.*,\s\w{2}\s\d{5}\-\d{4})") Then
        $arrRegExFound = StringRegExp($sFileRead, "(?m)Federal Express[^.]+(^.*,\s\w{2}\s\d{5}\-\d{4})", 1)
        $EntryOfficeLine3 = StringStripWS($arrRegExFound[0], 3)
    ElseIf StringRegExp($sFileRead, "(?m)United Parcel[^.]+(^.*,\s\w{2}\s\d{5}\-\d{4})") Then
        $arrRegExFound = StringRegExp($sFileRead, "(?m)United Parcel[^.]+(^.*,\s\w{2}\s\d{5}\-\d{4})", 1)
        $EntryOfficeLine3 = StringStripWS($arrRegExFound[0], 3)
    Else
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The Entry Office Line 3 RegEx failed to match...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop
    EndIf

    ;Finds and stores the entry office phone number from the job ticket.
    If StringRegExp($sFileRead, "Federal Express[^.]+\s(\d{3}\-\d{3}\-\d{4})") Then
        $arrRegExFound = StringRegExp($sFileRead, "Federal Express[^.]+\s(\d{3}\-\d{3}\-\d{4})", 1)
        $EntryOfficePhone = StringReplace(StringStripWS($arrRegExFound[0], $STR_STRIPTRAILING), "-", "")
    ElseIf StringRegExp($sFileRead, "United Parcel[^.]+\s(\d{3}\-\d{3}\-\d{4})") Then
        $arrRegExFound = StringRegExp($sFileRead, "United Parcel[^.]+\s(\d{3}\-\d{3}\-\d{4})", 1)
        $EntryOfficePhone = StringReplace(StringStripWS($arrRegExFound[0], $STR_STRIPTRAILING), "-", "")
    Else
        $EntryOfficePhone = ""  
    EndIf

    ;This block finds and stores the customer folder path (and folder name) based on GrandeID
    $folderArray = _FileListToArray($dirGCMaps, "*" & $GrandeID & "*", 2)
    If @error Then
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The customer folder path could not be located by Grande ID...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop
    Else
        $CustFolder = $folderArray[1]
        $arrRegExFound = StringRegExp($folderArray[1], "(.*)\s+?\(*?\w\d\w\d{6}", 1)
        ;Store Pizza Place name based on folder name in Grande Cheese Maps.
        ;The Grande ID is removed and "-", "(", ")", "_", "," chars are removed or replaced with spaces as needed.
        ;The flag '7' at the end is three flags in one:  trim leading space, trim trailing, trim double spaces between words to a single space)
        $PizzaPlace = StringStripWS(StringReplace(StringReplace(StringReplace(StringReplace(StringReplace(String($arrRegExFound[0]), "-", " "), "_", " "), "(", ""), ")", ""), ",", " "), 7)
    EndIf

    ;This block finds and stores the job folder path (and name) based on Job#
    $folderArray = _FileListToArray($dirGCMaps & "\" & $CustFolder, "*" & $JobNum & "*", 2)
    If @error Then
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The Job Folder Path could not be found with Job#" & $JobNum & "...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop
    Else
        $JobFolder = $folderArray[1]
    EndIf
    
    ;This block finds and stores the customer prebill folder name based on GrandeID.
    $folderArray = _FileListToArray($dirGrandePrebill, "*" & $GrandeID & "*", 2)
    If @error Then
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The Customer Prebill Folder could not be located using Grande ID " & $GrandeID & "...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop
    Else
        $PrebillFolder = $folderArray[1]
    EndIf
    
    ;This block finds and stores the customer prebill file name based on Job Number.
    $folderArray = _FileListToArray($dirGrandePrebill & "\" & $PrebillFolder, "*" & $JobNum & "*.xls", 1)
    If @error Then
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The Customer Prebill File could not be located using the Job Number. " & $GrandeID & "...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop
    Else
        $PrebillFile = $folderArray[1]
    EndIf

    ;Constructs the full path to the job folder for ease of reference
    $fullJobPath = $dirGCMaps & "\" & $CustFolder & "\" & $JobFolder

    ;This block finds and stores the list file name based on regular expression:   [Q]\d{6}\.[t][x][t]
    ;This RegExp defines the pattern format of the valassis-purchased lists.
    $folderArray = _FileListToArray($fullJobPath, "*.txt", 1)
    If @error Then
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The list file could not be located within the job folder...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop
    Else
        For $vElement In $folderArray
            If StringRegExp($vElement, "[Q]\d{6}\.[t][x][t]") Then $listFile = $vElement
        Next
    EndIf
    
    ;This block tests the line count of the list file to the expected quantity in the job ticket.
    If (_FileCountLines($fullJobPath & "\" & $listFile) - 1) <> $PieceCount Then
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The list file quantity does not match the expected piece count from the ticket...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        ;CloseAllJobWindows()
        ContinueLoop
    EndIf

    ; PROCESS JOB IN BCC
    #Region
    ;Activates the BCC Windows
    WinActivate("BCC Mail Manager FS Network - ADMIN")
    Sleep($shortDelay)
    ;Clicks the "New List" button.
    ControlClick("BCC Mail Manager", "", "[CLASS:TToolBar; INSTANCE:3]", "left" , 1, 10, 15)
    Sleep($shortDelay)

    ;Clicks the "Use Template..." option and finds the Grande Non-Auto template.
    send("{down}{down}{enter}")
    Sleep($microDelay)
    send("Grande Non-Auto")
    Sleep($shortDelay)
    ControlClick("Choose Template", "&OK", "[CLASS:TBitBtn; TEXT:&OK]", "left", 1)

    ;NOW:  This section will need variable input for the job# and pizza place name
    ;      BUT for now I'm having it overwrite a test DB
    WinWaitActive("Save New List As")
    Sleep($microDelay)
    ControlSetText("Save New List As", "&Save", "[CLASS:Edit; INSTANCE:1]", $listName)
    ControlClick("Save New List As", "&Save", "[CLASS:Button; TEXT:&Save]", "left", 1)
    Sleep($shortDelay)

    ;If the we are re-running a job this checks to see if we are overwriting the list DBF.
    If WinExists("Confirm Save As") then
        WinActivate("Confirm Save As")
        ControlClick("Confirm Save As", "", "[CLASS:Button; INSTANCE:1]")
    EndIf

    ;Handles the saved BATCH index screen
    WinWaitActive("[CLASS:#32770]", "The following index is saved")
    ControlClick("[CLASS:#32770]", "The following index is saved", "[CLASS:Button; INSTANCE:1]")

    ;Play loading animation while the client communicates with the server.
    _StartLoadingAnimation()

    ;Wait for the new DBF layout screen to exist, then pause, then stop the loading animation.
    WinWait($listName, "")
    Sleep($shortDelay)
    _StopLoadingAnimation()
    Sleep($mediumDelay)

    ;Ensures that the BCC main program has not minimized
    WinSetState("BCC Mail Manager FS Network - ADMIN", "", @SW_RESTORE)
    Sleep($microDelay)
    
    ;Clicks the save button on the layout screen just prior to DBF creation
    WinActivate($listName, "No Records")
    Sleep($shortDelay)
    ControlClick($listName, "No Records", "[CLASS:TPanel; INSTANCE:2]", "left", 1, 45, 10)
    
    ;Error handling for cases where the control is not clicked properly.
    Do
        $hWnd = WinWait($listName, "&Help", 10)
        If $hWnd = 0 Then
            WinActivate($listName, "No Records")
            Sleep($shortDelay)
            ControlClick($listName, "No Records", "[CLASS:TPanel; INSTANCE:2]", "left", 1, 45, 10)
        EndIf
        Sleep($shortDelay)
    Until $hWnd <> 0

    ;Fills list name and initials
    WinActivate($listName, "&Help")
    Sleep($shortDelay)
    ControlSetText($listName, "&OK", "[CLASS:TOvcSimpleField; INSTANCE:1]", "XX")
    ControlClick($listName, "&OK", "[CLASS:TBitBtn; TEXT:&OK]", "left", 1)

    ;Handles list import
    WinWait("[CLASS:TMailList_Form]", "")
    Sleep($microDelay)
    WinActivate("[CLASS:TMailList_Form]", "")
    Sleep($microDelay)
    ControlClick("BCC Mail Manager", "", "[CLASS:TToolBar; INSTANCE:3]", "left" , 1, 115, 15)

    WinWait("Import Wizard", "Select Transfer Format")
    Sleep($microDelay)
    WinActivate("Import Wizard", "Select Transfer Format")
    Sleep($microDelay)
    
    ;Infinite loop structure to find the and select the correct import transfer format.
    While 1
        ;Uses 'Tab' to highlight the first item and sends 'Enter' to trigger a selection of the text and '^c' to copy to cliboard.
        Send("{TAB}")
        Sleep($microDelay)
        Send("{ENTER}")
        Sleep($microDelay)
        Send("^c")
        Sleep($microDelay)
                                                                                                                                                                                                                                                                                                                                                                                                                                
        $sTempText = ClipGet()
        Sleep($microDelay)
        
        If $sTempText = "Grande Non-Auto Import" Then
            ;When the appropriate item is found, we click the modify button to advance.
            ControlClick("Import Wizard", "", "[CLASS:TBitBtn; TEXT:&Modify]")
            Sleep($microDelay)
            ExitLoop
        ElseIf $sTempText = $sPrevValue Then
            ;If the previous item now matches the current item it means we are at the bottom of the list and
            ;the appropriate item was not found.  In this case, processing cannot continue.
            ControlClick("Import Wizard", "", "[CLASS:TBitBtn; TEXT:&Cancel]")
            MsgBox(0, "Fatal Error", "Cannot locate ""Grande Non-Auto Import"" transfer format - Exiting Script!")
            Exit        
        EndIf
        
        ;Temporarily store the previous selection.
        $sPrevValue = $sTempText
        
        Send("{ENTER}")
        Sleep($microDelay)
    WEnd

    ;Error handling code to re-click the "Modify" button if the initial click does not register.
    Do
        $hWnd = WinWait("Import Wizard", "Source and Destination Files", 10)
        If $hWnd = 0 Then
            WinActivate("Import Wizard", "Select Transfer Format")
            Sleep($microDelay)
            ControlClick("Import Wizard", "", "[CLASS:TBitBtn; TEXT:&Modify]")
        EndIf
        Sleep($shortDelay)
    Until $hWnd <> 0
    
    WinActivate("Import Wizard", "Source and Destination Files")
    Sleep($microDelay)
    ControlClick("Import Wizard","Source and Destination Files", "[CLASS:TBitBtn; TEXT:Browse]")

    WinWaitActive("Open Delimited file", "&Open")
    Sleep($microDelay)
    ControlSetText("Open Delimited file", "&Open", "[CLASS:Edit; INSTANCE:1]", $fullJobPath & "\" & $listFile)
    ControlClick("Open Delimited file", "&Open", "[CLASS:Button; TEXT:&Open]")
    Sleep($microDelay)

    WinWaitActive("Import Wizard", "&Next")
    ControlClick("Import Wizard", "", "[CLASS:TBitBtn; TEXT:&Next]")

    WinWaitActive("Import Delimited File", "&Import")
    ControlClick("Import Delimited File", "", "[CLASS:TBitBtn; TEXT:&Import]")

    WinWaitActive("Save Procedure Information", "&Don't Save")
    ControlClick("Save Procedure Information", "", "[CLASS:TButton; TEXT:&Don't Save]")

    WinWaitActive("Import Status", "&OK")
    ControlClick("Import Status", "", "[CLASS:TBitBtn; TEXT:&OK]")

    Sleep($mediumDelay)
    WinActivate("BCC Mail Manager FS Network - ADMIN", "")
    Sleep($mediumDelay)
    Send("^d")

    ;This section creates a distribution report after changing some of the settings and setting the job folder path
    WinWaitActive("Distribution Report", "")
    ControlClick("Distribution Report", "Options", "[CLASS:TButton; TEXT:Options]")

    Sleep($shortDelay)
    WinWaitActive("Distribution Report Options", "")
    ControlClick("Distribution Report Options", "", "[CLASS:TCheckBox; TEXT:Omit Header && Pagination]")
    ControlClick("Distribution Report Options", "", "[CLASS:TCheckBox; TEXT:Don't Print Total Records at end of report]")
    ControlClick("Distribution Report Options", "", "[CLASS:TBitBtn; TEXT:&OK]")

    sleep($shortDelay)
    WinWaitActive("Distribution Report", "")
    $hWnd = ControlGetHandle("Distribution Report", "", "[CLASS:TPageControl; INSTANCE:1]")
    _GUICtrlTab_ClickTab($hWnd, _GUICtrlTab_FindTab($hWnd, "Print Setup"))


    ControlClick("Distribution Report", "", "[CLASS:TRadioButton; TEXT:Print to file]")
    ControlClick("Distribution Report", "", "[CLASS:TRadioButton; TEXT:Text File]")
    Sleep($shortDelay)
    ControlSetText("Distribution Report", "", "[CLASS:TEdit; INSTANCE:4]", $fullJobPath & "\DistRep.txt")
    Sleep($shortDelay)
    ControlClick("Distribution Report", "", "[CLASS:TBitBtn; TEXT:&Begin]")

    WinWaitActive("Save Procedure Information", "")
    ControlClick("Save Procedure Information", "", "[CLASS:TButton; TEXT:&Don't Save]")
    
    Sleep($mediumDelay)
    ;If we are re-running a job this handles the overwrite warning for the distribution report.
    If WinExists ("BCC Mail Manager FS", "&Overwrite") Then
        WinActivate("BCC Mail Manager FS", "&Overwrite")
        ControlClick("BCC Mail Manager FS", "&Overwrite", "[CLASS:Button; TEXT:&Overwrite]")
    EndIf
    Sleep($mediumDelay)
    
    ;Read the Distribution Report file and place the values found into an array
    If _FileReadToArray($fullJobPath & "\DistRep.txt", $arrZipCodes) Then

        _ArrayRemoveBlanks($arrZipCodes)
        
        ;This For Loop cleans the data (removes piece count for each unique zip code leaving just the zip codes)
        For $iCount = 1 to $arrZipCodes[0] - 1
            $arrZipCodes[$iCount] = StringLeft($arrZipCodes[$iCount], 5)
        Next

    Else
        ;Record event, copy ticket to Failed, reset variables, close job specific windows, and continue to next job.
        WriteToEventLog($JobNum, "The Distribution Report did not appear to contain any zip codes...", "FAIL")
        FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirFailedJobs & "\" & $jobTicketArray[$iCountJobs])
        InitializeVariables()
        CloseAllJobWindows()
        ContinueLoop
    EndIf

    Sleep($mediumDelay)
    WinActivate("BCC Mail Manager FS Network - ADMIN")
    Sleep($shortDelay)
    ;Clicks the "Presort" button.
    ControlClick("BCC Mail Manager", "", "[CLASS:TToolBar; INSTANCE:3]", "left" , 1, 390, 15)


    ;Load Saved Presort Settings
    Sleep($shortDelay)
    WinWaitActive("Mailing Presort Information", "Load")
    ControlClick("Mailing Presort Information", "Load", "[CLASS:TButton; TEXT:Load]")

    Sleep($shortDelay)
    WinWaitActive("List of Saved Presort Settings", "")
    ControlClick("List of Saved Presort Settings", "", "[CLASS:SysHeader32; INSTANCE:1]", "left", 1, 50, 8)
    Sleep($shortDelay)
    If StringLower($PieceType) <> "flat" Then
        Send("Grande - 1 Non-Auto{enter}")
    Else
        Send("Grande - 1 Non-Auto Flat{enter}")
    EndIf

    ;Permit Selection
    Sleep($shortDelay)
    WinWaitActive("Mailing Presort Information", "Permit...")
    ControlClick("Mailing Presort Information", "Permit...", "[CLASS:TButton; TEXT:Permit...]")
    Sleep($shortDelay)

    ;Saved presort settings are saved to permit 160 #1, so the down keys move to permit #160 #4 (my permit)
    WinWaitActive("Select a Permit", "&Modify")
    Sleep($shortDelay)
    Send("{down}")
    Sleep($microDelay)
    Send("{down}")
    Sleep($microDelay)
    Send("{down}")
    Sleep($microDelay)
    ControlClick("Select a Permit", "&Modify", "[CLASS:TBitBtn; TEXT:&Modify]")
    Sleep($mediumDelay) 
    
    WinActivate("Permit Information", "&Modfy")
    $hWnd = WinGetHandle("Permit Information", "")      ;For Pixel Search
    $arrPermitSize = WinGetPos($hWnd)                               ;For Pixel Search
    Sleep($shortDelay)

    Opt("MouseCoordMode", 0)
    MouseClick("left", 300, 120)
    MouseClick("left", 50, 240)
    Opt("MouseCoordMode", 1)

    Sleep($shortDelay)
    ;Permit name is found earlier based on the Grande ID in the identifier field.
    Send($PermitNameFind)
    Sleep($microDelay)
    
    ;Finds the selected permit's coordinates based on a pixel search for the blue selection color.
    $arrPermitPos = PixelSearch(50, 50, 51, $arrPermitSize[3], 0x3399FF,0,1,$hWnd)

    Opt("MouseCoordMode", 0)
    MouseClick("left", $arrPermitPos[0], $arrPermitPos[1], 2)
    Opt("MouseCoordMode", 1)

    Sleep($microDelay)
    Send("{ENTER}")
    
    Sleep($shortDelay)
    WinWaitActive("Select a Permit", "&Use")
    Sleep($shortDelay)
    ControlClick("Select a Permit", "&Use", "[CLASS:TBitBtn; TEXT:&Use]")

    WinWaitActive("Mailing Presort Information", "")
    Sleep($microDelay)
    
    ;Sets the piece specs (Weight, Sample Size, Thickness, Sample Size, Length, Width)
    ControlClick("Mailing Presort Information", "", "[CLASS:TOvcNumericField; INSTANCE:12]", "left", 2)
    Send($PieceWeight & "{TAB}")
    Sleep($microDelay)
    Send($PieceSampleQty & "{TAB}")
    Sleep($microDelay)
    ;The saved template lies to the program about the piece thickness stating .2499 when it would otherwise be .25.
    If $PieceThickness <> ".25" Then
        Send($PieceThickness & "{TAB}")
    Else
        Send("{TAB}")
    EndIf
    Sleep($microDelay)
    Send($PieceSampleQty & "{TAB}")
    Sleep($microDelay)
    Send($PieceLength & "{TAB}")
    Sleep($microDelay)
    Send($PieceHeight)
    Sleep($microDelay)
    
    ControlClick("Mailing Presort Information", "&OK", "[CLASS:TBitBtn; TEXT:&OK]")
    WinWaitActive("Warning", "&Yes")
    ControlClick("Warning", "&Yes", "[CLASS:TButton; TEXT:&Yes]")

    Sleep($microDelay)
    WinWaitActive("Possible Destination Sites", "&OK")
    Sleep($microDelay)

    _GUICtrlTab_ClickTab(ControlGetHandle("Possible Destination Sites", "", "[CLASS:TPageControl; INSTANCE:1]"), _GUICtrlTab_FindTab(ControlGetHandle("Possible Destination Sites", "", "[CLASS:TPageControl; INSTANCE:1]"), "DDU Destinations"))
    Sleep($microDelay)

    For $delDDUzips = 1 To 10
        ControlClick("Possible Destination Sites", "Delete", "[CLASS:TListBox; INSTANCE:1]", "left", 1, 15, 8)
        Sleep($microDelay)
        ControlClick("Possible Destination Sites", "Delete", "[CLASS:TBitBtn; TEXT:Delete]")
        Sleep($microDelay)
    Next

    For $populateZips = 1 To $arrZipCodes[0] - 1
        ControlSetText("Possible Destination Sites", "Delete", "[CLASS:TOvcSimpleField; INSTANCE:1]", $arrZipCodes[$populateZips])
        Sleep($microDelay)
    Next

    ControlClick("Possible Destination Sites", "&OK", "[CLASS:TBitBtn; TEXT:&OK]")

    WinWait($listName & " - Presort Summary",  "Select All")
    Sleep($shortDelay)
    WinActivate($listName & " - Presort Summary",  "Select All")
    Sleep($microDelay)

    Sleep($microDelay)
    ControlClick($listName & " - Presort Summary",  "Select All", "[CLASS:TToolBar; INSTANCE:1]", "left", 1, 245, 15)

    WinWait("Mail.dat", "Load saved Mail.dat")
    Sleep($shortDelay)
    WinActivate("Mail.dat", "Load saved Mail.dat")
    Sleep($shortDelay)

    ;If the "Load saved Mail.dat settings" check box is unchecked, then check it.
    If ControlCommand("Mail.dat", "Load saved Mail.dat", "[CLASS:TCheckBox; INSTANCE:2]", "IsChecked", "") = 0 Then
        ControlClick("Mail.dat", "Load saved Mail.dat", "[CLASS:TCheckBox; INSTANCE:2]")
    EndIf

    ;*****NOTE: For testing I am leaving the "Save Settings" box UNCHECKED!
    ;If the "Save Mail.dat settings" check box is checked, then UNcheck it.
    If ControlCommand("Mail.dat", "Save Mail.dat", "[CLASS:TCheckBox; INSTANCE:1]", "IsChecked", "") = 1 Then
        ControlClick("Mail.dat", "Save Mail.dat", "[CLASS:TCheckBox; INSTANCE:1]")
    EndIf

    ;USE THIS CODE WHEN IN PRODUCTION:
    ;If the "Save Mail.dat settings" check box is unchecked, then check it.
    ;If ControlCommand("Mail.dat", "Save Mail.dat", "[CLASS:TCheckBox; INSTANCE:1]", "IsChecked", "") = 0 Then
    ;   ControlClick("Mail.dat", "Save Mail.dat", "[CLASS:TCheckBox; INSTANCE:1]")
    ;EndIf
    ;*****END SAVE SETTINGS CHECK BOX SECTION

    ;If the current Mail.dat settings template is NOT "Grande Cheese", change it.
    If ControlGetText("Mail.dat", "Load saved Mail.dat", "[CLASS:TEdit; INSTANCE:1]") <> "Grande Cheese" Then
        ControlClick("Mail.dat", "Save Mail.dat", "[CLASS:TBitBtn; INSTANCE:1]")
        Sleep($microDelay)
        Send("{TAB}")
        Sleep($microDelay)
        Send("{TAB}")
        Sleep($microDelay)
        Send("Grande Cheese{ENTER}")
        Sleep($microDelay)
    EndIf

    ControlClick("Mail.dat", "&Next", "[CLASS:TBitBtn; TEXT:&Next]")
    Sleep($microDelay)
    ControlClick("Mail.dat", "&Next", "[CLASS:TBitBtn; TEXT:&Next]")
    Sleep($microDelay)
    ControlSetText("Mail.dat", "Job", "[CLASS:TEdit; INSTANCE:1]", $JobNum)
    Sleep($microDelay)
    ControlSetText("Mail.dat", "Job", "[CLASS:TEdit; INSTANCE:2]", $JobNum)
    Sleep($microDelay)
    ControlSetText("Mail.dat", "Job", "[CLASS:TMaskEdit; INSTANCE:6]", $MailDateFormatted)
    Sleep($microDelay)
    ControlSetText("Mail.dat", "Job", "[CLASS:TMaskEdit; INSTANCE:5]", "GC - " & $PizzaPlace)
    Sleep($microDelay)
    ControlClick("Mail.dat", "&Next", "[CLASS:TBitBtn; TEXT:&Next]")
    Sleep($microDelay)
    ControlClick("Mail.dat", "&Next", "[CLASS:TBitBtn; TEXT:&Next]")
    Sleep($microDelay)
    ControlClick("Mail.dat", "&Next", "[CLASS:TBitBtn; TEXT:&Next]")
    Sleep($microDelay)
    ControlClick("Mail.dat", "&Next", "[CLASS:TBitBtn; TEXT:&Next]")
    Sleep($microDelay)
    ControlClick("Mail.dat", "&Next", "[CLASS:TBitBtn; TEXT:&Next]")
    Sleep($microDelay)
    
    ;This section populates the 5 Mail Dates before moving forward.
    ControlClick("Mail.dat", "&Next", "[CLASS:TOvcPictureField; INSTANCE:8]", "left", 1)
    Send("{HOME}" & StringFormat("%02s", $arrDateParts[0]) & StringFormat("%02s", $arrDateParts[1]) & $arrDateParts[2])
    Sleep($microDelay)
    ControlClick("Mail.dat", "&Next", "[CLASS:TOvcPictureField; INSTANCE:3]", "left", 1)
    Send("{HOME}" & StringFormat("%02s", $arrDateParts[0]) & StringFormat("%02s", $arrDateParts[1]) & $arrDateParts[2])
    Sleep($microDelay)
    ControlClick("Mail.dat", "&Next", "[CLASS:TOvcPictureField; INSTANCE:17]", "left", 1)
    Send("{HOME}" & StringFormat("%02s", $arrDateParts[0]) & StringFormat("%02s", $arrDateParts[1]) & $arrDateParts[2])
    Sleep($microDelay)
    ControlClick("Mail.dat", "&Next", "[CLASS:TOvcPictureField; INSTANCE:15]", "left", 1)
    Send("{HOME}" & StringFormat("%02s", $arrDateParts[0]) & StringFormat("%02s", $arrDateParts[1]) & $arrDateParts[2])
    Sleep($microDelay)
    ControlClick("Mail.dat", "&Next", "[CLASS:TOvcPictureField; INSTANCE:4]", "left", 1)
    Send("{HOME}" & StringFormat("%02s", $arrDateParts[0]) & StringFormat("%02s", $arrDateParts[1]) & $arrDateParts[2])
    Sleep($microDelay)
    ControlClick("Mail.dat", "&Next", "[CLASS:TBitBtn; TEXT:&Next]")
    Sleep($microDelay)
    
    ControlClick("Mail.dat", "&Next", "[CLASS:TBitBtn; TEXT:&Next]")
    Sleep($microDelay)
    ControlClick("Mail.dat", "&Next", "[CLASS:TBitBtn; TEXT:&Next]")
    Sleep($microDelay)
    ControlClick("Mail.dat", "&Next", "[CLASS:TBitBtn; TEXT:&Next]")
    Sleep($microDelay)
    ControlClick("Mail.dat", "&Finish", "[CLASS:TBitBtn; TEXT:&Finish]")
    Sleep($microDelay)
    ;NOTE: In normal production we save and overwrite the Grande Mail.dat settings.  This might be the case during
    ;           automation as well.  It just depends on our needs.
    ;FINISHED WITH MAIL.DAT
    
    ;Return to Presort Menu
    WinWait($listName & " - Presort Summary",  "Select All")
    Sleep($shortDelay)
    WinActivate($listName & " - Presort Summary",  "Select All")
    Sleep($mediumDelay)

    ;Begin manipulating label screens to create output file (Code added to handle misfire where the sent keys don't register)
    ;Note: This portion relies on no labels being defined at run time as ctrl+alt+l normally opens the print labels section.
    Send("^!l")
    Do
        $hWnd = WinWait($listName & " - Labels", "&Use", 30)
        If $hWnd = 0 Then
                WinActivate($listName & " - Presort Summary",  "Select All")
                Sleep($microDelay)
                Send("^!l")
        EndIf
        Sleep($shortDelay)
    Until $hWnd <> 0
    WinActivate($listName & " - Labels", "&Use")
    Sleep($microDelay)
    Send("{DOWN}")
    Sleep($microDelay)
    ControlClick($listName & " - Labels", "&Use", "[CLASS:TBitBtn; TEXT:&Use]")
    WinWait("Label - Print To File", "&Save")
    Sleep($shortDelay)
    WinActivate("Label - Print To File", "&Save")
    Sleep($microDelay)

    ;Construct label output file name using format of 'jobnum_pizzaplace' after removing all white space and apostrophes
    $LabelOutputName = $JobNum & "_" & StringStripWS(StringReplace(StringReplace($PizzaPlace, "'", ""), ".", ""), $STR_STRIPALL)

    ;Set path and file name for output and click save.
    ControlSetText("Label - Print To File", "&Save", "[CLASS:Edit; INSTANCE:1]", $dirWideArray & "\" & $LabelOutputName)
    Sleep($microDelay)
    ControlClick("Label - Print To File", "&Save", "[CLASS:Button; TEXT:&Save]", "left", 1)
    Sleep($shortDelay)

    ;If we are re-running a job, this handles the overwrite warning for the output file.
    If WinExists("BCC Mail Manager FS", "&Overwrite") Then
        WinActivate("BCC Mail Manager FS", "&Overwrite")
        ControlClick("BCC Mail Manager FS", "&Overwrite", "[CLASS:Button; TEXT:&Overwrite]")
        Sleep($microDelay)
    EndIf

    ;Verify that finished job data does not already exist.  If it does, delete as the job is being redone.
    If FileExists($dirSuccessfulJobs & "\" & $JobNum) Then
        Sleep($microDelay)
        FileDelete($dirSuccessfulJobs & "\" & $JobNum)
        DirCreate($dirSuccessfulJobs & "\" & $JobNum)
    Else
        Sleep($microDelay)
        DirCreate($dirSuccessfulJobs & "\" & $JobNum)
    EndIf

    $AcroPID = ShellExecute("C:\Program Files (x86)\Adobe\Acrobat 11.0\Acrobat\Acrobat.exe","","","open",@SW_MINIMIZE)

    ;This line changes the manner in which window titles are matched.
    ;(Option 2 matches anywhere in the title rather than only from the start)
    Opt("WinTitleMatchMode", 2)

    ;Create Label Layout PDF
    WinWait($listName & " - Presort Summary",  "Select All")
    Sleep($microDelay)
    WinActivate($listName & " - Presort Summary",  "Select All")
    Send("^!b")
    WinWait("Preview - Label Layout Report", "")
    Sleep($shortDelay)
    WinActivate("Preview - Label Layout Report", "")
    Sleep($microDelay)
    Send("!p")
    WinWait("Label Layout Report - Print", "")
    Sleep($microDelay)
    WinActivate("Label Layout Report - Print", "")
    Sleep($microDelay)
    ControlCommand("Label Layout Report - Print", "", "[CLASS:TBccPrinterComboBox; INSTANCE:1]", "SetCurrentSelection", "Adobe PDF")
    Sleep($microDelay)
    Send("!u")
    Sleep($microDelay)
    Send("{ENTER}")
    WinWait("Save", "Label Layout Report.pdf")
    Sleep($microDelay)
    WinActivate("Save", "Label Layout Report.pdf")
    Sleep($microDelay)
    ControlSetText("Save", "Label Layout Report.pdf", "[CLASS:Edit; INSTANCE:1]", $dirSuccessfulJobs & "\" & $JobNum & "\Label Layout Report.pdf")
    ControlClick("Save", "Label Layout Report.pdf", "[CLASS:Button; TEXT:&Save]", "left", 1)

    ;Minimizes the resulting PDF
    WinWait("Label Layout Report.pdf - Adobe Acrobat", "AVUICommandWidget")
    Sleep($microDelay)
    WinActivate("Label Layout Report.pdf - Adobe Acrobat", "AVUICommandWidget")
    Sleep($microDelay)
    WinSetState("Label Layout Report.pdf - Adobe Acrobat", "AVUICommandWidget", @SW_MINIMIZE)
    Sleep($shortDelay)

    ;Creates the CR slips and prints them to PDF
    WinActivate($listName & " - Presort Summary",  "Select All")
    Sleep($shortDelay)
    Send("!p")
    Sleep($microDelay)
    Send("t")
    WinWait("Container Tag Options", "&Print")
    Sleep($microDelay)
    WinActivate("Container Tag Options", "&Print")
    Sleep($microDelay)
    Send("!r")
    ControlClick("Container Tag Options", "&Print", "[CLASS:TBitBtn; TEXT:&Print]", "left", 1)
    WinWait("Save", "Facing Slips.pdf")
    Sleep($microDelay)
    WinActivate("Save", "Facing Slips.pdf")
    Sleep($microDelay)
    ControlSetText("Save", "Facing Slips.pdf", "[CLASS:Edit; INSTANCE:1]", $dirSuccessfulJobs & "\" & $JobNum & "\Facing Slips.pdf")
    ControlClick("Save", "Facing Slips.pdf", "[CLASS:Button; TEXT:&Save]", "left", 1)

    ;Minimizes the resulting PDF
    WinWait("Facing Slips.pdf - Adobe Acrobat", "AVUICommandWidget")
    Sleep($microDelay)
    WinActivate("Facing Slips.pdf - Adobe Acrobat", "AVUICommandWidget")
    Sleep($microDelay)
    WinSetState("Facing Slips.pdf - Adobe Acrobat", "AVUICommandWidget", @SW_MINIMIZE)
    
    ;Copy the CR slips to the original job folder for record keeping (overwrites existing in case job is re-ran)
    FileCopy($dirSuccessfulJobs & "\" & $JobNum & "\Facing Slips.pdf", $fullJobPath & "\Facing Slips.pdf", 1)
    Sleep($shortDelay)

    ;Saves presort using generic name of "Grande Presort" so it can talk to the taskmaster
    WinActivate($listName & " - Presort Summary",  "Select All")
    Sleep($shortDelay)
    Send("+^s")
    WinWait("Saved Presort", "&OK")
    Sleep($shortDelay)
    WinActivate("Saved Presort", "&OK")
    Sleep($microDelay)
    ControlSetText("Saved Presort", "&OK", "[CLASS:TOvcSimpleField; INSTANCE:2]", "Grande Presort")
    ControlClick("Saved Presort", "&OK", "[CLASS:TBitBtn; TEXT:&OK]", "left", 1)

    ;TASKMASTER SECTION
    #Region
    WinActivate($listName,  "")
    Sleep($microDelay)
    Send("^!t")

    WinWait("TaskMaster Job List", "ToolBarJob")
    Sleep($microDelay)
    WinActivate("TaskMaster Job List", "ToolBarJob")
    Sleep($microDelay)
    Send("Grande Paperwork")
    Sleep($microDelay)
    Send("!f")
    Send("r")

    ;Handle 3602 Postage Statement.
    WinWait("TaskMaster Value Editor", "&OK")
    Sleep($microDelay)
    WinActivate("TaskMaster Value Editor", "&OK")
    Sleep($microDelay)
    
    ;Command: MAILID is equal to the Job Number.
    ControlSetText("TaskMaster Value Editor", "&OK", "[CLASS:Edit; INSTANCE:1]", $JobNum)
    ControlClick("TaskMaster Value Editor", "&OK", "[CLASS:TBitBtn; TEXT:&OK]", "left", 1)
    Sleep($shortDelay)

    WinWait("TaskMaster Value Editor", "&OK")
    Sleep($microDelay)
    WinActivate("TaskMaster Value Editor", "&OK")
    Sleep($microDelay)
    Send(StringReplace($MailDate, "/", "{RIGHT}"))
    ControlClick("TaskMaster Value Editor", "&OK", "[CLASS:TBitBtn; TEXT:&OK]", "left", 1)

    WinWait("Save", "PS Form 3602-R")
    Sleep($microDelay)
    WinActivate("Save", "PS Form 3602-R")
    Sleep($microDelay)
    ControlSetText("Save", "PS Form 3602-R", "[CLASS:Edit; INSTANCE:1]", $dirSuccessfulJobs & "\" & $JobNum & "\PS Form 3602-R.pdf")
    ControlClick("Save", "PS Form 3602-R", "[CLASS:Button; TEXT:&Save]", "left", 1)

    ;Minimizes the resulting PDF
    WinWait("PS Form 3602-R.pdf - Adobe Acrobat", "AVUICommandWidget")
    Sleep($microDelay)
    WinActivate("PS Form 3602-R.pdf - Adobe Acrobat", "AVUICommandWidget")
    Sleep($microDelay)
    WinSetState("PS Form 3602-R.pdf - Adobe Acrobat", "AVUICommandWidget", @SW_MINIMIZE)
    ;Copy the 3602 to the original job folder for record keeping (overwrites existing in case job is re-ran)
    FileCopy($dirSuccessfulJobs & "\" & $JobNum & "\" & $ControlText, $fullJobPath & "\PS Form 3602-R.pdf", 1)
    

    ;Start Handling 8125 - NOTE: This only handles single drop right now.
    ;Input Entry Office Address Line 1
    WinWait("TaskMaster Value Editor", "&OK")
    WinActivate("TaskMaster Value Editor", "&OK")
    Sleep($microDelay)
    ControlSetText("TaskMaster Value Editor", "&OK", "[CLASS:Edit; INSTANCE:1]", $EntryOfficeLine1)
    ControlClick("TaskMaster Value Editor", "&OK", "[CLASS:TBitBtn; TEXT:&OK]", "left", 1)
    Sleep($shortDelay)

    ;Input Entry Office Address Line 2
    WinWaitActive("TaskMaster Value Editor", "&OK")
    Sleep($microDelay)
    ControlSetText("TaskMaster Value Editor", "&OK", "[CLASS:Edit; INSTANCE:1]", $EntryOfficeLine2)
    ControlClick("TaskMaster Value Editor", "&OK", "[CLASS:TBitBtn; TEXT:&OK]", "left", 1)
    Sleep($shortDelay)

    ;Input Entry Office Address Line 3
    WinWaitActive("TaskMaster Value Editor", "&OK")
    Sleep($microDelay)
    ControlSetText("TaskMaster Value Editor", "&OK", "[CLASS:Edit; INSTANCE:1]", $EntryOfficeLine3)
    ControlClick("TaskMaster Value Editor", "&OK", "[CLASS:TBitBtn; TEXT:&OK]", "left", 1)
    Sleep($shortDelay)

    ;Input Entry Office Phone Number
    WinWaitActive("TaskMaster Value Editor", "&OK")
    Sleep($microDelay)
    If $EntryOfficePhone = "" Then
        ;Set phone number as default from destination table.   (Note: Sending "!n" would select "none")
        Send("!d")
        Sleep($microDelay)
    Else
        ;Set phone number using extracted text.
        ControlSetText("TaskMaster Value Editor", "&OK", "[CLASS:Edit; INSTANCE:1]", $EntryOfficePhone)
        Sleep($microDelay)
    EndIf
    ControlClick("TaskMaster Value Editor", "&OK", "[CLASS:TBitBtn; TEXT:&OK]", "left", 1)
    Sleep($microDelay)

    WinWait("Save", "PS Form 8125")
    Sleep($microDelay)
    WinActivate("Save", "PS Form 8125")
    Sleep($microDelay)
    ControlSetText("Save", "PS Form 8125", "[CLASS:Edit; INSTANCE:1]", $dirSuccessfulJobs & "\" & $JobNum & "\PS Form 8125.pdf")
    ControlClick("Save", "PS Form 8125", "[CLASS:Button; TEXT:&Save]", "left", 1)

    ;Minimizes the resulting PDF
    WinWait("PS Form 8125.pdf - Adobe Acrobat", "AVUICommandWidget")
    Sleep($microDelay)
    WinActivate("PS Form 8125.pdf - Adobe Acrobat", "AVUICommandWidget")
    Sleep($microDelay)
    WinSetState("PS Form 8125.pdf - Adobe Acrobat", "AVUICommandWidget", @SW_MINIMIZE)
    
    ;This block ignores additional 8125 pop-ups for jobs that go to a single destination but have multiple streams
    Do 
        If WinExists("Save", "PS Form 8125") Then
                WinActivate("Save", "PS Form 8125")
                Sleep($microDelay)
                ControlClick("Save", "PS Form 8125", "[CLASS:Button; TEXT:Cancel]", "left", 1)
                Sleep($microDelay)
        EndIf
    Until WinExists("Save", "Tray Tags")
    

    ;Handle Tray Tags
    WinWait("Save", "Tray Tags")
    Sleep($microDelay)
    WinActivate("Save", "Tray Tags")
    Sleep($microDelay)
    ControlSetText("Save", "Tray Tags", "[CLASS:Edit; INSTANCE:1]", $dirSuccessfulJobs & "\" & $JobNum & "\Tray Tags.pdf")
    ControlClick("Save", "Tray Tags", "[CLASS:Button; TEXT:&Save]", "left", 1)

    ;Minimize the resulting PDF
    WinWait("Tray Tags.pdf - Adobe Acrobat", "AVUICommandWidget")
    Sleep($microDelay)
    WinActivate("Tray Tags.pdf - Adobe Acrobat", "AVUICommandWidget")
    Sleep($microDelay)
    WinSetState("Tray Tags.pdf - Adobe Acrobat", "AVUICommandWidget", @SW_MINIMIZE)
    ;Copy the CR slips to the original job folder for record keeping (overwrites existing in case job is re-ran)
    FileCopy($dirSuccessfulJobs & "\" & $JobNum & "\" & $ControlText, $fullJobPath & "\Tray Tags.pdf", 1)
    

    ;Handle Presort Production Report
    WinWait("Save", "Presort Production Report")
    Sleep($microDelay)
    WinActivate("Save", "Presort Production Report")
    Sleep($microDelay)
    ControlSetText("Save", "Presort Production Report", "[CLASS:Edit; INSTANCE:1]", $dirSuccessfulJobs & "\" & $JobNum & "\Presort Production Report.pdf")
    ControlClick("Save", "Presort Production Report", "[CLASS:Button; TEXT:&Save]", "left", 1)

    ;Minimize the resulting PDF
    WinWait("Presort Production Report.pdf - Adobe Acrobat", "AVUICommandWidget")
    Sleep($microDelay)
    WinActivate("Presort Production Report.pdf - Adobe Acrobat", "AVUICommandWidget")
    Sleep($microDelay)
    WinSetState("Presort Production Report.pdf - Adobe Acrobat", "AVUICommandWidget", @SW_MINIMIZE)
    

    ;Handle Job Setup Report
    WinWait("Save", "Job Setup Report")
    Sleep($microDelay)
    WinActivate("Save", "Job Setup Report")
    Sleep($microDelay)
    ControlSetText("Save", "Job Setup Report", "[CLASS:Edit; INSTANCE:1]", $dirSuccessfulJobs & "\" & $JobNum & "\Job Setup Report.pdf")
    ControlClick("Save", "Job Setup Report", "[CLASS:Button; TEXT:&Save]", "left", 1)
    WinWait("Job Setup Report.pdf - Adobe Acrobat", "AVUICommandWidget")
    Sleep($shortDelay)
    
    ;Close the Adobe Acrobat Process.
    ProcessClose($AcroPID)
    ProcessWaitClose($AcroPID)

    ;Close Taskmaster window
    WinClose("TaskMaster Job List", "ToolBarJob")
    Sleep($microDelay)
    #EndRegion

    ;This line reverts the title matching to default which reads from the start only
    Opt("WinTitleMatchMode", 1)

    ;Close Job DBF
    WinClose($listName)
    #EndRegion

    ;PROCESS BACK-END PAPERWORK
    #Region
    ;Copy Job Ticket PDF to the Job Folder in _Successful.
    FileCopy($dirJobTickets & "\" & $jobTicketArray[$iCountJobs], $dirSuccessfulJobs & "\" & $JobNum & "\Job Ticket.pdf")
    
    ;Access the 8125 PDF and run the populate all fields javascript program.
    $AcrobatApp = ObjCreate("AcroExch.App")
    $AcrobatAVDoc = ObjCreate("AcroExch.AVDoc")                                                                         ; Connect to Ac Viewer
    $AcrobatAVDoc.Open($dirSuccessfulJobs & "\" & $JobNum & "\PS Form 8125.pdf", "")                ; Open a file into viewer
    $AcrobatPDDoc = $AcrobatAVDoc.GetPDDoc                                                                              ; Get the Doc opened in the viewer
    $AcrobatJSO = $AcrobatPDDoc.GetJSObject                                                                                 ; Connect to Acrobat JS
    
    $AcrobatJSO.AutoItPopulateAll8125Fields($PieceCount)
    Sleep($shortDelay)
    $AcrobatApp.CloseAllDocs
    $AcrobatApp.Exit
    
    ;Open the Job Ticket PDF from the successful folder in Acrobat and run the output file name adding program.
    $AcrobatApp = ObjCreate("AcroExch.App")
    $AcrobatAVDoc = ObjCreate("AcroExch.AVDoc")
    $AcrobatAVDoc.Open($dirSuccessfulJobs & "\" & $JobNum & "\Job Ticket.pdf", "")
    $AcrobatPDDoc = $AcrobatAVDoc.GetPDDoc
    $AcrobatJSO = $AcrobatPDDoc.GetJSObject
    
    $AcrobatJSO.AutoItAddOutputFilenameToJobTicket($LabelOutputName & ".csv")
    Sleep($shortDelay)
    $AcrobatApp.CloseAllDocs
    $AcrobatApp.Exit
    
    ;Open the Job Setup Report PDF from the successful folder in Acrobat and run the output file name adding program.
    $AcrobatApp = ObjCreate("AcroExch.App")
    $AcrobatAVDoc = ObjCreate("AcroExch.AVDoc")
    $AcrobatAVDoc.Open($dirSuccessfulJobs & "\" & $JobNum & "\Job Setup Report.pdf", "")
    $AcrobatPDDoc = $AcrobatAVDoc.GetPDDoc
    $AcrobatJSO = $AcrobatPDDoc.GetJSObject
    
    $AcrobatJSO.AutoItAddOutputFilenameToJobSetup($LabelOutputName & ".csv")
    Sleep($shortDelay)
    $AcrobatApp.CloseAllDocs
    $AcrobatApp.Exit
    
    ;Extract the first page of the 3602.
    $AcrobatApp = ObjCreate("AcroExch.App")
    $AcrobatAVDoc = ObjCreate("AcroExch.AVDoc")
    $AcrobatAVDoc.Open($dirSuccessfulJobs & "\" & $JobNum & "\PS Form 3602-R.pdf", "")
    $AcrobatPDDoc = $AcrobatAVDoc.GetPDDoc
    $AcrobatJSO = $AcrobatPDDoc.GetJSObject
    
    $AcrobatJSO.extractPages(0, 0, $dirSuccessfulJobs & "\" & $JobNum & "\3602 First Page.pdf")

    Sleep($shortDelay)
    $AcrobatApp.CloseAllDocs
    $AcrobatApp.Exit

    ;Closes the Acrobat process left behind from the OLE automation used to run the javascript programs.
    ProcessClose("Acrobat.exe")
    ProcessWaitClose("Acrobat.exe")
    
    ;Copy the 8125 to the original job folder for record keeping (overwrites existing in case job is re-ran)
    FileCopy($dirSuccessfulJobs & "\" & $JobNum & "\PS Form 8125.pdf", $fullJobPath & "\PS Form 8125.pdf", 1)
    
    ;Copy template files to job directory - FileCopy uses Flag 1 to overwrite if file exists.
    FileCopy($dirTemplateFiles & "\Grande Invoice Template.xls", $fullJobPath, 1)
    FileCopy($dirTemplateFiles & "\Weight Sheet Template.xls", $fullJobPath, 1)

    $oExcelApp = _Excel_Open(False)         ;False makes Excel invisible

    ;Registering the add-in as False and then True appears to be necessary.
    $oExcelApp.AddIns("Grandetools").Installed = False
    $oExcelApp.AddIns("Grandetools").Installed = True

    ;This Block captures the Prebill Subtotal amount from the prebill to be entered in the Grande Invoice.
    $oExcelBook = _Excel_BookOpen($oExcelApp, $dirGrandePrebill & "\" & $PrebillFolder & "\" & $PrebillFile)
    ;This line reads cell K19 from the prebill invoice.
    $PrebillSubTotal = _Excel_RangeRead($oExcelBook, Default, "K19")
    _Excel_BookClose($oExcelBook, False)

    ;This block opens the Grande Invoice and then runs the vba code modules needed to populate and submit.
    $oExcelBook = _Excel_BookOpen($oExcelApp, $fullJobPath & "\Grande Invoice Template.xls")
    Sleep($shortDelay)
    ;Run vba Import and Submit sub routines stored in the Grande Tools Add-in module "RunSilent" using variant parameters.
    $oExcelApp.Run("RunSilent.ImportToGrandeInvoice", $JobNum, $PizzaPlace, $BeginningQty, $PrebillSubTotal)
    $oExcelApp.Run("RunSilent.SubmitGrandeInvoice", $dirGrandeInvoice)
    _Excel_BookClose($oExcelBook, True)

    ;This block opens the Weight Sheet Template and then runs the vba code module needed to populate it.
    $oExcelBook = _Excel_BookOpen($oExcelApp, $fullJobPath & "\Weight Sheet Template.xls")
    Sleep($shortDelay)
    ;Run vba import sub routine stored in the Grande Tools Add-in module "RunSilent" using variant parameters.
    $oExcelApp.Run("RunSilent.ImportToWeightSheet", $JobNum, $PizzaPlace)
    Sleep($microDelay)
    _Excel_BookClose($oExcelBook, True)
    
    ;Copy the completed weight sheet file to the appropriate customer folder in the _Successful directory.
    FileCopy($fullJobPath & "\Weight Sheet Template.xls", $dirSuccessfulJobs & "\" & $JobNum & "\Weight Sheet.xls", 1)
    
    ;Copy the prebill document to the appropriate customer folder in the _Successful directory.
    FileCopy($dirGrandePrebill & "\" & $PrebillFolder & "\" & $PrebillFile, $dirSuccessfulJobs & "\" & $JobNum & "\Prebill.xls", 1)
    
    ;This block opens Prebill.xls located in _Successful, sets the print area, and saves it to PDF.
    $oExcelBook = _Excel_BookOpen($oExcelApp, $dirSuccessfulJobs & "\" & $JobNum & "\Prebill.xls")
    $oExcelBook.Application.Activesheet.PageSetup.Zoom = False
    $oExcelBook.Application.Activesheet.PageSetup.FitToPagesWide = 1
    $oExcelBook.Application.Activesheet.PageSetup.FitToPagesTall = 1
    _Excel_Export($oExcelApp, "A1:K55", $dirSuccessfulJobs & "\" & $JobNum & "\Prebill.pdf", $xlTypePDF)
    Sleep($microDelay)
    _Excel_BookClose($oExcelBook, True)
    
    ;This block opens Weight Sheet.xls located in _Successful,  and saves it to PDF.
    $oExcelBook = _Excel_BookOpen($oExcelApp, $dirSuccessfulJobs & "\" & $JobNum & "\Weight Sheet.xls")
    _Excel_Export($oExcelApp, $oExcelBook, $dirSuccessfulJobs & "\" & $JobNum & "\Weight Sheet.pdf", $xlTypePDF)
    _Excel_BookClose($oExcelBook, True)
    
    ;Exits Excel
    _Excel_Close($oExcelApp)
    
    ;Delete the Prebill.xls and Weight Sheet.xls files from _Successful.
    FileDelete($dirSuccessfulJobs & "\" & $JobNum & "\Prebill.xls")
    Sleep($microDelay)
    FileDelete($dirSuccessfulJobs & "\" & $JobNum & "\Weight Sheet.xls")
    
    ;Combine PDFs
    $AcrobatApp = ObjCreate("AcroExch.App")
    $AcrobatAVDoc = ObjCreate("AcroExch.AVDoc")
    $AcrobatPDDoc = ObjCreate("AcroExch.PDDoc")
    $AcrobatPDDoc.Create
    $AcrobatJSO = $AcrobatPDDoc.GetJSObject
    $AcrobatApp.Hide
    $AcrobatJSO.AutoItCombinePDFs(StringReplace($dirSuccessfulJobs & "\" & $JobNum, "\", "\\"))

    Sleep($shortDelay)
    $AcrobatApp.CloseAllDocs
    $AcrobatApp.Exit

    ;Closes the Acrobat process left behind from the OLE automation used to combine the PDFs.
    ProcessClose("Acrobat.exe")
    ProcessWaitClose("Acrobat.exe")
    
    ;Get the page count from Paperwork.pdf
    $AcrobatApp = ObjCreate("AcroExch.App")
    $AcrobatAVDoc = ObjCreate("AcroExch.AVDoc")
    $AcrobatAVDoc.Open($dirSuccessfulJobs & "\" & $JobNum & "\Paperwork.pdf", "")
    $AcrobatPDDoc = $AcrobatAVDoc.GetPDDoc
    $AcrobatJSO = $AcrobatPDDoc.GetJSObject
    
    $PaperPageCount = $AcrobatJSO.numPages

    Sleep($shortDelay)
    $AcrobatApp.CloseAllDocs
    $AcrobatApp.Exit

    ;Closes the Acrobat process left behind from the OLE automation used to run the javascript programs..
    ProcessClose("Acrobat.exe")
    ProcessWaitClose("Acrobat.exe")
    
    ;Get the page count from Tags.pdf
    $AcrobatApp = ObjCreate("AcroExch.App")
    $AcrobatAVDoc = ObjCreate("AcroExch.AVDoc")
    $AcrobatAVDoc.Open($dirSuccessfulJobs & "\" & $JobNum & "\Tags.pdf", "")
    $AcrobatPDDoc = $AcrobatAVDoc.GetPDDoc
    $AcrobatJSO = $AcrobatPDDoc.GetJSObject
    
    $TagPageCount = $AcrobatJSO.numPages

    Sleep($shortDelay)
    $AcrobatApp.CloseAllDocs
    $AcrobatApp.Exit

    ;Closes the Acrobat process left behind from the OLE automation used to run the javascript programs..
    ProcessClose("Acrobat.exe")
    ProcessWaitClose("Acrobat.exe")
    
    ;Now that PDFs have been combined, remove the left over individual copies.
    FileDelete($dirSuccessfulJobs & "\" & $JobNum & "\3602 First Page.pdf")
    FileDelete($dirSuccessfulJobs & "\" & $JobNum & "\Facing Slips.pdf")
    FileDelete($dirSuccessfulJobs & "\" & $JobNum & "\Job Setup Report.pdf")
    FileDelete($dirSuccessfulJobs & "\" & $JobNum & "\Job Ticket.pdf")
    FileDelete($dirSuccessfulJobs & "\" & $JobNum & "\Label Layout Report.pdf")
    FileDelete($dirSuccessfulJobs & "\" & $JobNum & "\Prebill.pdf")
    FileDelete($dirSuccessfulJobs & "\" & $JobNum & "\Presort Production Report.pdf")
    FileDelete($dirSuccessfulJobs & "\" & $JobNum & "\PS Form 3602-R.pdf")
    FileDelete($dirSuccessfulJobs & "\" & $JobNum & "\PS Form 8125.pdf")
    FileDelete($dirSuccessfulJobs & "\" & $JobNum & "\Tray Tags.pdf")
    FileDelete($dirSuccessfulJobs & "\" & $JobNum & "\Weight Sheet.pdf")

    #EndRegion
    
    ;Create info.txt for the printing operation (includes customer, regular page count, and tag page count).
    $hFileOpen = FileOpen($dirSuccessfulJobs & "\" & $JobNum & "\info.txt", 1)
    FileWriteLine($hFileOpen, $PizzaPlace)
    FileWriteLine($hFileOpen, $PaperPageCount)
    FileWriteLine($hFileOpen, $TagPageCount)
    FileClose($hFileOpen)
    
    ;Write Event Log Entry for successful completion.
    WriteToEventLog($JobNum, "Job Processing Complete....", "Success")
    
    ;Close left over idling Adobe Distiller instances.
    Do
        ProcessClose("acrodist.exe")
    Until Not ProcessExists("acrodist.exe")
    
    ;Reset all job variables by calling a function.
    InitializeVariables()
    Sleep($shortDelay)

Next
#EndRegion

; POST BATCH PROCESSING
#Region

;Remove "PermitTableExport.txt" - fresh copy will be created next run.
If FileExists($dirPermitTableExport & "\PermitTableExport.txt") Then
    FileDelete($dirPermitTableExport & "\PermitTableExport.txt")
EndIf

;Remove "Permit.csv" - fresh copy will be created next run.
If FileExists($dirPermitTableExport & "\Permit.csv") Then
    FileDelete($dirPermitTableExport & "\Permit.csv")
EndIf

;Calculate Run Time.
$RunTimeInMilliseconds = TimerDiff($hTimer)
$TimerHours = Floor($RunTimeInMilliseconds / (60000 * 60))
$TimerMinutes = Floor(($RunTimeInMilliseconds - ($TimerHours * (60000 * 60))) / 60000)
$TimerSeconds = Ceiling(($RunTimeInMilliseconds - ($TimerHours * (60000 * 60)) -($TimerMinutes * 60000)) / 1000)

;Write completion info to the event log.
WriteToEventLog("FINISHED", "Script completed operation.  Program Run Time:   " & $TimerHours & " Hours, " & $TimerMinutes & " Minutes, and " & $TimerSeconds & " Seconds", "Success")

;Display Timer
MsgBox(0, "Program Run Time", $TimerHours & " Hours, " & $TimerMinutes & " Minutes, and " & $TimerSeconds & " Seconds!")

#EndRegion

; FUNCTION - CONVERT PERMIT TABLE EXPORT TEXT TO CSV
#Region
Func ConvertPermitTextToCSV()
    
    Local $hPermitCSV = ""
    Local $hPermitExport = ""
    Local $arrRegExCompanies = ""
    Local $arrRegExIdentifiers = ""
    Local $sPermitRead = ""

    ;Read entire permit text file to a string.
    $hPermitExport = FileOpen($dirPermitTableExport & "\PermitTableExport.txt", 0)
    $sPermitRead = FileRead($hPermitExport)
    FileClose($hPermitExport)

    ;Delete Permit.csv if it already exists.
    If FileExists($dirPermitTableExport & "\Permit.csv") Then FileDelete($dirPermitTableExport & "\Permit.csv")

    ;Open a new file to parse into.
    $hPermitCSV = FileOpen($dirPermitTableExport & "\Permit.csv", 1)

    $arrRegExCompanies = StringRegExp($sPermitRead, "Company\s+\:\s(.*)[\r\n]", 3)
    $arrRegExIdentifiers = StringRegExp($sPermitRead, "Identifier\s+\:\s(.*)\s", 3)

    ;Write the header line.
    FileWriteLine($hPermitCSV, """Company"",""Identifier""")

    For $i = 0 To UBound($arrRegExCompanies) - 1
        FileWriteLine($hPermitCSV, """" & $arrRegExCompanies[$i] & """,""" & $arrRegExIdentifiers[$i] & """")
    Next

    FileClose($hPermitCSV)
    
EndFunc
#EndRegion

; FUNCTION - CLOSE JOB SPECIFIC WINDOWS TO RESET FOR NEXT JOB
#Region
Func CloseAllJobWindows()
    
    Local $arrAllHandles = ""
    $arrAllHandles = WinList()

    For $iCount = 1 To $arrAllHandles[0][0]
        
        If BitAND(WinGetState($arrAllHandles[$iCount][1]), 2) And _
           $arrAllHandles[$iCount][0] <> "" And _
           $arrAllHandles[$iCount][0] <> "Program Manager" And _
           $arrAllHandles[$iCount][0] <> "Start" Then
            
            If $arrAllHandles[$iCount][1] <> $hBCCWnd And _
               $arrAllHandles[$iCount][1] <> $hBCCBGWnd And _
               $arrAllHandles[$iCount][1] <> $hAutoItWnd Then
                    WinClose($arrAllHandles[$iCount][1])
                    Sleep($shortDelay)
            EndIf
               
        EndIf
           
    Next
    
EndFunc
#EndRegion

; FUNCTION - WRITE TO EVENT LOG
#Region
Func WriteToEventLog($sJobTicket, $sEventDesc, $sEventAction)
    
    Local $hLogFile = ""
    Local $arrSplit = ""
    Local $sDate = ""
    Local $sTime = ""
    Local $sLogEntry = ""
    
    $arrSplit = StringSplit(_NowCalc(), "/")
    $sDate = $arrSplit[2] & "/" & StringLeft($arrSplit[3], 2) & "/" & $arrSplit[1]

    $arrSplit = StringSplit(_NowCalc(), " ")
    $sTime = $arrSplit[2] & StringRight(_NowTime(), 3)
    
    $hLogFile = FileOpen($dirEventLog & "\" & $sLogName, 1)
    $sLogEntry = $sDate & " " & $sTime & "   " & StringFormat("%-12s", $sJobTicket) & "- DESC: " & StringFormat("%-90s", $sEventDesc) & "ACTION: " & $sEventAction
    FileWriteLine($hLogFile, $sLogEntry)
    FileClose($hLogFile)
    
EndFunc
#EndRegion

; FUNCTION - INITIALIZE VARIABLES
#Region
Func InitializeVariables()
    
    $listName = "Max_Test"
    $JobNum = ""
    $PizzaPlace = ""
    $GrandeID = ""
    $MailDate = ""
    $PieceCount = ""
    $BeginningQty = ""
    $PieceType = ""
    $TicketPieceHeight = ""
    $TicketPieceWidth = ""
    $PieceLength = ""
    $PieceHeight = ""
    $PieceWeight = ""
    $PieceThickness = ""
    $PieceSampleQty = ""
    $EntryOfficeLine1 = ""
    $EntryOfficeLine2 = ""
    $EntryOfficeLine3 = ""
    $EntryOfficePhone = ""
    $arrZipCodes = ""
    $arrRegExFound = ""
    $arrDateParts = ""  
    $folderArray = ""
    $fullJobPath = ""
    $JobFolder = ""
    $CustFolder = ""
    $PermitNameFind = ""
    $PrebillFolder = ""
    $listFile = ""
    $LabelOutputName = ""
    $FileNameOf8125 = ""
    $ControlText = ""
    $MailDateFormatted = ""
    $WaitingFlag = False
    $hFileOpen = ""
    $sFileRead = ""
    $AcrobatApp = ""
    $AcrobatAVDoc = ""
    $AcrobatPDDoc = ""
    $AcrobatJSO = ""
    $PaperPageCount = ""
    $TagPageCount = ""
    $AcroPID = ""
    $oExcelApp = ""
    $oExcelBook = ""
    $hWnd = ""
    $sPrevValue = ""
    $sTempText = ""
    
EndFunc
#EndRegion

; FUNCTION PAUSE
#Region
Func TogglePause()
    $Paused = NOT $Paused
    While $Paused
        sleep(100)
        ToolTip("**** SCRIPT PAUSED ****",0,0, "Script Status", 1)
    WEnd
    ToolTip("")
EndFunc
#EndRegion

; FUNCTION TERMINATE
#Region
Func Terminate()
    Exit 0
EndFunc
#EndRegion

 

Link to comment
Share on other sites

 

This maybe can help a little

Questions:

Why you automate Acrobat via Window. ?
Can't you just use only COM object ?

 

Btw.
Long ago, I automate Adobe Acrobat Reader window.
It worked well with AAR 9.x, but automation of windows in the AAR 10.x and 11.x, was very annoying.

 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

Way at the bottom I use some of that with code like this:

;Combine PDFs
    $AcrobatApp = ObjCreate("AcroExch.App")
    $AcrobatAVDoc = ObjCreate("AcroExch.AVDoc")
    $AcrobatPDDoc = ObjCreate("AcroExch.PDDoc")
    $AcrobatPDDoc.Create
    $AcrobatJSO = $AcrobatPDDoc.GetJSObject
    $AcrobatApp.Hide
    $AcrobatJSO.AutoItCombinePDFs(StringReplace($dirSuccessfulJobs & "\" & $JobNum, "\", "\\"))

    Sleep($shortDelay)
    $AcrobatApp.CloseAllDocs
    $AcrobatApp.Exit

    ;Closes the Acrobat process left behind from the OLE automation used to combine the PDFs.
    ProcessClose("Acrobat.exe")
    ProcessWaitClose("Acrobat.exe")

The mailing software prints to the PDF Printer so I just need to put in a dynamic path when the save as box comes up.  Thats the main reason for Acrobat window automation.  Thank you for the resource you provided, I'll definitely check it out!

Link to comment
Share on other sites

Which One PDF Printer ?

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

The code above is just an example of Acrobat automation not using the GUI.  In the mailing software you can set the default printer and I'm using the basic "Adobe PDF" printer that comes with Acrobat XI Standard.  I WinWait for the Save As window, then WinActivate it and ControlSetText the full path into the filename box and ControlClick the save button.  Since the script batch processes jobs, this allows me to save to the current job in the batch using a constructed path.

Link to comment
Share on other sites

I never use "Adobe PDF" printer 

but found this

 

As I assume you can set the printer to save PDF without view results. 
Just setup Output Folder.

For ... to ...

Delete all old PDF in OutputFolder

Initialize printing, wait for any new PDF file in Output folder, check if this new PDF file is not used (saved at all) 

do your further stuff...

Next

 

EDIT:

Btw.... is it commercial or only internall project ? I ask because you can also use PDFCreator (look in my signature).

 

Edited by mLipok

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

The app "BCC Mail Manager Full Service" is normal Win32 API ? or .NET eventually Delphi ... other dev.env ... ?

Why you are using 
http://www.nirsoft.net/utils/sysexp.html

I think if you can do it all in native AutoIt or with some UDF.

 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

Also try to use A-PDF Text Extractor Command Line

http://www.a-pdf.com/text/cmd.htm

edit:
or other like mudraw.exe from: http://mupdf.com/

Edited by mLipok

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

Thank you for all of your input mLipok, I appreciate it.

This is sort of a pet project at work since this company has no dedicated programmers.   I only work on it in my spare time, but once I "unveiled" the prototype management wanted it in full production asap.  I'm not using A-PDF Text Extractor Command Line simply because it cost money and the GUI version is doing the trick.  BCC Mail Manager uses A LOT of non-standard windows controls, I use NirSoft sysexporter because there is an internal database in the software that gets loaded into a listview control and I need to dump that to .csv in order to search on an ID and grab the name of individual entries.

Link to comment
Share on other sites

In BCC MailManager this ListView is normal Win32 API ? can you see this list view Class with https://www.autoitscript.com/autoit3/docs/intro/au3spy.htm

?

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...