Some fixes and improvements copied form phantom-one's work