Included modifications from Alex. Figures are now closed after plotting
to try and solve the memory leak.