solved from Joe's algorhythm