Add test for apply_mask and fix issues