fixed algorithm and errors