/*  ENVI_BSQ_2_IDL_BIP by Ch Iossif @ 11/2005   */
/*  Starts here...  */
#include <stdio.h>
#include <stdlib.h>

void error(char *);
void report(char *);

int main(int argc, char **argv){
    FILE *fpin, *fpout;
    char buff[BUFSIZ], *imb;
    int rows, cols, band, pixs;
    register int r, c, b;

    if (argc!=7){
        error("Use me with the following command line data:\n\
        ..>ENVI_BSQ_2_IDL_BIP InputFileName OutputFileName Rows Columns Bands PixelSize");
    }
    if ((fpin=fopen(argv[1],"rb"))==NULL){
        sprintf(buff,"Bad input file name: <%s>.",argv[1]);
        error(buff);
        }
    if ((fpout=fopen(argv[2],"wb"))==NULL){
        sprintf(buff,"Bad output file name: <%s>.",argv[2]);
        error(buff);
        }
    rows=atoi(argv[3]);
    cols=atoi(argv[4]);
    band=atoi(argv[5]);
    pixs=atoi(argv[6]);
    if (rows<1 || cols<1 || band<1 ||pixs<1){
        error("Rows Columns Bands PixelSize must be positive integer.");
    }
    if (rows*cols*band*pixs!=band*pixs*rows*cols){
        report("Rows Columns Bands PixelSize are too big, aren\'t they\?");
    }

    if ((imb=(char *)malloc(pixs))==NULL){
        error("Not enough memory allocated.");
    }

    for (r=0;r<rows;r++){
        for (c=0;c<cols;c++){
            for (b=0;b<band;b++){
                if (fseek(fpin, (long)((b*rows+r)*cols+c)*pixs, SEEK_SET)){
                    sprintf(buff,"Bad file seek <%d,%d,%d> at input file.",r,c,b);
                    error(buff);
                }
                if (fread(imb, pixs, 1, fpin)!=1){
                    error("Bad file read at input file.");
                }
                if (fwrite(imb, pixs, 1, fpout)!=1){
                    error("Bad file write at input file.");
                }
            }
        }
    }

    fclose(fpin);
    fclose(fpout);
    free(imb);

    printf("\nENVI_BSQ_2_IDL_BIP by Ch Iossif @ 11/2005.\n\n");
	return 0;
}

void error(char *s){
    printf("ENVI_BSQ_2_IDL_BIP reports an error: %s\n\n",s);
    printf("ENVI_BSQ_2_IDL_BIP by Ch Iossif @ 11/2005.\n\n");
    exit(1);
}

void report(char *s){
    printf("ENVI_BSQ_2_IDL_BIP reports a warning: %s.\n",s);
}
/*  ...and here is end.    */
/*  ENVI_BSQ_2_IDL_BIP by Ch Iossif @ 11/2005   */

