Changed subfunction definitions to closures, because they can be nested