merged with mark's code