Fixed memory issues

- clearing index cache periodically, so that it doesn't grow too much
- fixed memory leaks
- less copying

Change-Id: I1483a2f4855a7faa751dd8ed7ee050b17a0c7204