code for plotting and fix bugs