significantly upgraded I/O and added sampling flag