Fix potentially unclosed streams

Simplified some file checks
Code formatting and added copyright