reduce memory usage and fix seg fault