added function for detect encoding, bugs fixed