added error listener, correct some bugs and cleanup