revised code for performance; removed redundancies