upto 4 dimensions with cleaner code