Move matching logic to R; reformatting of melt.cpp