Moved data extraction loop into its own function for resuse (currently bugged)