reordered code to fix null pointer exception