You can store the count at tile[tilesAmount-1]
at data parse start:
tiles[tilesAmount-1] = tilesAmount - 2;
........

at tile:
--tiles[tilesAmount];
tiles[tilesAmount - 3 - tiles[tilesAmount-1]] =  gid;

sample
we have 5 elements
t[0]  t[1]  t[2]  t[3]  t[4] 
start t[every] = -1   count=5  t[4] = 3

index 0: t[4]=2  t[5 - 3 - t[4]] -> t[0] = gid0
index 1: t[4]=1  t[5 - 3 - t[4]] -> t[1] = gid1
index 2: t[4]=0  t[5 - 3 - t[4]] -> t[2] = gid2
index 3: t[4]=-1 t[5 - 3 - t[4]] -> t[3] = gid3
index 4: t[4]=-2 t[5 - 3 - t[4]] -> t[4] = gid4

When layer parse end, you can test t[count-2],  if  it's -1, you change the t[count-1] to -1, if it's not -1, the t[count-1] is -1 or the gid number, so you can just leave it.