#include "rslib.h"
#pragma hdrstop

/** file streams throw exceptions, other streams just set their 'error' flag */
Stream* OpenStream(const char* type,xdb* error)
{
 Stream* ret = NULL;
 if (type == NULL) return NULL;

 const char* name = strstr(type,"://");
 if (!name) return NULL;
 name += 3;

 if (type[0] == 0) return NULL;
 try {

#ifndef NO_INET_STREAM
 if (!strnicmp(type,"http://",7)) ret = new InternetStream(type);

 if (!strnicmp(type,"inet://",7))
 {
  TStr host(type+7);
  char *port = strchr(host,':');
  if (port)
   *port++=0;
  ret = new InternetStream(host,port ? atoi(port) : 80);
 }
#endif

#ifndef NO_COMM_STREAM
 else if (!strnicmp(type,"com",3)) ret = new CommStream(TStr(type,4),name);
#endif

#ifndef NO_MEMORY_STREAM
 else if (!strnicmp(type,"text",4))
   {
    ret = new MemoryStream(atoi(name));
// use the ByteStream constructor only if you know that the pointer won't disappear
//    Stream* s = new ByteStream((char*)name);
//    s->Type = Stream::ReadOnly;
//    return s;
  }
 else if (!strnicmp(type,"temp",4)) ret = new MemoryStream(atoi(name));
#endif

#ifndef NO_FILE_STREAM
 else if (!strnicmp(type,"file",4)) ret = new FileStream(name);
#endif
 }
 catch (xdb& x)
  {
   if (error) *error = x;
  }
 catch(...)
  {
   return NULL;
  }

 if (!ret) return NULL;
 if (ret->error) {if (error) *error = *ret->error; delete ret; return NULL;}
 if (ret->Type == Stream::NotOpen) {delete ret; return NULL;}

 return ret;
}


