fixed broken code and reoptimized
attempted elimination of inner loops