Re-factored and cleaned-up