direct translation from matlab -- need to clean up