Fixed some bugs and improved robustness of apply