Remove some code duplicate and cleanup