this method is very complex and nested very deep. Is this necessary?