Add threading, collapse external functions into main file