algorithm improvements and cleanup