fixing some bugs and making it much more flexible