program logic optimized and simplified
(unneeded cicles deleted)