fixing sort bug, moving out calculate functions