Ah! Now it works better!
But there a new problem 
If I go up or left, I'm on the other side...
Do you understand me? 
Oh sorry, I found the problem and corrected it. I needed to check if the position became negative one before performing the min function. Check the code again, hopefully it should work now.