Made the code work with any number, needs a few optimizations though