Moved long code to functions. trivial changes
Changed the way to get min load thread