Adds workaround for retrieving records in chunks, improves and optimizes code