Just try using && instead of || in the second for loop.I think that should solve a major part of the problem.