At least now the internal table has correct line items..
Also can you check if which WRITE_FORM it is throwing the error and at which stage.
As for counter please first reset it before you start counting maybe in HEADER_TEXT
/: DEFINE &SAPSCRIPT_COUNTER_1& = 1
within the HEADER_LINE
/: &SAPSCRIPT_COUNTER_1(+)&
/:IF &SAPSCRIPT_COUNTER_1& =20
/: ULINE
/: ENDIF