working version before adding stop condition