WIP, refactored and fixed
Refactored nncostfunction