cleanup code and add sorting