Moved much of main into separate file