Fix loops processing
Various code improvements