Fixed #16383

This code needs comments.
Also, seems like we can combine the if statements instead of nesting them?