restructured code for faster queries