Code Cleaning and added conditional querying