Fix bugs and added some flexibility