Prevent crashes

Added some checks that prevent crashes (access violation and invalid type cast) .
Also some line trimming.