Fixed memory leak and bad index issues.