I have tried to demonstrate below in the sample code what I am trying to do. The subroutine and function, which the problem arises from them, are depicted below: