Improved structure matching function