Added more intelligent space detection for layer attaching
Utilized intelligent space detection
Removed redundant code