The following script demonstrates some lesser known AppleScript syntax tricks.
-- address InDesign version independent, by ID.
-- works like an implicit tell application within the methods
propertyparent : applicationid "com.adobe.indesign"
-- help the applescript compiler
using terms fromapplication "Adobe InDesign CS6"
-- You could isolate other code blocks into similar "on …" handlers.
ondeleteUnusedMasterSpreads(aDoc)
tellaDoc
-- build an ID list
setusedMasterIDstoidofapplied masterofeverypage
-- use "whose" to filter
-- store the whole expression as "reference"
setunusedMasterSpreadstoa referenceto (master spreadswhoseidis notinusedMasterIDs)
-- unfortunately, delete does not ignore the empty list
ifexistsunusedMasterSpreadsthen
deleteunusedMasterSpreads
endif
endtell-- aDoc
enddeleteUnusedMasterSpreads
onrun
deleteUnusedMasterSpreads(document 1)
endrun
endusing terms from