First of all, this code has a lot of exploits, you shouldn't use it as it is because it is very unsafe, see the post of qwerty for an explanation:
https://forums.mirc.com/ubbthreads.php/topics/198734/1About the deleting part, you should debug the code to find out at which point it's not behaving like you're expecting it to.