working version before chart algorithm