refactor functions code to allow save to file