refactoring code. Need to bug test it