Major Refactoring Changes And Added Code To Handle Invalid Queries