Finished refactoring Python and SQL code