some bug fixes copied from prototype version