Restructure and reformat code