added safety checks, fixed potential bug