refactor code for method f and g with using ip and sp as global variable