Complete functional of program.

Also some refactorings.