fixed bug in flatMap and beefed up tests