working version with minor problem leading to null pointer