Improved and generalized some code