optimizing algorithm, getting rid of prints, etc