finished first version, to be debugged