Without looking to closely at your code, the first thing I see is the reason your variables are resetting to zero values. This is by design, if you want to retain the value of those variables you have a couple of options, move them out of the current subroutine to the top of the current module...