Fix a segfault.
Correctly deal with different modes of operation
Include cstdio for building on ubuntu 12.04