Cleaned and commented; needs testing/verification