Counter Gateway Tag Change Script Issue

Hello,
I have the following Gateway Tag Change Script on a tag “Counter”:
‘’’ if not initialChange:

    currentValue = event.getCurrentValue().getValue()
    previousValue = event.getPreviousValue().getValue()

    if previousValue > currentValue or currentValue == 0:

          sc = system.tag.readBlocking(["[default]UNI_Room12/StartCount12"])[0].value
          brb = system.tag.readBlocking(["[default]UNI_Room12/BatchResetBit12"])[0].value
          pv = system.tag.readBlocking(["[default]UNI_Room12/PreviousBatchCount12"])[0].value
          pv = pv + previousValue

          tagPaths = ['[default]/PreviousBatchCount', '[default]/BatchResetBit']
          values = [pv, brb+1]
          system.tag.writeBlocking(tagPaths,values)

    if currentValue > previousValue or previousValue == currentValue:

         sc = system.tag.readBlocking(["[default]UNI_Room12/StartCount12"])[0].value
         cc = system.tag.readBlocking(["[default]UNI_Room12/Counter"])[0].value
         pv = system.tag.readBlocking(["[default]UNI_Room12/PreviousBatchCount12"])[0].value
         total = pv - sc + cc
         system.tag.writeBlocking(["[default]Total"],[total])'''

The script works well, however randomly I have the following problem:
as you can see on the attachment, though the previous value of the counter (65292) is not greater than the current value (66848), the value of the brb variable goes from 0 to 1, i.e. the first part of the script was executed. Any idea why?