Fixes bugs and improves implementation