modified to n dim

not tested