Your Key_Cnt variable increments inside the IF condition and therefore, placing the SEROUT statement before the IF works correctly.

You need to investigate that IF statement with this in mind.