working version. needs cleenup and tests