You'll find the code a lot easier to debug if you indent it correctly.

What does it do wrong?