Finish cost() function and fixed casting issues