implement loop and do some other improvements