Fixed missing reference bug and cleaned up code