/* VGAlib version 1.2 - (c) 1993 Tommy Frandsen 		   */
/*								   */
/* This library is free software; you can redistribute it and/or   */
/* modify it without any restrictions. This library is distributed */
/* in the hope that it will be useful, but without any warranty.   */

/* Multi-chipset support Copyright 1993 Harm Hanemaayer */
/* partially copyrighted (C) 1993 by Hartmut Schirmer */

#include <stdio.h>
#include "vga.h"
#include "libvga.h"


static inline void read_write(char *p)
{
  ++(*p); 
}

int vga_drawpixel(int x, int y)
{
    unsigned long offset;

    if (MODEX) goto modeX;
    switch (CI.colors) {
      case 2 :
      case 16:
	    /* set up video page */
	    offset = y*CI.xbytes + (x>>3);
            vga_setpage(offset>>16);
	    offset &= 0xffff;

	    /* select bit */
	    port_out(8, GRA_I);
	    port_out(0x80 >> (x & 7), GRA_D);   

            /* read into latch and write dummy back */
	    read_write(GM+offset);
            break;
      case 256 :
	    switch (CM) {
		case G320x240x256:
		case G320x400x256:
		case G360x480x256:
modeX:
		    /* select plane */ 
		    port_out(0x02, SEQ_I); 
    		    port_out(1 << (x & 3), SEQ_D);
	            /* write color to pixel */
		    GM[y*CI.xbytes + (x>>2)] = COL;  
	            return 0;
	    }
	    offset = y*CI.xbytes+x; 

	    /* select segment */
	    vga_setpage(offset >> 16);

            /* write color to pixel */
	    GM[offset & 0xFFFF] = COL;  
            break;
        case 32768:
        case 65536:
            offset = y * CI.xbytes + x * 2;
            vga_setpage(offset >> 16);
            *(unsigned short *)(GM + (offset & 0xffff)) = COL;
            break;
        case 1<<24 :
        	offset = y * CI.xbytes + x * 3;
        	vga_setpage(offset >> 16);
        	switch (offset & 0xffff) {
        		case 0xfffe :
        			*(unsigned short *)(GM+0xfffe) = COL;
        			vga_setpage((offset >> 16) + 1);
        			GM[0] = COL >> 16;
        			break; 
        		case 0xffff :
        			GM[0xffff] = COL;
        			vga_setpage((offset >> 16) + 1);
        			*(unsigned short *)(GM) = COL>>8;
        			break;
        		default :
				offset &= 0xffff;
        			*(unsigned short *)(GM+offset) = COL;
        			GM[offset+2] = COL>>16;
        			break;
        	}
        	break;
    }

    return 0;
}

