cleaned up code, still too slow though