This if looks pretty fragile. Not sure what's a better way to do it though.