fully working code. Caveates re: mem usage added