trying to speed up
optimized with some continue and break statements