combined logic from raw and from cpaste...now works like a charm