these while loops are not very elegant, this can all be done with vector operations.