started porting beej's code