Fixed triangle function to give correct results