Moved system calls to internal function, moved code around