consolidated, full working version