Fixed some warnings; added some comments. Did some code deduplication.