start porting doTrial function