fixing errors and reorder code