Several amendments to the code. Now it works as it should.