Code simplified for publication