Here is some code for your project

It will resolves many bugs !