added many comments - hopefully understandable