working version with too much debug printout