working version and minor cleanup