Triggering samples on the keyboard only on the beat so it is never out of time

Hi
I have created a step sequencer using matrix ctrl. I have then linked it up so that samples and MIDI are linked to my midi keyboard on two seperate octaves.
I was just wondering if anyone knows anyideas on how have it so that it will never go out of time when i hit on the keyboard if it is playing along with a pattern or otherwise.

This is what i have so far. Any help will be much appreciated.

— Pasted Max Patch, click to expand. —

Copy all of the following text. Then, in Max, select New From Clipboard.

first, determine your smallest quantization time (sixteenth, eighth, etc.)–how exact do you want "in time" to be. use a metro that continually bangs at that rate, which might be very fast. You can also use [counter] –> [%4] –> [sel 0] to use every 4th pulse instead of every one, etc. If you change the [metro] rate you’ll need to be sure it starts its new rate at the right time, so probably a [trigger 1 i 0] where 0 stops it, i sets the new msec rate, then 1 starts it again, or tie it somehow to the [matrixctrl] counter. (that could be used for the quantization too, actually.)

then, instead of your input (keyboard) notes actually sounding right away, store the note(s) in [i] or a message box, and they only get played when you get your overall "timing" bang from the main metro. Of course, this only helps with early notes.