Replaced two loops with fancy indexing for huge performance increase