Some comments on issues to resolve. I think you should refactor this code entirely.