the main parts of lab5, still need error bounds checking