Updated with mightyguava's improvements.