Fix bug #66 and code refatoring