working after slight optimizations in while()