// © Roman Vernik (Usethics), Russia

with (app) {
	try {
		for (i = 0; i < selection.length; i++) {
			newBounds = selection[i].geometricBounds;
			gridStepH = activeDocument.gridPreferences.horizontalGridlineDivision / activeDocument.gridPreferences.horizontalGridSubdivision;
			gridStepV = activeDocument.gridPreferences.verticalGridlineDivision / activeDocument.gridPreferences.verticalGridSubdivision;
			
			delta0 = mod(newBounds[0], gridStepV);
			delta2 = mod(newBounds[2], gridStepV);
			delta1 = mod(newBounds[1], gridStepH);
			delta3 = mod(newBounds[3], gridStepH);
	
			newBounds[0]  = newBounds[0] - delta0;
			newBounds[2]  = newBounds[2] - delta2;
			if (newBounds[2] == newBounds[0]) {
				if (delta0 * delta0 < delta2 * delta2) {
					newBounds[2]  = newBounds[2] + gridStepV;
				} else {
					newBounds[0]  = newBounds[0]  - gridStepV;
				}
			}
		
			newBounds[1]  = newBounds[1] - delta1;
			newBounds[3]  = newBounds[3] - delta3;
			if (newBounds[3] == newBounds[1]) {
				if (delta1 * delta1 < delta3 * delta3) {
					newBounds[3]  = newBounds[3] + gridStepH;
				} else {
					newBounds[1]  = newBounds[1]  - gridStepH;
				}
			}
		
			selection[i].geometricBounds = newBounds;
		}
	} catch(e) {}
}

function mod(division, divider) {
	while (division > 0) {
		division = division - divider;
	}
	if (division > -divider / 2)
		return division
	else
		return division + divider;
}