You are printing ltr and val even when started and ended are not true.
Delete code not being used. Don't just comment it out.
Use the Tools + Auto Format... menu item to properly indent your code.
Read the code; try to understand what it is doing. Don't just stick new stuff in anywhere.