refactored #triangle function