Changed lots of loops so that X is outer and Y is inner loop