Added encoding support and did some general code cleanup