Working code. with major fixes