full working sequential version