Some changes taken from steipetes repo