Splitting function into smaller chunks... removed unused globals