Functions rewritten and fixed