fixes and cleanup; restored end loop