Arduino is one of the most popular embedded platform and majority of students and hobbyists are using it for their projects. However very few people pay attention towards the code optimization. For the successful and flawless operation of any project, its code should be optimized. So if your project is showing some abnormal behavior some times and behaving ridiculously under some conditions then it means its code need some optimization!
I'll do the code optimization by:
1. Removing un-necessary statements
2. Dividing the code into separate modules/functions
3. Declaring/re-declaring the variables in their proper scope
4. Tweaking the overall code by optimized short statements
5. Doing proper indentation of the code
I'll also give your suggestions for the further improvements related to your project.