add condition to prevent invalid index

When a line consists of white spaces only, the while loop will eventually produce a negative value to be used as the index.